diff --git a/bce-sdk-go/.gitignore b/bce-sdk-go/.gitignore new file mode 100644 index 0000000..bf20aac --- /dev/null +++ b/bce-sdk-go/.gitignore @@ -0,0 +1,16 @@ +# Binaries for programs and plugins +*.exe +*.dll +*.so +*.dylib + +# Test binary, build with `go test -c` +*.test + +# Output of the go coverage tool, specifically when used with LiteIDE +*.out + +# Project-local glide cache, RE: https://github.com/Masterminds/glide/issues/736 +.glide/ + +.idea \ No newline at end of file diff --git a/bce-sdk-go/LICENSE b/bce-sdk-go/LICENSE new file mode 100644 index 0000000..f433b1a --- /dev/null +++ b/bce-sdk-go/LICENSE @@ -0,0 +1,177 @@ + + 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 diff --git a/bce-sdk-go/README.md b/bce-sdk-go/README.md new file mode 100644 index 0000000..c10319f --- /dev/null +++ b/bce-sdk-go/README.md @@ -0,0 +1,284 @@ +# GO SDK 文档 + +# 概述 + +本文档主要介绍百度云Go语言版的开发者工具包(SDK),用户可基于该SDK使用Go语言接入百度云的各项产品(详见支持产品列表)。SDK封装了便捷的调用接口,保持了多种编程语言版的使用方式、调用接口相似,提供了统一的错误码和返回格式,方便开发者调试。 + +# 安装SDK工具包 + +## 运行环境 + +GO SDK可以在go1.3及以上环境下运行。 + +## 安装SDK + +**直接从github下载** + +使用`go get`工具从github进行下载: + +```shell +go get github.com/baidubce/bce-sdk-go +``` + +**SDK目录结构** + +```text +bce-sdk-go +|--auth //BCE签名和权限认证 +|--bce //BCE公用基础组件 +|--http //BCE的http通信模块 +|--services //BCE相关服务目录 +| |--appblb //应用型负载均衡服务目录 +| |--as //弹性伸缩 +| |--bbc //物理服务器 +| |--bcc //云服务器 +| |--bcm //云监控 +| |--bec //百度边缘计算 +| |--bie //百度智能边缘 +| |--bls //日志服务 +| |--bos //BOS服务目录 +| | |--bos_client.go //BOS客户端入口 +| | |--api //BOS相关API目录 +| | |--bucket.go //BOS的Bucket相关API实现 +| | |--object.go //BOS的Object相关API实现 +| | |--multipart.go //BOS的Multipart相关API实现 +| | |--module.go //BOS相关API的数据模型 +| | |--util.go //BOS相关API实现使用的工具 +| |--bvw //BVW服务目录 +| |--cce //容器引擎 +| |--cdn //内容分布网络 +| |--cert //SSL证书服务 +| |--cfc //函数计算 +| |--cfs //CFS文件存储服务 +| |--cfw //云防火墙 +| |--csn //云智能网 +| |--ddc //DDC数据库专属集群 +| |--dts //数据传输服务 +| |--eccr //容器镜像服务企业版 +| |--eip //弹性公网IP +| |--endpoint //SNIC服务网卡 +| |--eni //ENIC弹性网卡 +| |--esg //企业安全组 +| |--etGateway //专线网关 +| |--havip //高可用虚拟IP +| |--iam //身份管理 +| |--media //音视频处理MCP +| |--rds //云数据库 +| |--scs //SCS服务目录 +| |--sms //SMS服务目录 +| |--sts //STS服务目录 +| |--vca //VCA服务目录 +| |--vcr //VCR服务目录 +| |--vpc //私有网络 +| |--vpn //VPN网关 +| |--mms //多模态媒资检索目录 +|--util //BCE公用的工具实现 +``` + +## 卸载SDK + +预期卸载SDK时,删除下载的源码即可。 + +# 使用步骤 + +## 确认Endpoint + +在使用SDK之前,需确认您将接入的百度云产品的Endpoint(服务域名)。以百度对象存储产品为例,可阅读[BOS访问域名](https://cloud.baidu.com/doc/BOS/DevRef.html#BOS.E8.AE.BF.E9.97.AE.E5.9F.9F.E5.90.8D)的部分,理解Endpoint相关的概念。其他服务类似,需理解并确认对应服务的Endpoint。 + +## 创建Client对象 + +每种具体的服务都有一个`Client`对象,为开发者与对应的服务进行交互封装了一系列易用的方法。开发者可参考SDK中具体服务对应的目录下的说明文档使用相应的服务。 + +## 调用功能接口 + +开发者基于创建的对应服务的`Client`对象,即可调用相应的功能接口,使用百度云产品的功能。 + +## 示例 + +下面以百度云对象存储服务(BOS)为例,给出一个基本的使用示例,详细使用说明请参考各服务的详细说明文档。 + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bos" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := "", "" + + // BOS服务的Endpoint + ENDPOINT := "" + + // 创建BOS服务的Client + bosClient, err := bos.NewClient(AK, SK, ENDPOINT) + + // 创建Bucket + location, err := bosClient.PutBucket(""); err != nil { + if err != nil { + fmt.Println("create bucket failed:", err) + } + fmt.Println("create bucket success in", location) + + // 上传对象 + etag, err := bosClient.PutObjectFromFile("", "", "", nil) + if err != nil { + fmt.Println("upload file to BOS failed:", err) + } + fmt.Println("upload file to BOS success, etag = ", etag) +} +``` + +# 配置 + +## 使用HTTPS协议 + +该SDK支持使用HTTPS协议访问百度云的服务产品。要使用HTTPS协议,只需在您创建对应服务的`Client`对象时指定的Endpoint中指明使用https协议的域名即可,SDK会自动识别并使用HTTPS协议访问。 + +## 详细配置 + +开发者使用GO SDK时,创建的对应服务的`Client`对象,其导出字段`Config`提供如下参数以便支持详细配置: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +开发者可据此进行详细参数的配置,下面给出部分配置示例: + +```go +// client为某一种具体服务的`Client`对象 + +// 配置请求代理地址 +client.Config.ProxyUrl = "127.0.0.1:8080" + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 + +// 配置签名使用的HTTP请求头为`Host` +client.Config.SignOption.HeadersToSign = map[string]struct{}{"Host": struct{}{}} + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +# 错误处理 + +GO语言以error类型标识错误,定义了如下两种错误类型: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | BOS服务返回的错误 + +用户使用SDK调用各服务的相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误的详细信息进行处理。实例如下: + +```go +// bosClient 为已创建的BOS服务的Client对象 +bucketLocation, err := bosClient.PutBucket("test-bucket") +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +fmt.Println("create bucket success, bucket location:", bucketLocation) +``` + +## 客户端异常 + +客户端异常表示客户端尝试向百度云服务发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当服务端出现异常时,百度云服务端会返回给用户相应的错误信息,以便定位问题。每种服务端的异常需参考各服务的官网文档。 + +## SDK日志 + +GO SDK自行实现了支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +该日志模块无任何外部依赖,开发者使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用。可使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +```go +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the sdk") +``` + +# 支持产品列表 + +产品名称 | 产品缩写 | 导入路径 | 说明文档 +-----------|-----------|---------------------------------------------------|---------- +应用型负载均衡 | APPBLB | github.com/baidubce/bce-sdk-go/services/appblb | [APPBLB.md](./doc/APPBLB.md) +物理服务器 | BBC | github.com/baidubce/bce-sdk-go/services/bbc | [BBC.md](./doc/BBC.md) +云服务器 | BCC | github.com/baidubce/bce-sdk-go/services/bcc | [BCC.md](./doc/BCC.md) +云监控 | BCM | github.com/baidubce/bce-sdk-go/services/bcm | [BCM.md](./doc/BCM.md) +边缘计算节点 | BEC | github.com/baidubce/bce-sdk-go/services/bec |[BEC.md](./doc/BEC.md) +百度智能边缘 | BIE | github.com/baidubce/bce-sdk-go/services/bie | +负载均衡 | BLB | github.com/baidubce/bce-sdk-go/services/blb | [BLB.md](./doc/BLB.md) +日志服务 | BLS | github.com/baidubce/bce-sdk-go/services/bls | [BLS.md](./doc/BLS.md) +百度对象存储 | BOS | github.com/baidubce/bce-sdk-go/services/bos | [BOS.md](./doc/BOS.md) +百度视频创作分发平台 | BVW | github.com/baidubce/bce-sdk-go/services/bvw | [BVW.md](./doc/BVW.md) +容器引擎 | CCE | github.com/baidubce/bce-sdk-go/services/cce | [CCE.md](./doc/CCE.md) +内容分布网络 | CDN | github.com/baidubce/bce-sdk-go/services/cdn | [CDN.md](./doc/CDN.md) +SSL证书服务 | CERT | github.com/baidubce/bce-sdk-go/services/cert | [CERT.md](./doc/CERT.md) +函数计算 | CFC | github.com/baidubce/bce-sdk-go/services/cfc | [CFC.md](./doc/CFC.md) +文件存储服务 | CFS | github.com/baidubce/bce-sdk-go/services/cfs | [CFS.md](./doc/CFS.md) +云防火墙 | CFW | github.com/baidubce/bce-sdk-go/services/cfw | [CFW.md](./doc/CFW.md) +云智能网 | CSN | github.com/baidubce/bce-sdk-go/services/csn | [CSN.md](./doc/CSN.md) +文档服务 | DOC | github.com/baidubce/bce-sdk-go/services/doc | [DOC.md](./doc/DOC.md) +数据传输服务 | DTS | github.com/baidubce/bce-sdk-go/services/dts | [DTS.md](./doc/DTS.md) +容器镜像服务 企业版 | ECCR | github.com/baidubce/bce-sdk-go/services/eccr | [ECCR.md](./doc/ECCR.md) +弹性公网IP | EIP | github.com/baidubce/bce-sdk-go/services/eip | [EIP.md](./doc/EIP.md) +ENIC弹性网卡 | ENIC | github.com/baidubce/bce-sdk-go/services/eni | [ENIC.md](./doc/ENIC.md) +企业安全组 | ESG | github.com/baidubce/bce-sdk-go/services/esg | [ESG.md](./doc/ESG.md) +高可用虚拟IP | HAVIP | github.com/baidubce/bce-sdk-go/services/havip | [HAVIP.md](./doc/HAVIP.md) +专线网关 | EtGateway | github.com/baidubce/bce-sdk-go/services/etGateway | [ETGateway.md](./doc/ETGateway.md) +身份管理 | IAM | github.com/baidubce/bce-sdk-go/services/iam | [IAM.md](./doc/IAM.md) +内网DNS | LOCALDNS | github.com/baidubce/bce-sdk-go/services/localDns | [LOCALDNS.md](./doc/LOCALDNS.md) +音视频处理MCP | MCP | github.com/baidubce/bce-sdk-go/services/media | [MCP.md](./doc/MCP.md) +云数据库 | RDS | github.com/baidubce/bce-sdk-go/services/rds | [RDS.md](./doc/RDS.md) +分布式缓存服务 | SCS | github.com/baidubce/bce-sdk-go/services/scs | [SCS.md](./doc/SCS.md) +SMS简单消息服务 | SMS | github.com/baidubce/bce-sdk-go/services/sms | [SMS.md](./doc/SMS.md) +SNIC服务网卡 | SNIC | github.com/baidubce/bce-sdk-go/services/endpoint | [SNIC.md](./doc/SNIC.md) +安全Token服务| STS | github.com/baidubce/bce-sdk-go/services/sts | [STS.md](./doc/STS.md) +视频内容分析 | VCA | github.com/baidubce/bce-sdk-go/services/vca | +视频内容审核 | VCR | github.com/baidubce/bce-sdk-go/services/vcr | +私有网络 | VPC | github.com/baidubce/bce-sdk-go/services/vpc | [VPC.md](./doc/VPC.md) +VPN网关 | VPN | github.com/baidubce/bce-sdk-go/services/vpn | [VPN.md](./doc/VPN.md) +多模态媒资检索 | MMS | github.com/baidubce/bce-sdk-go/services/mms | [MMS.md](./doc/MMS.md) +数据库专属集群 | DDC | github.com/baidubce/bce-sdk-go/services/ddc | [DDC.md](./doc/DDC.md) diff --git a/bce-sdk-go/auth/credentials.go b/bce-sdk-go/auth/credentials.go new file mode 100644 index 0000000..fb1e415 --- /dev/null +++ b/bce-sdk-go/auth/credentials.go @@ -0,0 +1,62 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// credentials.go - the credentials data structure definition + +// Package auth implements the authorization functionality for BCE. +// It use the BCE access key ID and secret access key with the specific sign algorithm to generate +// the authorization string. It also supports the temporary authorization by the STS token. +package auth + +import "errors" + +// BceCredentials define the data structure for authorization +type BceCredentials struct { + AccessKeyId string // access key id to the service + SecretAccessKey string // secret access key to the service + SessionToken string // session token generate by the STS service +} + +func (b *BceCredentials) String() string { + str := "ak: " + b.AccessKeyId + ", sk: " + b.SecretAccessKey + if len(b.SessionToken) != 0 { + return str + ", sessionToken: " + b.SessionToken + } + return str +} + +func NewBceCredentials(ak, sk string) (*BceCredentials, error) { + if len(ak) == 0 { + return nil, errors.New("accessKeyId should not be empty") + } + if len(sk) == 0 { + return nil, errors.New("secretKey should not be empty") + } + + return &BceCredentials{ak, sk, ""}, nil +} + +func NewSessionBceCredentials(ak, sk, token string) (*BceCredentials, error) { + if len(token) == 0 { + return nil, errors.New("sessionToken should not be empty") + } + + result, err := NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + result.SessionToken = token + + return result, nil +} diff --git a/bce-sdk-go/auth/signer.go b/bce-sdk-go/auth/signer.go new file mode 100644 index 0000000..212e1f5 --- /dev/null +++ b/bce-sdk-go/auth/signer.go @@ -0,0 +1,184 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// signer.go - implement the specific sign algorithm of BCE V1 protocol + +package auth + +import ( + "fmt" + "sort" + "strings" + + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BCE_AUTH_VERSION = "bce-auth-v1" + SIGN_JOINER = "\n" + SIGN_HEADER_JOINER = ";" + DEFAULT_EXPIRE_SECONDS = 1800 + DEFAULT_HEADERS_TO_SIGN = map[string]struct{}{ + strings.ToLower(http.HOST): {}, + strings.ToLower(http.CONTENT_LENGTH): {}, + strings.ToLower(http.CONTENT_TYPE): {}, + strings.ToLower(http.CONTENT_MD5): {}, + } +) + +// Signer abstracts the entity that implements the `Sign` method +type Signer interface { + // Sign the given Request with the Credentials and SignOptions + Sign(*http.Request, *BceCredentials, *SignOptions) +} + +// SignOptions defines the data structure used by Signer +type SignOptions struct { + HeadersToSign map[string]struct{} + Timestamp int64 + ExpireSeconds int +} + +func (opt *SignOptions) String() string { + return fmt.Sprintf(`SignOptions [ + HeadersToSign=%s; + Timestamp=%d; + ExpireSeconds=%d + ]`, opt.HeadersToSign, opt.Timestamp, opt.ExpireSeconds) +} + +// BceV1Signer implements the v1 sign algorithm +type BceV1Signer struct{} + +// Sign - generate the authorization string from the BceCredentials and SignOptions +// +// PARAMS: +// - req: *http.Request for this sign +// - cred: *BceCredentials to access the serice +// - opt: *SignOptions for this sign algorithm +func (b *BceV1Signer) Sign(req *http.Request, cred *BceCredentials, opt *SignOptions) { + if req == nil { + log.Fatal("request should not be null for sign") + return + } + if cred == nil { + log.Fatal("credentials should not be null for sign") + return + } + + // Prepare parameters + accessKeyId := cred.AccessKeyId + secretAccessKey := cred.SecretAccessKey + signDate := util.FormatISO8601Date(util.NowUTCSeconds()) + // Modify the sign time if it is not the default value but specified by client + if opt.Timestamp != 0 { + signDate = util.FormatISO8601Date(opt.Timestamp) + } + + // Set security token if using session credentials and session token not in param + if len(cred.SessionToken) != 0 && req.Param(http.BCE_SECURITY_TOKEN) == "" { + req.SetHeader(http.BCE_SECURITY_TOKEN, cred.SessionToken) + } + + // Prepare the canonical request components + signKeyInfo := fmt.Sprintf("%s/%s/%s/%d", + BCE_AUTH_VERSION, + accessKeyId, + signDate, + opt.ExpireSeconds) + signKey := util.HmacSha256Hex(secretAccessKey, signKeyInfo) + canonicalUri := getCanonicalURIPath(req.Uri()) + canonicalQueryString := getCanonicalQueryString(req.Params()) + canonicalHeaders, signedHeadersArr := getCanonicalHeaders(req.Headers(), opt.HeadersToSign) + + // Generate signed headers string + signedHeaders := "" + if len(signedHeadersArr) > 0 { + sort.Strings(signedHeadersArr) + signedHeaders = strings.Join(signedHeadersArr, SIGN_HEADER_JOINER) + } + + // Generate signature + canonicalParts := []string{req.Method(), canonicalUri, canonicalQueryString, canonicalHeaders} + canonicalReq := strings.Join(canonicalParts, SIGN_JOINER) + log.Debug("CanonicalRequest data:\n" + canonicalReq) + signature := util.HmacSha256Hex(signKey, canonicalReq) + + // Generate auth string and add to the reqeust header + authStr := signKeyInfo + "/" + signedHeaders + "/" + signature + log.Info("Authorization=" + authStr) + + req.SetHeader(http.AUTHORIZATION, authStr) +} + +func getCanonicalURIPath(path string) string { + if len(path) == 0 { + return "/" + } + canonical_path := path + if strings.HasPrefix(path, "/") { + canonical_path = path[1:] + } + canonical_path = util.UriEncode(canonical_path, false) + return "/" + canonical_path +} + +func getCanonicalQueryString(params map[string]string) string { + if len(params) == 0 { + return "" + } + + result := make([]string, 0, len(params)) + for k, v := range params { + if strings.ToLower(k) == strings.ToLower(http.AUTHORIZATION) { + continue + } + item := "" + if len(v) == 0 { + item = fmt.Sprintf("%s=", util.UriEncode(k, true)) + } else { + item = fmt.Sprintf("%s=%s", util.UriEncode(k, true), util.UriEncode(v, true)) + } + result = append(result, item) + } + sort.Strings(result) + return strings.Join(result, "&") +} + +func getCanonicalHeaders(headers map[string]string, + headersToSign map[string]struct{}) (string, []string) { + canonicalHeaders := make([]string, 0, len(headers)) + signHeaders := make([]string, 0, len(headersToSign)) + for k, v := range headers { + headKey := strings.ToLower(k) + if headKey == strings.ToLower(http.AUTHORIZATION) { + continue + } + _, headExists := headersToSign[headKey] + if headExists || + (strings.HasPrefix(headKey, http.BCE_PREFIX) && + (headKey != http.BCE_REQUEST_ID)) { + + headVal := strings.TrimSpace(v) + encoded := util.UriEncode(headKey, true) + ":" + util.UriEncode(headVal, true) + canonicalHeaders = append(canonicalHeaders, encoded) + signHeaders = append(signHeaders, headKey) + } + } + sort.Strings(canonicalHeaders) + sort.Strings(signHeaders) + return strings.Join(canonicalHeaders, SIGN_JOINER), signHeaders +} diff --git a/bce-sdk-go/bce/builder.go b/bce-sdk-go/bce/builder.go new file mode 100644 index 0000000..1b25504 --- /dev/null +++ b/bce-sdk-go/bce/builder.go @@ -0,0 +1,189 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// builder.go - defines the RequestBuilder structure for BCE servies + +package bce + +import ( + "encoding/json" + "fmt" +) + +// RequestBuilder holds config data for bce request. +// Some of fields are required and the others are optional. +// The builder pattern can simplify the execution of requests. +type RequestBuilder struct { + client Client + + url string // required + method string // required + queryParams map[string]string // optional + headers map[string]string // optional + body interface{} // optional + result interface{} // optional +} + +// create RequestBuilder with the client. +func NewRequestBuilder(client Client) *RequestBuilder { + return &RequestBuilder{ + client: client, + } +} + +func (b *RequestBuilder) WithURL(url string) *RequestBuilder { + b.url = url + return b +} + +func (b *RequestBuilder) WithMethod(method string) *RequestBuilder { + b.method = method + return b +} + +// set query param with the key/value directly. +func (b *RequestBuilder) WithQueryParam(key, value string) *RequestBuilder { + if b.queryParams == nil { + b.queryParams = make(map[string]string) + } + b.queryParams[key] = value + return b +} + +// set query param with the key/value only when the value is not blank. +func (b *RequestBuilder) WithQueryParamFilter(key, value string) *RequestBuilder { + if len(value) == 0 { + return b + } + return b.WithQueryParam(key, value) +} + +func (b *RequestBuilder) WithQueryParams(params map[string]string) *RequestBuilder { + if b.queryParams == nil { + b.queryParams = params + } else { + for key, value := range params { + b.queryParams[key] = value + } + } + return b +} + +func (b *RequestBuilder) WithHeader(key, value string) *RequestBuilder { + if b.headers == nil { + b.headers = make(map[string]string) + } + b.headers[key] = value + return b +} + +func (b *RequestBuilder) WithHeaders(headers map[string]string) *RequestBuilder { + if b.headers == nil { + b.headers = headers + } else { + for key, value := range headers { + b.headers[key] = value + } + } + return b +} + +func (b *RequestBuilder) WithBody(body interface{}) *RequestBuilder { + b.body = body + return b +} + +func (b *RequestBuilder) WithResult(result interface{}) *RequestBuilder { + b.result = result + return b +} + +// Do will send request to bce and get result with the builder's parameters. +func (b *RequestBuilder) Do() error { + if err := b.validate(); err != nil { + return err + } + + // build BceRequest + req, err := b.buildBceRequest() + if err != nil { + return err + } + + // get result from BceResponse + if err := b.buildBceResponse(req); err != nil { + return err + } + + return nil +} + +// Validate if the required fields are providered. +func (b *RequestBuilder) validate() error { + if len(b.url) == 0 { + return fmt.Errorf("The url can't be null.") + } + if len(b.method) == 0 { + return fmt.Errorf("The method can't be null.") + } + if b.client == nil { + return fmt.Errorf("The client can't be null.") + } + return nil +} + +func (b *RequestBuilder) buildBceRequest() (*BceRequest, error) { + // Build the request + req := &BceRequest{} + req.SetUri(b.url) + req.SetMethod(b.method) + + if b.headers != nil { + req.SetHeaders(b.headers) + } + if b.queryParams != nil { + req.SetParams(b.queryParams) + } + if b.body != nil { + bodyBytes, err := json.Marshal(b.body) + if err != nil { + return nil, err + } + body, err := NewBodyFromBytes(bodyBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + } + + return req, nil +} + +func (b *RequestBuilder) buildBceResponse(req *BceRequest) error { + // Send request and get response + resp := &BceResponse{} + if err := b.client.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer resp.Body().Close() + + if b.result == nil { + return nil + } + + return resp.ParseJsonBody(b.result) +} diff --git a/bce-sdk-go/bce/client.go b/bce-sdk-go/bce/client.go new file mode 100644 index 0000000..d8ea23d --- /dev/null +++ b/bce-sdk-go/bce/client.go @@ -0,0 +1,279 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - definiton the BceClientConfiguration and BceClient structure + +// Package bce implements the infrastructure to access BCE services. +// +// - BceClient: +// It is the general client of BCE to access all services. It builds http request to access the +// services based on the given client configuration. +// +// - BceClientConfiguration: +// The client configuration data structure which contains endpoint, region, credentials, retry +// policy, sign options and so on. It supports most of the default value and user can also +// access or change the default with its public fields' name. +// +// - Error types: +// The error types when making request or receiving response to the BCE services contains two +// types: the BceClientError when making request to BCE services and the BceServiceError when +// recieving response from them. +// +// - BceRequest: +// The request instance stands for an request to access the BCE services. +// +// - BceResponse: +// The response instance stands for an response from the BCE services. +package bce + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "time" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +// Client is the general interface which can perform sending request. Different service +// will define its own client in case of specific extension. +type Client interface { + SendRequest(*BceRequest, *BceResponse) error + SendRequestFromBytes(*BceRequest, *BceResponse, []byte) error + GetBceClientConfig() *BceClientConfiguration +} + +// BceClient defines the general client to access the BCE services. +type BceClient struct { + Config *BceClientConfiguration + Signer auth.Signer // the sign algorithm +} + +// BuildHttpRequest - the helper method for the client to build http request +// +// PARAMS: +// - request: the input request object to be built +func (c *BceClient) buildHttpRequest(request *BceRequest) { + // Construct the http request instance for the special fields + request.BuildHttpRequest() + + // Set the client specific configurations + if request.Endpoint() == "" { + request.SetEndpoint(c.Config.Endpoint) + } + if request.Protocol() == "" { + request.SetProtocol(DEFAULT_PROTOCOL) + } + if len(c.Config.ProxyUrl) != 0 { + request.SetProxyUrl(c.Config.ProxyUrl) + } + request.SetTimeout(c.Config.ConnectionTimeoutInMillis / 1000) + + // Set the BCE request headers + request.SetHeader(http.HOST, request.Host()) + request.SetHeader(http.USER_AGENT, c.Config.UserAgent) + request.SetHeader(http.BCE_DATE, util.FormatISO8601Date(util.NowUTCSeconds())) + + //set default content-type if null + if request.Header(http.CONTENT_TYPE) == "" { + request.SetHeader(http.CONTENT_TYPE, DEFAULT_CONTENT_TYPE) + } + + // Generate the auth string if needed + if c.Config.Credentials != nil { + c.Signer.Sign(&request.Request, c.Config.Credentials, c.Config.SignOption) + } +} + +// SendRequest - the client performs sending the http request with retry policy and receive the +// response from the BCE services. +// +// PARAMS: +// - req: the request object to be sent to the BCE service +// - resp: the response object to receive the content from BCE service +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *BceClient) SendRequest(req *BceRequest, resp *BceResponse) error { + // Return client error if it is not nil + if req.ClientError() != nil { + return req.ClientError() + } + + // Build the http request and prepare to send + c.buildHttpRequest(req) + log.Infof("send http request: %v", req) + + // Send request with the given retry policy + retries := 0 + if req.Body() != nil { + defer req.Body().Close() // Manually close the ReadCloser body for retry + } + for { + // The request body should be temporarily saved if retry to send the http request + var retryBuf bytes.Buffer + var teeReader io.Reader + if c.Config.Retry.ShouldRetry(nil, 0) && req.Body() != nil { + teeReader = io.TeeReader(req.Body(), &retryBuf) + req.Request.SetBody(ioutil.NopCloser(teeReader)) + } + httpResp, err := http.Execute(&req.Request) + + if err != nil { + if c.Config.Retry.ShouldRetry(err, retries) { + delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) + time.Sleep(delay_in_mills) + } else { + return &BceClientError{ + fmt.Sprintf("execute http request failed! Retried %d times, error: %v", + retries, err)} + } + retries++ + log.Warnf("send request failed: %v, retry for %d time(s)", err, retries) + if req.Body() != nil { + ioutil.ReadAll(teeReader) + req.Request.SetBody(ioutil.NopCloser(&retryBuf)) + } + continue + } + resp.SetHttpResponse(httpResp) + resp.ParseResponse() + + log.Infof("receive http response: status: %s, debugId: %s, requestId: %s, elapsed: %v", + resp.StatusText(), resp.DebugId(), resp.RequestId(), resp.ElapsedTime()) + + if resp.ElapsedTime().Milliseconds() > DEFAULT_WARN_LOG_TIMEOUT_IN_MILLS { + log.Warnf("request time more than 5 second, debugId: %s, requestId: %s, elapsed: %v", + resp.DebugId(), resp.RequestId(), resp.ElapsedTime()) + } + for k, v := range resp.Headers() { + log.Debugf("%s=%s", k, v) + } + if resp.IsFail() { + err := resp.ServiceError() + if c.Config.Retry.ShouldRetry(err, retries) { + delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) + time.Sleep(delay_in_mills) + } else { + return err + } + retries++ + log.Warnf("send request failed, retry for %d time(s)", retries) + if req.Body() != nil { + ioutil.ReadAll(teeReader) + req.Request.SetBody(ioutil.NopCloser(&retryBuf)) + } + continue + } + return nil + } +} + +// SendRequestFromBytes - the client performs sending the http request with retry policy and receive the +// response from the BCE services. +// +// PARAMS: +// - req: the request object to be sent to the BCE service +// - resp: the response object to receive the content from BCE service +// - content: the content of body +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *BceClient) SendRequestFromBytes(req *BceRequest, resp *BceResponse, content []byte) error { + // Return client error if it is not nil + if req.ClientError() != nil { + return req.ClientError() + } + // Build the http request and prepare to send + c.buildHttpRequest(req) + log.Infof("send http request: %v", req) + // Send request with the given retry policy + retries := 0 + for { + // The request body should be temporarily saved if retry to send the http request + buf := bytes.NewBuffer(content) + req.Request.SetBody(ioutil.NopCloser(buf)) + defer req.Request.Body().Close() // Manually close the ReadCloser body for retry + httpResp, err := http.Execute(&req.Request) + if err != nil { + if c.Config.Retry.ShouldRetry(err, retries) { + delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) + time.Sleep(delay_in_mills) + } else { + return &BceClientError{ + fmt.Sprintf("execute http request failed! Retried %d times, error: %v", + retries, err)} + } + retries++ + log.Warnf("send request failed: %v, retry for %d time(s)", err, retries) + continue + } + resp.SetHttpResponse(httpResp) + resp.ParseResponse() + log.Infof("receive http response: status: %s, debugId: %s, requestId: %s, elapsed: %v", + resp.StatusText(), resp.DebugId(), resp.RequestId(), resp.ElapsedTime()) + for k, v := range resp.Headers() { + log.Debugf("%s=%s", k, v) + } + if resp.IsFail() { + err := resp.ServiceError() + if c.Config.Retry.ShouldRetry(err, retries) { + delay_in_mills := c.Config.Retry.GetDelayBeforeNextRetryInMillis(err, retries) + time.Sleep(delay_in_mills) + } else { + return err + } + retries++ + log.Warnf("send request failed, retry for %d time(s)", retries) + continue + } + return nil + } +} + +func (c *BceClient) GetBceClientConfig() *BceClientConfiguration { + return c.Config +} + +func NewBceClient(conf *BceClientConfiguration, sign auth.Signer) *BceClient { + clientConfig := http.ClientConfig{RedirectDisabled: conf.RedirectDisabled} + http.InitClient(clientConfig) + return &BceClient{conf, sign} +} + +func NewBceClientWithAkSk(ak, sk, endPoint string) (*BceClient, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &BceClientConfiguration{ + Endpoint: endPoint, + Region: DEFAULT_REGION, + UserAgent: DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS, + RedirectDisabled: false} + v1Signer := &auth.BceV1Signer{} + + return NewBceClient(defaultConf, v1Signer), nil +} diff --git a/bce-sdk-go/bce/config.go b/bce-sdk-go/bce/config.go new file mode 100644 index 0000000..37de16a --- /dev/null +++ b/bce-sdk-go/bce/config.go @@ -0,0 +1,81 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// config.go - define the client configuration for BCE + +package bce + +import ( + "fmt" + "reflect" + "runtime" + + "github.com/baidubce/bce-sdk-go/auth" +) + +// Constants and default values for the package bce +const ( + SDK_VERSION = "0.9.164" + URI_PREFIX = "/" // now support uri without prefix "v1" so just set root path + DEFAULT_DOMAIN = "baidubce.com" + DEFAULT_PROTOCOL = "http" + DEFAULT_REGION = "bj" + DEFAULT_CONTENT_TYPE = "application/json;charset=utf-8" + DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS = 1200 * 1000 + DEFAULT_WARN_LOG_TIMEOUT_IN_MILLS = 5 * 1000 +) + +var ( + DEFAULT_USER_AGENT string + DEFAULT_RETRY_POLICY = NewBackOffRetryPolicy(3, 20000, 300) +) + +func init() { + DEFAULT_USER_AGENT = "bce-sdk-go" + DEFAULT_USER_AGENT += "/" + SDK_VERSION + DEFAULT_USER_AGENT += "/" + runtime.Version() + DEFAULT_USER_AGENT += "/" + runtime.GOOS + DEFAULT_USER_AGENT += "/" + runtime.GOARCH +} + +// BceClientConfiguration defines the config components structure. +type BceClientConfiguration struct { + Endpoint string + ProxyUrl string + Region string + UserAgent string + Credentials *auth.BceCredentials + SignOption *auth.SignOptions + Retry RetryPolicy + ConnectionTimeoutInMillis int + // CnameEnabled should be true when use custom domain as endpoint to visit bos resource + CnameEnabled bool + BackupEndpoint string + RedirectDisabled bool +} + +func (c *BceClientConfiguration) String() string { + return fmt.Sprintf(`BceClientConfiguration [ + Endpoint=%s; + ProxyUrl=%s; + Region=%s; + UserAgent=%s; + Credentials=%v; + SignOption=%v; + RetryPolicy=%v; + ConnectionTimeoutInMillis=%v; + RedirectDisabled=%v + ]`, c.Endpoint, c.ProxyUrl, c.Region, c.UserAgent, c.Credentials, + c.SignOption, reflect.TypeOf(c.Retry).Name(), c.ConnectionTimeoutInMillis, c.RedirectDisabled) +} diff --git a/bce-sdk-go/bce/error.go b/bce-sdk-go/bce/error.go new file mode 100644 index 0000000..e625651 --- /dev/null +++ b/bce-sdk-go/bce/error.go @@ -0,0 +1,64 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// error.go - define the error types for BCE + +package bce + +const ( + EACCESS_DENIED = "AccessDenied" + EINAPPROPRIATE_JSON = "InappropriateJSON" + EINTERNAL_ERROR = "InternalError" + EINVALID_ACCESS_KEY_ID = "InvalidAccessKeyId" + EINVALID_HTTP_AUTH_HEADER = "InvalidHTTPAuthHeader" + EINVALID_HTTP_REQUEST = "InvalidHTTPRequest" + EINVALID_URI = "InvalidURI" + EMALFORMED_JSON = "MalformedJSON" + EINVALID_VERSION = "InvalidVersion" + EOPT_IN_REQUIRED = "OptInRequired" + EPRECONDITION_FAILED = "PreconditionFailed" + EREQUEST_EXPIRED = "RequestExpired" + ESIGNATURE_DOES_NOT_MATCH = "SignatureDoesNotMatch" +) + +// BceError abstracts the error for BCE +type BceError interface { + error +} + +// BceClientError defines the error struct for the client when making request +type BceClientError struct{ Message string } + +func (b *BceClientError) Error() string { return b.Message } + +func NewBceClientError(msg string) *BceClientError { return &BceClientError{msg} } + +// BceServiceError defines the error struct for the BCE service when receiving response +type BceServiceError struct { + Code string + Message string + RequestId string + StatusCode int +} + +func (b *BceServiceError) Error() string { + ret := "[Code: " + b.Code + ret += "; Message: " + b.Message + ret += "; RequestId: " + b.RequestId + "]" + return ret +} + +func NewBceServiceError(code, msg, reqId string, status int) *BceServiceError { + return &BceServiceError{code, msg, reqId, status} +} diff --git a/bce-sdk-go/bce/request.go b/bce-sdk-go/bce/request.go new file mode 100644 index 0000000..49eecc2 --- /dev/null +++ b/bce-sdk-go/bce/request.go @@ -0,0 +1,224 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// request.go - defines the BCE servies request + +package bce + +import ( + "bytes" + "fmt" + "io" + "io/ioutil" + "os" + + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +// Body defines the data structure used in BCE request. +// Every BCE request that sets the body field must set its content-length and content-md5 headers +// to ensure the correctness of the body content forcely, and users can also set the content-sha256 +// header to strengthen the correctness with the "SetHeader" method. +type Body struct { + stream io.ReadCloser + size int64 + contentMD5 string +} + +func (b *Body) Stream() io.ReadCloser { return b.stream } + +func (b *Body) SetStream(stream io.ReadCloser) { b.stream = stream } + +func (b *Body) Size() int64 { return b.size } + +func (b *Body) ContentMD5() string { return b.contentMD5 } + +// NewBodyFromBytes - build a Body object from the byte stream to be used in the http request, it +// calculates the content-md5 of the byte stream and store the size as well as the stream. +// +// PARAMS: +// - stream: byte stream +// +// RETURNS: +// - *Body: the return Body object +// - error: error if any specific error occurs +func NewBodyFromBytes(stream []byte) (*Body, error) { + buf := bytes.NewBuffer(stream) + size := int64(buf.Len()) + contentMD5, err := util.CalculateContentMD5(buf, size) + if err != nil { + return nil, err + } + buf = bytes.NewBuffer(stream) + return &Body{ioutil.NopCloser(buf), size, contentMD5}, nil +} + +// NewBodyFromString - build a Body object from the string to be used in the http request, it +// calculates the content-md5 of the byte stream and store the size as well as the stream. +// +// PARAMS: +// - str: the input string +// +// RETURNS: +// - *Body: the return Body object +// - error: error if any specific error occurs +func NewBodyFromString(str string) (*Body, error) { + buf := bytes.NewBufferString(str) + size := int64(len(str)) + contentMD5, err := util.CalculateContentMD5(buf, size) + if err != nil { + return nil, err + } + buf = bytes.NewBufferString(str) + return &Body{ioutil.NopCloser(buf), size, contentMD5}, nil +} + +// NewBodyFromFile - build a Body object from the given file name to be used in the http request, +// it calculates the content-md5 of the byte stream and store the size as well as the stream. +// +// PARAMS: +// - fname: the given file name +// +// RETURNS: +// - *Body: the return Body object +// - error: error if any specific error occurs +func NewBodyFromFile(fname string) (*Body, error) { + file, err := os.Open(fname) + if err != nil { + return nil, err + } + fileInfo, infoErr := file.Stat() + if infoErr != nil { + return nil, infoErr + } + contentMD5, md5Err := util.CalculateContentMD5(file, fileInfo.Size()) + if md5Err != nil { + return nil, md5Err + } + if _, err = file.Seek(0, 0); err != nil { + return nil, err + } + return &Body{file, fileInfo.Size(), contentMD5}, nil +} + +// NewBodyFromSectionFile - build a Body object from the given file pointer with offset and size. +// It calculates the content-md5 of the given content and store the size as well as the stream. +// +// PARAMS: +// - file: the input file pointer +// - off: offset of current section body +// - size: current section body size +// +// RETURNS: +// - *Body: the return Body object +// - error: error if any specific error occurs +func NewBodyFromSectionFile(file *os.File, off, size int64) (*Body, error) { + if _, err := file.Seek(off, 0); err != nil { + return nil, err + } + contentMD5, md5Err := util.CalculateContentMD5(file, size) + if md5Err != nil { + return nil, md5Err + } + if _, err := file.Seek(0, 0); err != nil { + return nil, err + } + section := io.NewSectionReader(file, off, size) + return &Body{ioutil.NopCloser(section), size, contentMD5}, nil +} + +// NewBodyFromSizedReader - build a Body object from the given reader with size. +// It calculates the content-md5 of the given content and store the size as well as the stream. +// +// PARAMS: +// - r: the input reader +// - size: the size to be read, -1 is read all +// +// RETURNS: +// - *Body: the return Body object +// - error: error if any specific error occurs +func NewBodyFromSizedReader(r io.Reader, size int64) (*Body, error) { + var buffer bytes.Buffer + var rlen int64 + var err error + if size >= 0 { + rlen, err = io.CopyN(&buffer, r, size) + } else { + rlen, err = io.Copy(&buffer, r) + } + if err != nil { + return nil, err + } + if rlen != int64(buffer.Len()) { // must be equal + return nil, NewBceClientError("unexpected reader") + } + if size >= 0 { + if rlen < size { + return nil, NewBceClientError("size is great than reader actual size") + } + } + contentMD5, err := util.CalculateContentMD5(bytes.NewBuffer(buffer.Bytes()), rlen) + if err != nil { + return nil, err + } + body := &Body{ + stream: ioutil.NopCloser(&buffer), + size: rlen, + contentMD5: contentMD5, + } + return body, nil +} + +// BceRequest defines the request structure for accessing BCE services +type BceRequest struct { + http.Request + requestId string + clientError *BceClientError +} + +func (b *BceRequest) RequestId() string { return b.requestId } + +func (b *BceRequest) SetRequestId(val string) { b.requestId = val } + +func (b *BceRequest) ClientError() *BceClientError { return b.clientError } + +func (b *BceRequest) SetClientError(err *BceClientError) { b.clientError = err } + +func (b *BceRequest) SetBody(body *Body) { // override SetBody derived from http.Request + b.Request.SetBody(body.Stream()) + b.SetLength(body.Size()) // set field of "net/http.Request.ContentLength" + if body.Size() > 0 { + b.SetHeader(http.CONTENT_MD5, body.ContentMD5()) + b.SetHeader(http.CONTENT_LENGTH, fmt.Sprintf("%d", body.Size())) + } +} + +func (b *BceRequest) BuildHttpRequest() { + // Only need to build the specific `requestId` field for BCE, other fields are same as the + // `http.Request` as well as its methods. + if len(b.requestId) == 0 { + // Construct the request ID with UUID + b.requestId = util.NewRequestId() + } + b.SetHeader(http.BCE_REQUEST_ID, b.requestId) +} + +func (b *BceRequest) String() string { + requestIdStr := "requestId=" + b.requestId + if b.clientError != nil { + return requestIdStr + ", client error: " + b.ClientError().Error() + } + return requestIdStr + "\n" + b.Request.String() +} diff --git a/bce-sdk-go/bce/response.go b/bce-sdk-go/bce/response.go new file mode 100644 index 0000000..94f2ae4 --- /dev/null +++ b/bce-sdk-go/bce/response.go @@ -0,0 +1,128 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// response.go - defines the common BCE services response + +package bce + +import ( + "bytes" + "encoding/json" + "io" + "io/ioutil" + "strings" + "time" + + "github.com/baidubce/bce-sdk-go/http" +) + +// BceResponse defines the response structure for receiving BCE services response. +type BceResponse struct { + statusCode int + statusText string + requestId string + debugId string + response *http.Response + serviceError *BceServiceError +} + +func (r *BceResponse) IsFail() bool { + return r.response.StatusCode() >= 400 +} + +func (r *BceResponse) StatusCode() int { + return r.statusCode +} + +func (r *BceResponse) StatusText() string { + return r.statusText +} + +func (r *BceResponse) RequestId() string { + return r.requestId +} + +func (r *BceResponse) DebugId() string { + return r.debugId +} + +func (r *BceResponse) Header(key string) string { + return r.response.GetHeader(key) +} + +func (r *BceResponse) Headers() map[string]string { + return r.response.GetHeaders() +} + +func (r *BceResponse) Body() io.ReadCloser { + return r.response.Body() +} + +func (r *BceResponse) SetHttpResponse(response *http.Response) { + r.response = response +} + +func (r *BceResponse) ElapsedTime() time.Duration { + return r.response.ElapsedTime() +} + +func (r *BceResponse) ServiceError() *BceServiceError { + return r.serviceError +} + +func (r *BceResponse) ParseResponse() { + r.statusCode = r.response.StatusCode() + r.statusText = r.response.StatusText() + r.requestId = r.response.GetHeader(http.BCE_REQUEST_ID) + r.debugId = r.response.GetHeader(http.BCE_DEBUG_ID) + if r.IsFail() { + r.serviceError = NewBceServiceError("", r.statusText, r.requestId, r.statusCode) + + // First try to read the error `Code' and `Message' from body + rawBody, _ := ioutil.ReadAll(r.Body()) + defer r.Body().Close() + if len(rawBody) != 0 { + jsonDecoder := json.NewDecoder(bytes.NewBuffer(rawBody)) + if err := jsonDecoder.Decode(r.serviceError); err != nil { + r.serviceError = NewBceServiceError( + EMALFORMED_JSON, + "Service json error message decode failed", + r.requestId, + r.statusCode) + } + return + } + + // Then guess the `Message' from by the return status code + switch r.statusCode { + case 400: + r.serviceError.Code = EINVALID_HTTP_REQUEST + case 403: + r.serviceError.Code = EACCESS_DENIED + case 412: + r.serviceError.Code = EPRECONDITION_FAILED + case 500: + r.serviceError.Code = EINTERNAL_ERROR + default: + words := strings.Split(r.statusText, " ") + r.serviceError.Code = strings.Join(words[1:], "") + } + } +} + +func (r *BceResponse) ParseJsonBody(result interface{}) error { + defer r.Body().Close() + jsonDecoder := json.NewDecoder(r.Body()) + return jsonDecoder.Decode(result) +} diff --git a/bce-sdk-go/bce/retry.go b/bce-sdk-go/bce/retry.go new file mode 100644 index 0000000..19675a3 --- /dev/null +++ b/bce-sdk-go/bce/retry.go @@ -0,0 +1,118 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// retry.go - define the retry policy when making requests to BCE services + +package bce + +import ( + "net" + "net/http" + "time" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +// RetryPolicy defines the two methods to retry for sending request. +type RetryPolicy interface { + ShouldRetry(BceError, int) bool + GetDelayBeforeNextRetryInMillis(BceError, int) time.Duration +} + +// NoRetryPolicy just does not retry. +type NoRetryPolicy struct{} + +func (_ *NoRetryPolicy) ShouldRetry(err BceError, attempts int) bool { + return false +} + +func (_ *NoRetryPolicy) GetDelayBeforeNextRetryInMillis( + err BceError, attempts int) time.Duration { + return 0 * time.Millisecond +} + +func NewNoRetryPolicy() *NoRetryPolicy { + return &NoRetryPolicy{} +} + +// BackOffRetryPolicy implements a policy that retries with exponential back-off strategy. +// This policy will keep retrying until the maximum number of retries is reached. The delay time +// will be a fixed interval for the first time then 2 * interval for the second, 4 * internal for +// the third, and so on. +// In general, the delay time will be 2^number_of_retries_attempted*interval. When a maximum of +// delay time is specified, the delay time will never exceed this limit. +type BackOffRetryPolicy struct { + maxErrorRetry int + maxDelayInMillis int64 + baseIntervalInMillis int64 +} + +func (b *BackOffRetryPolicy) ShouldRetry(err BceError, attempts int) bool { + // Do not retry any more when retry the max times + if attempts >= b.maxErrorRetry { + return false + } + + if err == nil { + return true + } + + // Always retry on IO error + if _, ok := err.(net.Error); ok { + return true + } + + // Only retry on a service error + if realErr, ok := err.(*BceServiceError); ok { + switch realErr.StatusCode { + case http.StatusInternalServerError: + log.Warn("retry for internal server error(500)") + return true + case http.StatusBadGateway: + log.Warn("retry for bad gateway(502)") + return true + case http.StatusServiceUnavailable: + log.Warn("retry for service unavailable(503)") + return true + case http.StatusBadRequest: + if realErr.Code != "Http400" { + return false + } + log.Warn("retry for bad request(400)") + return true + } + + if realErr.Code == EREQUEST_EXPIRED { + log.Warn("retry for request expired") + return true + } + } + return false +} + +func (b *BackOffRetryPolicy) GetDelayBeforeNextRetryInMillis( + err BceError, attempts int) time.Duration { + if attempts < 0 { + return 0 * time.Millisecond + } + delayInMillis := (1 << uint64(attempts)) * b.baseIntervalInMillis + if delayInMillis > b.maxDelayInMillis { + return time.Duration(b.maxDelayInMillis) * time.Millisecond + } + return time.Duration(delayInMillis) * time.Millisecond +} + +func NewBackOffRetryPolicy(maxRetry int, maxDelay, base int64) *BackOffRetryPolicy { + return &BackOffRetryPolicy{maxRetry, maxDelay, base} +} diff --git a/bce-sdk-go/doc/APPBLB.md b/bce-sdk-go/doc/APPBLB.md new file mode 100644 index 0000000..b7ade3b --- /dev/null +++ b/bce-sdk-go/doc/APPBLB.md @@ -0,0 +1,1288 @@ +# APPBLB服务 + +# 概述 + +本文档主要介绍应用型BLB GO SDK的使用。在使用本文档前,您需要先了解应用型BLB的一些基本知识。若您还不了解应用型BLB,可以参考[产品描述](https://cloud.baidu.com/doc/BLB/s/Ajwvxno34)和[入门指南](https://cloud.baidu.com/doc/BLB/s/cjwvxnr91)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BLB访问域名](https://cloud.baidu.com/doc/BLB/s/cjwvxnzix)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云BLB,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BLB做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建应用型BLB Client + +应用型BLB Client是应用型BLB服务的客户端,为开发者与BLB服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建应用型BLB Client + +通过AK/SK方式访问BLB,用户可以参考如下代码新建一个BLB Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BLBClient + blbClient, err := appblb.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BLB/s/ojwvynrqn)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BLB的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`blb.bj.baidubce.com`。 + +### 使用STS创建BLB Client + +**申请STS token** + +BLB可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BLB,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建BLB Client** + +申请好STS后,可将STS Token配置到BLB Client中,从而实现通过STS Token创建BLB Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BLB Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/appblb" //导入APPBLB服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BLB服务的Client对象,Endpoint使用默认值 + blbClient, err := appblb.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create appblb client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + blbClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BLB Client时,无论对应BLB服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问BLB + +BLB支持HTTPS传输协议,您可以通过在创建BLB Client对象时指定的Endpoint中指明HTTPS的方式,在BLB GO SDK中使用HTTPS访问BLB服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/appblb" + +ENDPOINT := "https://blb.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +blbClient, _ := appblb.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BLB Client + +如果用户需要配置BLB Client的一些细节的参数,可以在创建BLB Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BLB服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/appblb" + +//创建BLB Client对象 +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com +client, _ := appblb.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/appblb" + +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := appblb.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/appblb" + +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := appblb.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BLB时,创建的BLB Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BLB Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +应用型blb实例针对用户复杂应用部署架构,特别是大型网站架构。使用基于策略的网络管理框架构建,实现业务驱动的流量负载均衡。 + +## 实例管理 + +### 创建实例 + +通过以下代码,可以创建一个应用型LoadBalancer,返回分配的服务地址及实例ID +```go +args := &appblb.CreateLoadBalancerArgs{ + // 设置实例名称 + Name: "sdkBlb", + // 设置实例描述 + Description: "sdk create", + // 设置实例所属vpc + VpcId: vpcId, + // 设置实例所属子网 + SubnetId: subnetId, +} + +// 若要为实例设置标签,可以按照以下代码,标签设置之后,不可修改和删除 +args.Tags = []model.TagModel{ + { + TagKey: "key", + TagValue: "value", + }, +} +result, err := client.CreateLoadBalancer(args) +if err != nil { + fmt.Println("create appblb failed:", err) +} else { + fmt.Println("create appblb success: ", result) +} +``` + +### 更新实例 + +通过以下代码,可以更新一个LoadBalancer的配置信息,如实例名称和描述 +```go +args := &appblb.UpdateLoadBalancerArgs{ + Name: "testSdk", + Description: "test desc", +} +err := client.UpdateLoadBalancer(blbId, args) +if err != nil { + fmt.Println("update appblb failed:", err) +} else { + fmt.Println("update appblb success") +} +``` +### 查询已有的实例 + +通过以下代码,可以查询用户账户下所有LoadBalancer的信息 +```go +args := &appblb.DescribeLoadBalancersArgs{} + +// 支持按LoadBalancer的id、name、address进行查询,匹配规则支持部分包含(不支持正则) +args.BlbId = blbId +args.Name = blbName +args.Address = blbAddress +args.ExactlyMatch = true + +// 支持查找绑定指定BLB的LoadBalancer,通过blbId参数指定 +args.BlbId = blbId + +result, err := client.DescribeLoadBalancers(args) +if err != nil { + fmt.Println("list all appblb failed:", err) +} else { + fmt.Println("list all appblb success: ", result) +} +``` + +### 查询实例详情 + +通过以下代码,可以按id查询用户账户下特定的应用型LoadBalancer的详细信息,包含LoadBalancer所有的监听器端口信息 +```go +result, err := client.DescribeLoadBalancerDetail(blbId) +if err != nil { + fmt.Println("get appblb detail failed:", err) +} else { + fmt.Println("get appblb detail success: ", result) +} +``` + +### 释放实例 + +通过以下代码,可以释放指定LoadBalancer,被释放的LoadBalancer无法找回 +```go +err := client.DeleteLoadBalancer(blbId) +if err != nil { + fmt.Println("delete appblb failed:", err) +} else { + fmt.Println("delete appblb success") +} +``` + +## 服务器组管理 + +### 创建应用型服务器组 + +通过以下代码,在指定应用型BLB下,创建一个服务器组,用来绑定后端服务器,以及为监听器开放相应的端口 +```go +args := &appblb.CreateAppServerGroupArgs{ + // 设置服务器组名称 + Name: "sdkTest", + // 设置服务器组描述 + Description: "sdk test desc", +} + +// 若想直接绑定后端服务器,可以设置以下参数 +args.BackendServerList = []appblb.AppBackendServer{ + { + InstanceId: instanceId, + Weight: 50, + }, +} + +result, err := client.CreateAppServerGroup(blbId, args) +if err != nil { + fmt.Println("create server group failed:", err) +} else { + fmt.Println("create server group success: ", result) +} +``` + +### 更新服务器组 + +通过以下代码,更新指定LoadBalancer下的服务器组参数,所有请求参数中指定的域都会被更新,未指定的域保持不变 +```go +args := &appblb.UpdateAppServerGroupArgs{ + // 设置要更新的服务器组ID + SgId: serverGroupId, + // 设置新的服务器组名称 + Name: "testSdk", + // 设置新的服务器组描述 + Description: "test desc", +} +err := client.UpdateAppServerGroup(blbId, args) +if err != nil { + fmt.Println("update server group failed:", err) +} else { + fmt.Println("update server group success: ", result) +} +``` + +### 查询服务器组 + +通过以下代码,查询指定LoadBalancer下所有服务器组的信息 +```go +args := &appblb.DescribeAppServerGroupArgs{} + +// 按BLBID、name为条件进行全局查询 +args.BlbId = blbId +args.Name = servergroupName +args.ExactlyMatch = true + +result, err := client.DescribeAppServerGroup(blbId, args) +if err != nil { + fmt.Println("describe server group failed:", err) +} else { + fmt.Println("describe server group success: ", result) +} +``` + +### 删除服务器组 + +通过以下代码,删除服务器组,通过服务器组id指定 +```go +args := &appblb.DeleteAppServerGroupArgs{ + // 要删除的服务器组ID + SgId: serverGroupId, +} +err := client.DeleteAppServerGroup(blbId, args) +if err != nil { + fmt.Println("delete server group failed:", err) +} else { + fmt.Println("delete server group success: ", result) +} +``` + +### 创建应用型服务器组端口 + +通过以下代码,在指定应用型BLB下,创建一个服务器组后端端口,将发往该端口的所有流量按权重轮询分发到其绑定的对应服务器列表中的服务器 +```go +args := &appblb.CreateAppServerGroupPortArgs{ + // 端口所属服务器组ID + SgId: serverGroupId, + // 监听的端口号 + Port: 80, + // 监听的协议类型 + Type: "TCP", +} + +// 可以选择设置相应健康检查协议的参数 +args.HealthCheck = "TCP" +args.HealthCheckPort = 30 +args.HealthCheckIntervalInSecond = 10 +args.HealthCheckTimeoutInSecond = 10 + +result, err := client.CreateAppServerGroupPort(blbId, args) +if err != nil { + fmt.Println("create server group port failed:", err) +} else { + fmt.Println("create server group port success: ", result) +} +``` + +> **提示:** +> - 配置健康检查协议的参数,详细请参考BLB API 文档[创建应用型服务器组端口](https://cloud.baidu.com/doc/BLB/s/Bjwvxny4u#createappservergroupport%E5%88%9B%E5%BB%BA%E5%BA%94%E7%94%A8%E5%9E%8B%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BB%84%E7%AB%AF%E5%8F%A3) + +### 更新服务器组端口 + +通过以下代码,根据id更新服务器组端口 +```go +args := &appblb.UpdateAppServerGroupPortArgs{ + // 端口所属服务器组ID + SgId: serverGroupId, + // 端口Id,由创建创建应用型服务器组端口返回 + PortId: portId, + // 设置健康检查协议参数 + HealthCheck: "TCP", + HealthCheckPort: 30, + HealthCheckIntervalInSecond: 10, + HealthCheckTimeoutInSecond: 10, +} +err := client.UpdateAppServerGroupPort(blbId, args) +if err != nil { + fmt.Println("update server group port failed:", err) +} else { + fmt.Println("update server group port success: ", result) +} +``` + +> **提示:** +> - 配置健康检查协议的参数,详细请参考BLB API 文档[更新服务器组端口](https://cloud.baidu.com/doc/BLB/s/Bjwvxny4u#updateappservergroupport%E6%9B%B4%E6%96%B0%E6%9C%8D%E5%8A%A1%E5%99%A8%E7%BB%84%E7%AB%AF%E5%8F%A3) + +### 删除服务器组端口 + +通过以下代码,删除服务器组端口,通过服务器组id指定 +```go +args := &appblb.DeleteAppServerGroupPortArgs{ + // 端口所属服务器组ID + SgId: serverGroupId, + // 要删除的端口服务ID列表 + PortIdList: []string{portId}, +} +err := client.DeleteAppServerGroupPort(blbId, args) +if err != nil { + fmt.Println("delete server group port failed:", err) +} else { + fmt.Println("delete server group port success: ", result) +} +``` + +### 添加应用型BLB后端RS + +通过以下代码,在指定应用型BLB和服务器组下绑定后端服务器RS +```go +args := &appblb.CreateBlbRsArgs{ + BlbRsWriteOpArgs: appblb.BlbRsWriteOpArgs{ + // RS所属服务器组ID + SgId: serverGroupId, + // 配置后端服务器的列表及权重 + BackendServerList: []appblb.AppBackendServer{ + {InstanceId: instanceId, Weight: 30}, + }, + }, +} +err := client.CreateBlbRs(blbId, args) +if err != nil { + fmt.Println("create blbRs failed:", err) +} else { + fmt.Println("create blbRs success: ", result) +} +``` + +### 更新服务器组下挂载的RS权重 + +通过以下代码,更新指定服务器组下的RS信息 +```go +args := &appblb.UpdateBlbRsArgs{ + BlbRsWriteOpArgs: appblb.BlbRsWriteOpArgs{ + // RS所属服务器组ID + SgId: serverGroupId, + // 配置要更新的后端服务器的列表及权重 + BackendServerList: []appblb.AppBackendServer{ + {InstanceId: instanceId, Weight: 60}, + }, + }, +} +err := client.UpdateBlbRs(blbId, args) +if err != nil { + fmt.Println("update blbRs failed:", err) +} else { + fmt.Println("update blbRs success: ", result) +} +``` + +### 查询服务器组下的RS列表信息 + +通过以下代码,查询指定LoadBalancer下所有服务器组的信息 +```go +args := &appblb.DescribeBlbRsArgs{ + // RS所属服务器组ID + SgId: serverGroupId, +} +result, err := client.DescribeBlbRs(blbId, args) +if err != nil { + fmt.Println("describe blbRs failed:", err) +} else { + fmt.Println("describe blbRs success: ", result) +} +``` + +### 删除服务器组下挂载的rs + +通过以下代码,删除服务器组,通过服务器组id指定 +```go +args := &appblb.DeleteBlbRsArgs{ + // RS所属服务器组ID + SgId: serverGroupId, + // 要从RS列表中删除的实例列表 + BackendServerIdList: []string{instanceId}, +} +err := client.DeleteBlbRs(blbId, args) +if err != nil { + fmt.Println("delete blbRs failed:", err) +} else { + fmt.Println("delete blbRs success: ", result) +} +``` + +### 查询服务器组下绑定的server + +通过以下代码,查询服务器组下绑定的server +```go +result, err := client.DescribeRsMount(blbId, serverGroupId) +if err != nil { + fmt.Println("describe mount Rs list failed:", err) +} else { + fmt.Println("describe mount Rs list success: ", result) +} +``` + +### 查询服务器组下未绑定的RS + +通过以下代码,查询服务器组下未绑定的RS +```go +result, err := client.DescribeRsUnMount(blbId, serverGroupId) +if err != nil { + fmt.Println("describe unmount Rs list failed:", err) +} else { + fmt.Println("describe unmount Rs list success: ", result) +} +``` + +## 监听器管理 + +### 创建TCP监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于TCP协议的应用型blb监听器,监听一个前端端口,将发往该端口的所有TCP流量,根据策略进行转发 +```go +args := &appblb.CreateAppTCPListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 90, + // 负载均衡算法,支持RoundRobin/LeastConnection/Hash + Scheduler: "RoundRobin", + // TCP设置链接超时时间,默认900秒,需要为10-4000之间的整数 + TcpSessionTimeout: 1000, +} +err := client.CreateAppTCPListener(BLBID, args) +if err != nil { + fmt.Println("create TCP Listener failed:", err) +} else { + fmt.Println("create TCP Listener success") +} +``` + +### 更新TCP监听器 + +通过以下代码,更新指定LoadBalancer下的TCP监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &appblb.UpdateAppTCPListenerArgs{ + UpdateAppListenerArgs: appblb.UpdateAppListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 90, + // 更新负载均衡的算法 + Scheduler: "Hash", + // 更新tcp链接超时时间 + TcpSessionTimeout: 2000, + }, +} +err := client.UpdateAppTCPListener(BLBID, args) +if err != nil { + fmt.Println("update TCP Listener failed:", err) +} else { + fmt.Println("update TCP Listener success") +} +``` + +### 查询TCP监听器 + +通过以下代码,查询指定LoadBalancer下所有TCP监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &appblb.DescribeAppListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 90, +} +result, err := client.DescribeAppTCPListeners(BLBID, args) +if err != nil { + fmt.Println("describe TCP Listener failed:", err) +} else { + fmt.Println("describe TCP Listener success: ", result) +} +``` + +### 创建UDP监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于UDP协议的应用型监听器,监听一个前端端口,将发往该端口的所有UDP流量,根据策略进行转发 +```go +args := &appblb.CreateAppUDPListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection/Hash + Scheduler: "RoundRobin", +} +err := client.CreateAppUDPListener(BLBID, args) +if err != nil { + fmt.Println("create UDP Listener failed:", err) +} else { + fmt.Println("create UDP Listener success") +} +``` + +### 更新UDP监听器 + +通过以下代码,更新指定LoadBalancer下的UDP监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &appblb.UpdateAppUDPListenerArgs{ + UpdateAppListenerArgs: appblb.UpdateAppListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 80, + // 更新负载均衡的算法 + Scheduler: "Hash", + }, +} +err := client.UpdateAppUDPListener(BLBID, args) +if err != nil { + fmt.Println("update UDP Listener failed:", err) +} else { + fmt.Println("update UDP Listener success") +} +``` + +### 查询UDP监听器 + +通过以下代码,查询指定LoadBalancer下所有UDP监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &appblb.DescribeAppListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 80, +} +result, err := client.DescribeAppUDPListeners(BLBID, args) +if err != nil { + fmt.Println("describe UDP Listener failed:", err) +} else { + fmt.Println("describe UDP Listener success: ", result) +} +``` + +### 创建HTTP监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于HTTP协议的应用型监听器,监听一个前端端口,将发往该端口的所有HTTP请求,根据策略转发到后端服务器监听的后端端口上 +```go +args := &appblb.CreateAppHTTPListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection + Scheduler: "RoundRobin", +} +err := client.CreateAppHTTPListener(BLBID, args) +if err != nil { + fmt.Println("create HTTP Listener failed:", err) +} else { + fmt.Println("create HTTP Listener success") +} +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[创建HTTP监听器](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#createapphttplistener%E5%88%9B%E5%BB%BAhttp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新HTTP监听器 + +通过以下代码,更新指定LoadBalancer下的HTTP监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &appblb.UpdateAppHTTPListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 80, + // 更新负载均衡的算法 + Scheduler: "LeastConnection", + // 开启会话保持功能 + KeepSession: true, +} +err := client.UpdateAppHTTPListener(BLBID, args) +if err != nil { + fmt.Println("update HTTP Listener failed:", err) +} else { + fmt.Println("update HTTP Listener success") +} +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[更新HTTP监听器](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#updateapphttplistener%E6%9B%B4%E6%96%B0http%E7%9B%91%E5%90%AC%E5%99%A8) + +### 查询HTTP监听器 + +通过以下代码,查询指定LoadBalancer下所有HTTP监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &appblb.DescribeAppListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 80, +} +result, err := client.DescribeAppHTTPListeners(BLBID, args) +if err != nil { + fmt.Println("describe HTTP Listener failed:", err) +} else { + fmt.Println("describe HTTP Listener success: ", result) +} +``` + +### 创建HTTPS监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于HTTPS协议的应用型监听器,监听一个前端端口,将发往该端口的所有HTTPS请求,先通过SSL卸载转换为HTTP请求后,再根据策略转发到后端服务器监听的后端端口上 +```go +args := &appblb.CreateAppHTTPSListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection + Scheduler: "RoundRobin", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.CreateAppHTTPSListener(BLBID, args) +if err != nil { + fmt.Println("create HTTPS Listener failed:", err) +} else { + fmt.Println("create HTTPS Listener success") +} +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[创建HTTPS监听器](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#createapphttpslistener%E5%88%9B%E5%BB%BAhttps%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新HTTPS监听器 + +通过以下代码,更新指定LoadBalancer下的HTTPS监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &appblb.UpdateAppHTTPSListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 80, + // 更新负载均衡的算法 + Scheduler: "LeastConnection", + // 开启会话保持功能 + KeepSession: true, + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.UpdateAppHTTPSListener(BLBID, args) +if err != nil { + fmt.Println("update HTTPS Listener failed:", err) +} else { + fmt.Println("update HTTPS Listener success") +} +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[更新HTTPS监听器](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#updateapphttpslistener%E6%9B%B4%E6%96%B0https%E7%9B%91%E5%90%AC%E5%99%A8) + +### 查询HTTPS监听器 + +通过以下代码,查询指定LoadBalancer下所有HTTPS监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &appblb.DescribeAppListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 80, +} +result, err := client.DescribeAppHTTPSListeners(BLBID, args) +if err != nil { + fmt.Println("describe HTTPS Listener failed:", err) +} else { + fmt.Println("describe HTTPS Listener success: ", result) +} +``` + +### 创建SSL监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于SSL协议的应用型blb监听器,监听一个前端端口,将发往该端口的所有SSL流量,根据策略进行转发 +```go +args := &appblb.CreateAppSSLListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection/Hash + Scheduler: "RoundRobin", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.CreateAppSSLListener(BLBID, args) +if err != nil { + fmt.Println("create SSL Listener failed:", err) +} else { + fmt.Println("create SSL Listener success") +} +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[创建SSL监听器](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#createappssllistener%E5%88%9B%E5%BB%BAssl%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新SSL监听器 + +通过以下代码,更新指定LoadBalancer下的SSL监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &appblb.UpdateAppSSLListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 80, + // 更新负载均衡的算法 + Scheduler: "LeastConnection", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.UpdateAppSSLListener(BLBID, args) +if err != nil { + fmt.Println("update SSL Listener failed:", err) +} else { + fmt.Println("update SSL Listener success") +} +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[更新SSL监听器](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#updateappssllistener%E6%9B%B4%E6%96%B0ssl%E7%9B%91%E5%90%AC%E5%99%A8) + +### 查询SSL监听器 + +通过以下代码,查询指定LoadBalancer下所有HTTPS监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &appblb.DescribeAppListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 80, +} +result, err := client.DescribeAppSSLListeners(BLBID, args) +if err != nil { + fmt.Println("describe SSL Listener failed:", err) +} else { + fmt.Println("describe SSL Listener success: ", result) +} +``` + +### 删除监听器 + +通过以下代码,释放指定LoadBalancer下的监听器,监听器通过监听端口来指定,支持批量释放 +```go +args := &appblb.DeleteAppListenersArgs{ + // 要删除的监听器监听的端口 + PortList: []uint16{80}, +} +err := client.DeleteAppListeners(BLBID, args) +if err != nil { + fmt.Println("delete Listeners failed:", err) +} else { + fmt.Println("delete Listeners success: ", result) +} +``` + +### 创建策略 + +通过以下代码,在指定应用型BLB监听器端口下创建策略 +```go +args := &appblb.CreatePolicysArgs{ + // 需要绑定策略的监听器监听的端口 + ListenerPort: 80, + // 需要绑定的策略,其中TCP/UDP/SSL仅支持绑定一个策略,HTTP/HTTPS支持绑定多个策略 + AppPolicyVos: []appblb.AppPolicy{ + { + // 策略描述 + Description: "test policy", + // 策略绑定的服务器组ID + AppServerGroupId: servergroupId, + // 目标端口号 + BackendPort: 80, + // 策略的优先级,有效取值范围为1-32768 + Priority: 301, + // 策略的规则列表,TCP/UDP/SSL仅支持{*:*}策略 + RuleList: []appblb.AppRule{ + { + Key: "*", + Value: "*", + }, + }, + }, + }, +} +err := client.CreatePolicys(blbId, args) +if err != nil { + fmt.Println("create policy failed:", err) +} else { + fmt.Println("create policy success") +} +``` + +> **提示:** +> - 策略中backendPort参数,即目标端口号,当listenerPort对应监听器为TCP或SSL时需要传入对应服务器组(appServerGroupId)下开放的TCP端口号;当listenerPort对应监听器为HTTP或HTTPS时需要传入对应服务器组(appServerGroupId)下开放的HTTP端口号;当listenerPort对应监听器为UDP时需要传入对应服务器组(appServerGroupId)下开放的UDP端口号 +> - 各个协议可绑定的策略的具体配置参数,可以参考BLB API 文档[创建策略](https://cloud.baidu.com/doc/BLB/s/ujwvxnyux#createpolicys%E5%88%9B%E5%BB%BA%E7%AD%96%E7%95%A5) + +### 查询对应BLB端口下策略信息 + +通过以下代码,查询指定LoadBalancer下所有服务器组的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &appblb.DescribePolicysArgs{ + // 要查询的监听器端口号 + Port: 80, +} +result, err := client.DescribePolicys(blbId, args) +if err != nil { + fmt.Println("describe policy failed:", err) +} else { + fmt.Println("describe policy success: ", result) +} +``` + +### 批量删除策略 + +通过以下代码,批量删除对应BLB端口下的策略 +```go +args := &appblb.DeletePolicysArgs{ + // 要删除策略所在监听器的端口号 + Port: 80, + // 要删除的策略ID列表 + PolicyIdList: []string{describeResult.PolicyList[0].Id}, +} +err := client.DeletePolicys(blbId, args) +if err != nil { + fmt.Println("delete policy failed:", err) +} else { + fmt.Println("delete policy success") +} +``` + +### 创建应用型IP组 + +通过以下代码,在指定应用型BLB下,创建一个IP组,用来添加IP组成员和IP组协议 +```go +args := &appblb.CreateAppIpGroupArgs{ + // 设置IP组名称 + Name: "sdkTest", + // 设置IP组描述 + Desc: "sdk test desc", +} + +// 若想直接添加IP组成员,可以设置以下参数 +args.MemberList = []appblb.AppIpGroupMember{ + { + Ip: "192.168.0.25", + Port: 80, + Weight: 50, + }, +} + +result, err := client.CreateAppIpGroup(blbId, args) +if err != nil { + fmt.Println("create ip group failed:", err) +} else { + fmt.Println("create ip group success: ", result) +} +``` + +### 更新IP组 + +通过以下代码,更新指定LoadBalancer下的IP组,所有请求参数中指定的域都会被更新,未指定的域保持不变 +```go +args := &appblb.UpdateAppIpGroupArgs{ + // 设置要更新的IP组ID + IpGroupId: ipGroupId, + // 设置新的IP组名称 + Name: "testSdk", + // 设置新的IP组描述 + Desc: "test desc", +} +err := client.UpdateAppIpGroup(blbId, args) +if err != nil { + fmt.Println("update ip group failed:", err) +} else { + fmt.Println("update ip group success: ") +} +``` + +### 查询IP组 + +通过以下代码,查询指定LoadBalancer下所有IP组的信息 +```go +args := &appblb.DescribeAppIpGroupArgs{} + +// 按blbId、name为条件进行全局查询 +args.Name = ipgroupName +args.ExactlyMatch = true + +result, err := client.DescribeAppIpGroup(blbId, args) +if err != nil { + fmt.Println("describe ip group failed:", err) +} else { + fmt.Println("describe ip group success: ", result) +} +``` + +### 删除IP组 + +通过以下代码,删除IP组,通过IP组id指定 +```go +args := &appblb.DeleteAppIpGroupArgs{ + // 要删除的IP组ID + IpGroupId: ipGroupId, +} +err := client.DeleteAppIpGroup(blbId, args) +if err != nil { + fmt.Println("delete ip group failed:", err) +} else { + fmt.Println("delete ip group success: ") +} +``` + +### 创建应用型IP组协议 + +通过以下代码,在指定应用型BLB下,创建一个IP组协议,定义IP组和后端ip之间传输协议 +```go +args := &appblb.CreateAppIpGroupBackendPolicyArgs{ + // 端口所属IP组ID + IpGroupId: ipGroupId, + // IP组协议类型 + Type: "TCP", +} + +// 可以选择设置相应健康检查协议的参数 +args.HealthCheckPort = 30 +args.HealthCheckIntervalInSecond = 10 +args.HealthCheckTimeoutInSecond = 10 +args.HealthCheckDownRetry = 3 +args.HealthCheckUpRetry = 3 +args.HealthCheckNormalStatus = "http_2xx|http_3xx" +args.HealthCheckUrlPath = "/" +args.UdpHealthCheckString = "udp" + +err := client.CreateAppIpGroupBackendPolicy(blbId, args) +if err != nil { + fmt.Println("create ip group backend policy failed:", err) +} else { + fmt.Println("create ip group backend policy success: ") +} +``` + +### 更新应用型IP组协议 + +通过以下代码,根据ID更新IP组协议 +```go +args := &appblb.UpdateAppIpGroupBackendPolicyArgs{ + // IP组ID + IpGroupId: ipGroupId, + // IP组协议的ID + Id: id, + // 设置健康检查协议参数 + HealthCheckPort: 30, + HealthCheckIntervalInSecond: 10, + HealthCheckTimeoutInSecond: 10, + HealthCheckDownRetry: 3, + HealthCheckUpRetry: 3, + HealthCheckNormalStatus = "http_2xx|http_3xx", + HealthCheckUrlPath = "/", + UdpHealthCheckString = "udp" + +} +err := client.UpdateAppIpGroupBackendPolicy(blbId, args) +if err != nil { + fmt.Println("update ip group backend policy failed:", err) +} else { + fmt.Println("update ip group backend policy success: ") +} +``` + +### 删除IP组协议 + +通过以下代码,删除IP组协议,通过IP组id指定 +```go +args := &appblb.DeleteAppIpGroupBackendPolicyArgs{ + // 端口所属IP组ID + IpGroupId: ipGroupId, + // 要删除的IP组协议ID列表 + BackendPolicyIdList: []string{backendPolicyId}, +} +err := client.DeleteAppIpGroupBackendPolicy(blbId, args) +if err != nil { + fmt.Println("delete ip group backend policy failed:", err) +} else { + fmt.Println("delete ip group backend policy success: ") +} +``` + +### 创建IP组成员 + +通过以下代码,在指定应用型BLB和IP组下创建IP组成员 +```go +args := &appblb.CreateAppIpGroupMemberArgs{ + AppIpGroupMemberWriteOpArgs: appblb.AppIpGroupMemberWriteOpArgs{ + // IP组成员所属IP组ID + IpGroupId: ipGroupId, + // 配置IP组列表IP、端口以及权重 + MemberList: []appblb.AppIpGroupMember{ + {Ip: "192.168.0.25", Port: 80, Weight: 30}, + }, + }, +} +err := client.CreateAppIpGroupMember(blbId, args) +if err != nil { + fmt.Println("create ip group member failed:", err) +} else { + fmt.Println("create ip group member success: ") +} +``` + +### 更新IP组成员 + +通过以下代码,更新指定IP组下的IP组成员信息 +```go +args := &appblb.UpdateAppIpGroupMemberArgs{ + AppIpGroupMemberWriteOpArgs: appblb.AppIpGroupMemberWriteOpArgs{ + // IP组成员所属IP组ID + IpGroupId: ipGroupId, + // IP组列表IP、端口以及权重 + MemberList: []appblb.AppIpGroupMember{ + {MemberId: memberId, Port: 80, Weight: 30}, + }, + }, +} +err := client.UpdateAppIpGroupMember(blbId, args) +if err != nil { + fmt.Println("update ip group member failed:", err) +} else { + fmt.Println("update ip group member success: ") +} +``` + +### 查询IP组成员列表信息 + +通过以下代码,查询指定LoadBalancer下所有IP组的信息 +```go +args := &appblb.DescribeAppIpGroupMemberArgs{ + // 成员所属IP组ID + IpGroupId: ipGroupId, +} +result, err := client.DescribeAppIpGroupMember(blbId, args) +if err != nil { + fmt.Println("describe ip group member failed:", err) +} else { + fmt.Println("describe ip group member success: ", result) +} +``` + +### 删除IP组成员 + +通过以下代码,删除IP组成员,通过IP组id指定 +```go +args := &appblb.DeleteAppIpGroupMemberArgs{ + // 成员所属IP组ID + IpGroupId: ipGroupId, + // 要删除的IP组成员id + MemberIdList: []string{memberId}, +} +err := client.DeleteAppIpGroupMember(blbId, args) +if err != nil { + fmt.Println("delete ip group member failed:", err) +} else { + fmt.Println("delete ip group member success: ") +} +``` + +### 创建策略(策略绑定IP组id) + +通过以下代码,在指定应用型BLB监听器端口下创建策略 +```go +args := &appblb.CreatePolicysArgs{ + // 需要绑定策略的监听器监听的端口 + ListenerPort: 80, + // 需要绑定的策略,其中TCP/UDP/SSL仅支持绑定一个策略,HTTP/HTTPS支持绑定多个策略 + AppPolicyVos: []appblb.AppPolicy{ + { + // 策略描述 + Description: "test policy", + // 策略绑定的服务器组ID + AppIpGroupId: ipGroupId, + // 策略的优先级,有效取值范围为1-32768 + Priority: 301, + // 策略的规则列表,TCP/UDP/SSL仅支持{*:*}策略 + RuleList: []appblb.AppRule{ + { + Key: "*", + Value: "*", + }, + }, + }, + }, +} +err := client.CreatePolicys(blbId, args) +if err != nil { + fmt.Println("create policy failed:", err) +} else { + fmt.Println("create policy success") +} +``` + + +# 错误处理 + +GO语言以error类型标识错误,BLB支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | BLB服务返回的错误 + +用户使用SDK调用BLB相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// blbClient 为已创建的BLB Client对象 +blbDetail, err := blbClient.DescribeLoadBalancerDetail(blbId) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get appblb detail success: ", blbDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向BLB发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当BLB服务端出现异常时,BLB服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BLB错误返回](https://cloud.baidu.com/doc/BLB/s/Djwvxnzw6) + +# 版本变更记录 + +## v0.9.1 [2019-09-26] + +首次发布: + + - 创建、查看、列表、更新、删除应用型BLB实例 + - 创建、列表、更新、删除服务器组 + - 创建、更新、删除服务器组端口 + - 创建、列表、更新、删除服务器组后端RS,并支持查询已绑定和未绑定的服务器 + - 创建、查看、更新、删除监听器端口,支持TCP/UDP/HTTP/HTTPS/SSL协议 + - 创建、查看、删除监听器相关策略 + +再次发布: + - 创建、列表、更新、删除IP组 + - 创建、更新、删除IP组协议 + - 创建、列表、更新、删除IP组成员 \ No newline at end of file diff --git a/bce-sdk-go/doc/AS.md b/bce-sdk-go/doc/AS.md new file mode 100644 index 0000000..cd4328b --- /dev/null +++ b/bce-sdk-go/doc/AS.md @@ -0,0 +1,321 @@ +# AS服务 + +# 概述 + +本文档主要介绍AS GO SDK的使用。在使用本文档前,您需要先了解 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[AS域名](https://cloud.baidu.com/doc/AS/s/fk3imcz57)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云AS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问AS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建AS Client + +AS Client是AS控制面服务的客户端,为开发者与AS控制面服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建AS Client + +通过AK/SK方式访问AS,用户可以参考如下代码新建一个AS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/as" //导入AS服务模块 +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个ASClient + asClient, err := as.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/as/index.html)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为AS的控制面服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`as.bj.baidubce.com`。 + +### 使用STS创建AS Client + +**申请STS token** + +AS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问AS,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建AS Client** + +申请好STS后,可将STS Token配置到AS Client中,从而实现通过STS Token创建AS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建AS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/as" //导入AS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建AS控制面服务的Client对象,Endpoint使用默认值 + asClient, err := as.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create as client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + asClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置AS Client时,无论对应AS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问AS + +AS支持HTTPS传输协议,您可以通过在创建AS Client对象时指定的Endpoint中指明HTTPS的方式,在AS GO SDK中使用HTTPS访问AS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/as" + +ENDPOINT := "https://as.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +asClient, _ := as.NewClient(AK, SK, ENDPOINT) +``` + +## 配置AS Client + +如果用户需要配置AS Client的一些细节的参数,可以在创建AS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问AS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/as" + +//创建AS Client对象 +AK, SK := , +ENDPOINT := "as.bj.baidubce.com +client, _ := as.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/AS" + +AK, SK := , +ENDPOINT := "as.bj.baidubce.com" +client, _ := as.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/AS" + +AK, SK := , +ENDPOINT := "as.bj.baidubce.com" +client, _ := as.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问AS时,创建的AS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建AS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +百度智能云弹性伸缩(Auto Scaling)是自动化扩缩容用户云资源的管理服务,当您业务所需的云资源用量经常性变化时,弹性伸缩会是您使用云资源的理想方式。 + +## 查询伸缩组列表接口 + +### 接口描述 +可查询所有伸缩组的详细信息。 + +### 请求示例 + +```go +req := &as.ListAsGroupRequest{ + // 可选,伸缩组名称 + GroupName: "as-Group-Name", + // 可选,批量获取列表的查询的起始位置,是一个由系统生成的字符串 + Marker: "marker", + // 可选,每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 + MaxKeys: 100, +} +resp, err := asClient.ListAsGroup(req) +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考AS API 文档[查询伸缩组列表](https://cloud.baidu.com/doc/AS/s/hk3imj0oq#%E6%9F%A5%E8%AF%A2%E4%BC%B8%E7%BC%A9%E7%BB%84%E5%88%97%E8%A1%A8) + +## 查询伸缩组详情接口 + +### 接口描述 +可查询单个伸缩组的详细信息。 + +### 请求示例 +```go +req := &as.GetAsGroupRequest{ + // 必填,待查询的伸缩组ID + GroupId: "asg-wqksXo95", +} +resp, err := asClient.GetAsGroup(req) +``` + +## 查询伸缩组下节点列表 + +### 接口描述 +可查询指定伸缩组下节点的详细信息。 + +### 请求示例 +```go +req := &as.ListAsNodeRequest{ + // 必填,伸缩组ID + GroupId: "asg-wqksXo95", + // 可选,批量获取列表的查询的起始位置,是一个由系统生成的字符串 + Marker: "marker", + // 可选,每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 + MaxKeys: 100, +} +resp, err := asClient.ListAsNode(req) +``` + +## 伸缩组扩容 + +### 接口描述 +在指定伸缩组下添加节点。 + +### 请求示例 +```go +req := &as.IncreaseAsGroupRequest{ + // 必填,伸缩组ID + GroupId: "asg-Hhm2ucIK", + // 必填,扩容可指定可用区(扩容时会与伸缩组配置的可用区取交集) + Zone: []string{"zoneB"}, + // 扩容节点数量 + NodeCount: 1, + // 扩容时的可用区选择策略 + // Priority - 以单独可用区进行创建 + // Balanced - 在选定可用区中均衡创建 + ExpansionStrategy:"Priority" +} +err := asClient.IncreaseAsGroup(req) +``` + +## 伸缩组缩容 + +### 接口描述 +用于伸缩组下节点的缩容。 + +### 请求示例 +```go +req := &as.DecreaseAsGroupRequest{ + // 必填,伸缩组ID + GroupId: "asg-Hhm2ucIK", + // 必填,手动缩容指定的实例短Id + Nodes: []string{"i-z0PXqFD3"}, +} +err := asClient.DecreaseAsGroup(req) +``` + + +## 客户端异常 + +客户端异常表示客户端尝试向AS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当AS服务端出现异常时,AS服务端会返回给用户相应的错误信息,以便定位问题 + diff --git a/bce-sdk-go/doc/BBC.md b/bce-sdk-go/doc/BBC.md new file mode 100644 index 0000000..38f2f7e --- /dev/null +++ b/bce-sdk-go/doc/BBC.md @@ -0,0 +1,1529 @@ +# BBC服务 + +# 概述 + +本文档主要介绍BBC GO SDK的使用。在使用本文档前,您需要先了解BBC的一些基本知识。若您还不了解BBC,可以 +参考[产品描述](https://cloud.baidu.com/doc/BBC/s/ojwvxu4di)和 +[操作指南](https://cloud.baidu.com/doc/BBC/s/fjwvxu86k)。 + +# 初始化 + +## 确认Endpoint +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于 +[BBC访问域名](https://cloud.baidu.com/doc/BBC/s/3jwvxu9iz#%E6%9C%8D%E5%8A%A1%E5%9F%9F%E5%90%8D)的部分, +理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +由于BBC维修任务并不按照区域区分,在访问维修任务相关接口时,Endpoint统一使用北京区域的BBC访问域名。 + +## 获取密钥 + +要使用百度云BBC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。 +AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BBC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BBC Client + +BBC Client是BBC服务的客户端,为开发者与BBC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BBC Client + +通过AK/SK方式访问BBC,用户可以参考如下代码新建一个Bbc Client: + +```go +import "github.com/baidubce/bce-sdk-go/services/bbc" + +func main() { + // 用户的Access Key ID和Secret Access Key + AK, SK := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BBClient + bbcClient, err := bbc.NewClient(AK, SK, ENDPOINT) +} +``` +在上面代码中,`AK`对应控制台中的“Access Key ID”,`SK`对应控制台中的“Access Key Secret”, +获取方式请参考[获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb)。 +第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BBC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bbc.bj.baidubce.com`。 + +## 配置HTTPS协议访问BBC + +BBC支持HTTPS传输协议,您可以通过在创建BBC Client对象时指定的Endpoint中指明HTTPS的方式,在BBC GO SDK中使用HTTPS访问BBC服务: + +```go +import "github.com/baidubce/bce-sdk-go/services/bbc" + +ENDPOINT := "https://bbc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +bbcClient, _ := bbc.NewClient(AK, SK, ENDPOINT) +``` +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +import "github.com/baidubce/bce-sdk-go/services/bbc" + +AK, SK := , +ENDPOINT := "bbc.bj.baidubce.com" +client, _ := bbc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bbc" + +AK, SK := , +ENDPOINT := "bbc.bj.baidubce.com" +client, _ := bbc.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BBC时,创建的BBC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者. 后者为使用STS鉴权时使用 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +# 主要接口 + +云服务器BCC(Baidu Cloud Compute)是处理能力可弹性伸缩的计算服务。 +管理方式比物理服务器更简单高效,可根据您的业务需要创建、释放任意多台云服务器实例,提升运维效率。 + +## 实例 + +### 创建实例 + +使用以下代码可以创建一个物理机实例: +```go +createInstanceArgs := &CreateInstanceArgs{ + // 输入你选择的flavor(套餐)ID,通过SDK获取可用flavor id的方法详见套餐章节 + FlavorId: "your-choose-flavor-id", + // 输入你要创建instance使用的镜像ID,通过SDK获取可用镜像ID的方法详见镜像章节 + ImageId: "your-choose-image-id", + // 输入你要创建instance使用的raid ID,通过SDK获取可用raid id的方法详见套餐章节 + RaidId: "your-choose-raid-id", + // 输入待创建物理磁盘的大小,单位为GB,缺省为20 + RootDiskSizeInGb: 20, + // 批量创建(购买)的虚拟机实例个数,必须为大于0的整数,可选参数,缺省为1 + PurchaseCount: 1, + // 可用区,格式为:国家-区域-可用区,如'中国-北京-可用区A'就是'cn-bj-a' + ZoneName: "cn-bj-a", + // 指定子网 ID,必填参数 + SubnetId: "your-choose-subnet-id", + // 设置内网IP(只有智能卡套餐支持自定义内网IP) + InternalIps []string internalIps + // 指定安全组id,可选参数 + SecurityGroupId: "your-choose-security-group-id" + // 设置创建BCC使用的企业安全组,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupId: "enterpriseSecurityGroupId" + // 使用 uuid 生成一个长度不超过64位的ASCII字符串 + ClientToken: "random-uuid", + //创建实例支持幂等的token,永久有效 + RequestToken string "requestToken" + // 选择付费方式 + Billing: Billing{ + PaymentTiming: PaymentTimingPostPaid, + Reservation: Reservation{ + Length: 1, + TimeUnit: "Month", + }, + }, + // 指定使用的部署集id,可选参数,通过SDK获取可用部署集id的方法详见部署集章节 + DeploySetId: "your-choose-raid-id", + // 设置实例管理员密码(8-16位字符,英文,数字和符号必须同时存在,符号仅限!@#$%^*()) + AdminPass: "your-admin-pass", + // 实例名称 + Name: "your-choose-instance-name", + // 实例主机名,可选参数,若不选则主机名和实例名称保持一致(实例名称不包含中文名时) + // 仅支持小写字母、数字以及- . 特殊字符,不可连续使用特殊符号,不支持特殊符号开头或结尾,长度2-64 + Hostname: "your-choose-instance-hostname", + // 支持幂等的token + RequestToken: "requestToken", + // 指定是否开启numa true为开启,false为关闭 + EnableNuma: true, + // 指定系统盘文件系统,当前合法值:xfs,ext4 + RootPartitionType: "your-choose-rootPartitionType", + // 指定数据盘文件系统,当前合法值:xfs,ext4 + DataPartitionType: "your-choose-dataPartitionType", + // 指定实例绑定标签 + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagVaule", + }, + }, +} +if res, err := bbcClient.CreateInstance(createInstanceArgs); err != nil { + fmt.Println("create instance failed: ", err) +} else { + fmt.Println("create instance success, instanceId: ", res.InstanceIds[0]) +} +``` + +> **注意:** +>付费方式(PaymentTiming)可选: +>- 后付费: PaymentTimingPostPaid +>- 预付费: PaymentTimingPrePaid + +### 查询实例列表 +使用以下代码查询所有BBC实例的列表及详情信息: +```go +listArgs := &ListInstancesArgs{ + // 批量获取列表的查询起始位置,是一个由系统产生的字符串 + Marker: "your-marker", + // 设置返回数据大小,缺省为1000 + MaxKeys: 100, + // 通过internal Ip过滤BBC列表 + InternalIp: "your-choose-internal-ip", +} +if res, err := bbcClient.ListInstances(listArgs); err != nil { + fmt.Println("list instances failed: ", err) +} else { + fmt.Println("list instances success, result: ", res) +} +``` +### 查询实例详情 +使用以下代码可以查询指定BBC实例的详细信息: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +//设置是否展示部署集字段 +isDeploySet := "your-isDeploySet" +if res, err := bbcClient.GetInstanceDetail(instanceId); err != nil { + fmt.Println("get instance detail failed: ", err) +} else { + fmt.Println("get instance detail success, result: ", res) +} +``` +### 查询带部署集相关字段实例详情 +查询带部署集相关字段实例详情: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +//设置是否展示部署集字段true or false +isDeploySet := "your-isDeploySet" + +if res, err := bccClient.GetInstanceDetailWithDeploySet(instanceId,isDeploySet); err != nil { + fmt.Println("get instance detail failed: ", err) +} else { + fmt.Println("get instance detail success, result: ", res) +} +``` + +### 启动实例 +使用以下代码可以启动指定BBC实例,实例状态必须为 Stopped,调用此接口才可以成功返回,否则提示409错误: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bbcClient.StartInstance(instanceId); err != nil { + fmt.Println("start instance failed: ", err) +} else { + fmt.Println("start instance success.") +} +``` + +### 停止实例 +使用以下代码可以停止指定BBC实例,只有状态为 Running 的实例才可以进行此操作,否则提示 409 错误: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +// 是否强制停止实例,为True代表强制停止 +forceStop := true +if err := bbcClient.StopInstance(instanceId, forceStop); err != nil { + fmt.Println("stop instance failed: ", err) +} else { + fmt.Println("stop instance success.") +} +``` + +### 重启实例 +使用以下代码可以重启指定BBC实例,只有状态为 Running 的实例才可以进行此操作,否则提示 409 错误: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +// 是否强制停止实例,为True代表强制停止 +forceStop := true +if err := bbcClient.RebootInstance(instanceId, forceStop); err != nil { + fmt.Println("reboot instance failed: ", err) +} else { + fmt.Println("reboot instance success.") +} +``` + +### 修改实例名称 +使用以下代码可以修改指定BBC实例的名称: +```go +modifyInstanceNameArgs := &ModifyInstanceNameArgs{ + Name: "new_bbc_name", +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bbcClient.ModifyInstanceName(instanceId, modifyInstanceNameArgs); err != nil { + fmt.Println("modify instance name failed: ", err) +} else { + fmt.Println("modify instance name success.") +} +``` + +### 修改实例描述 +使用以下代码可以修改指定BBC实例的描述: +```go +modifyInstanceDescArgs := &ModifyInstanceDescArgs{ + Description: "new_bbc_description", +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bbcClient.ModifyInstanceDesc(instanceId, modifyInstanceDescArgs); err != nil { + fmt.Println("modify instance desc failed: ", err) +} else { + fmt.Println("modify instance desc success.") +} +``` + +### 实例变更子网 + +如下代码可以变更实例的子网 +```go +instanceChangeVpcArgs := &api.InstanceChangeSubnetArgs{ + InstanceId: instanceId, + SubnetId: subnetId, + InternalIp: internalIp, + Reboot: false, +} +err := bbcClient.InstanceChangeSubnet(args) +if err != nil { + fmt.Println("change instance subnet failed:", err) +} else { + fmt.Println("change instance subnet success") +} +``` + +> **提示:** +> - 变更子网后默认自动重启,用户选择是否执行该操作。 +> - 变更子网的范围目前仅支持在同AZ下变更子网,不支持跨AZ或跨VPC变更子网。 + +### 修改实例VPC +使用以下代码可以修改指定BBC实例所在的VPC: +```go +instanceChangeVpcArgs := &InstanceChangeVpcArgs{ + InstanceId: "your-choose-instance-id", + SubnetId: "new_subnet_id_in_vpc", + InternalIp: internalIp, + Reboot: true, +} +if err := bbcClient.InstanceChangeVpc(instanceChangeVpcArgs); err != nil { + fmt.Println("modify instance vpc failed: ", err) +} else { + fmt.Println("modify instance vpc success.") +} +``` + +> **提示:** +> - 变更VPC后默认自动重启,用户选择是否执行该操作。 +> - 变更VPC后仅保留主网卡主IP(在新子网中自动分配),实例上的辅助IP和安全组等信息不跟随主体迁移。 + + +### 重装实例 +使用以下代码可以使用镜像重建指定BBC实例: +```go +rebuildArgs := &RebuildInstanceArgs{ + // 设置使用的镜像id + ImageId: "your-choose-image-id", + // 设置管理员密码 + AdminPass: "your-new-admin-pass", + // 是否保留数据。当该值为true时,raidId和sysRootSize字段不生效 + IsPreserveData: false, + // 此参数在isPreserveData为false时为必填,在isPreserveData为true时不生效 + RaidId: "your_raid_id", + // 系统盘根分区大小,默认为20G,取值范围为20-100。此参数在isPreserveData为true时不生效 + SysRootSize: 20, + // 指定系统盘文件系统,当前合法值:xfs,ext4 + RootPartitionType: "your-choose-rootPartitionType", + // 指定数据盘文件系统,当前合法值:xfs,ext4 + DataPartitionType: "your-choose-dataPartitionType", +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +// 设置是否保留数据 +isPreserveData = false +if err := bbcClient.RebuildInstance(instanceId, isPreserveData, rebuildArgs); err != nil { + fmt.Println("rebuild instance failed: ", err) +} else { + fmt.Println("rebuild instance success.") +} +``` +> **注意:** +>IsPreserveData表示是否保留数据: +>- 当IsPreserveData设置为 false 时,RaidId 和 SysRootSize 是必填参数 +>- 当IsPreserveData设置为 true 时,RaidId、SysRootSize 和 DataPartitionType 参数不生效 + +### 批量重装实例 +使用以下代码可以使用镜像批量重建指定BBC实例: +```go +rebuildArgs := &BatchRebuildInstanceArgs{ + // 设置重装BBC的实例ID + InstanceIds: []string{"your-choose-instance-id"}, + // 设置使用的镜像id + ImageId: "your-choose-image-id", + // 设置管理员密码 + AdminPass: "your-new-admin-pass", + // 是否保留数据。当该值为true时,raidId和sysRootSize字段不生效 + IsPreserveData: false, + // 此参数在isPreserveData为false时为必填,在isPreserveData为true时不生效 + RaidId: "your_raid_id", + // 系统盘根分区大小,默认为20G,取值范围为20-100。此参数在isPreserveData为true时不生效 + SysRootSize: 20, + // 指定系统盘文件系统,当前合法值:xfs,ext4 + RootPartitionType: "your-choose-rootPartitionType", + // 指定数据盘文件系统,当前合法值:xfs,ext4 + DataPartitionType: "your-choose-dataPartitionType", +} +if res, err := bbcClient.BatchRebuildInstance(rebuildArgs); err != nil { + fmt.Println("batch rebuild instance failed: ", err) +} else { + fmt.Println("batch rebuild instance success, result: %s", res) +} +``` +> **注意:** +>IsPreserveData表示是否保留数据: +>- 当IsPreserveData设置为 false 时,RaidId 和 SysRootSize 是必填参数 +>- 当IsPreserveData设置为 true 时,RaidId、SysRootSize 和 DataPartitionType 参数不生效 + +### 实例续费 + +对BBC实例的续费操作,可以延长过期时长,或者从回收站恢复预付费BBC实例,以下代码可以对实例进行续费 +```go +args := &PurchaseReservedArgs { + Billing: Billing{ + PaymentTiming: PaymentTimingPrePaid, + Reservation: Reservation{ + Length: 1, + TimeUnit: "Month", + }, + }, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bbcClient.InstancePurchaseReserved(instnaceId, args); err != nil { + fmt.Println("Renew Instance failed: ", err) +} else { + fmt.Println("Renew Instance success.") +} +``` + +> **提示:** +> - 续费时若实例已欠费停机,续费成功后有个BBC实例启动的过程。 +> - 该接口是一个异步接口。 + +### 释放实例 +对于后付费Postpaid以及预付费Prepaid过期的BBC实例,可以使用以下代码将其释放: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bbcClient.DeleteInstance(instanceId); err != nil { + fmt.Println("release instance failed: ", err) +} else { + fmt.Println("release instance success.") +} +``` + +### 释放实例(包含预付费实例) +不区分后付费还是预付费实例,释放bbc以及关联的eip,可以使用以下代码将其释放: +```go + args := &DeleteInstanceIngorePaymentArgs{ + InstanceId: "instanceid", + RelatedReleaseFlag: relatedReleaseFlag, //true or false + //设置是否立即释放,默认false,实例进入回收站,关联eip资源解绑;为true时,实例和设置了关联释放的eip资源,一起立即释放 + DeleteImmediate: false, + } + if res, err := BBC_CLIENT.DeleteInstanceIngorePayment(args); err != nil { + fmt.Println("delete instance failed: ", err) + } else { + fmt.Printf("delelte instance success, result: %s", res) + } +``` + +### 批量释放或进入回收站实例(不包含预付费实例) +释放或者进入回收站bbc实例,可以使用以下代码将其释放: +```go + instanceIds := []string{"instanceId"} + queryArgs := &DeleteInstanceArgs{ + BbcRecycleFlag: bbcRecycleFlag, // true or false, true recycled the bbc + InstanceIds: instanceIds, + } + if err := BBC_CLIENT.DeleteInstances(queryArgs); err != nil { + fmt.Println("delete instances failed: ", err) + } else { + fmt.Println("delete instances success") + } +``` + +### 查询回收站实例列表 +使用以下代码查询所有BBC回收站实例的列表及详情信息 +```go + queryArgs := &ListRecycledInstancesArgs{ + Marker: "your marker", + PaymentTiming: "your paymentTiming", + RecycleBegin: "RecycleBegin", // recycled begin time ,eg: 2020-11-23T17:18:24Z + RecycleEnd: "RecycleEnd", + MaxKeys: 10, + InstanceId: "InstanceId", + Name: "InstanceName", + } + if res, err := BBC_CLIENT.ListRecycledInstances(queryArgs); err != nil { + fmt.Println("list recycled bbc failed: ", err) + } else { + fmt.Println("list recycled bbc success, result: ", res) + } +``` + +### 释放回收站实例 +回收站实例7天后自动释放,清理回收站资源,可以使用以下代码将其释放: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bbcClient.DeleteRecycledInstance(instanceId); err != nil { + fmt.Println("release instance failed: ", err) +} else { + fmt.Println("release instance success.") +} +``` + +### 后付费回收站bbc实例恢复计费 +使用以下代码可以恢复后付费回收站bbc实例,再次使用。 备注: 预付费回收站实例使用预付费续费接口即可 +```go + instanceIds := []string{"instanceId"} + queryArgs := &RecoveryInstancesArgs{ + InstanceIds: instanceIds, + } + if err := BBC_CLIENT.RecoveryInstances(queryArgs); err != nil { + fmt.Println("recovery instance failed: ", err) + } else { + fmt.Println("recovery instance success") + } +``` + +### 修改实例密码 +使用以下代码可以修改指定BBC实例的管理员密码: +```go +modifyInstancePasswordArgs := &ModifyInstancePasswordArgs{ + AdminPass: "your_new_password", +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bbcClient.ModifyInstancePassword(instanceId, modifyInstancePasswordArgs); err != nil { + fmt.Println("modify instance password failed: ", err) +} else { + fmt.Println("modify instance password success.") +} +``` + +### 查询实例VNC地址 + +如下代码可以查询实例的VNC地址 +```go +result, err := client.GetInstanceVNC(instanceId) +if err != nil { + fmt.Println("get instance VNC url failed:", err) +} else { + fmt.Println("get instance VNC url success: ", result) +} +``` + +> **提示:** +> - VNC地址一次使用后即失效 +> - URL地址有效期为10分钟 + +> **注意:** +>BBC 实例密码要求: +>- 8-16位字符,英文,数字和符号必须同时存在,符号仅限!@#$%^*() + +### 查询实例VPC/Subnet信息 +使用以下代码可以通过BBC实例id查询VPC/Subnet信息: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +getVpcSubnetArgs := &GetVpcSubnetArgs{ + BbcIds: []string{instanceId}, +} +if res, err := bbcClient.GetVpcSubnet(getVpcSubnetArgs); err != nil { + fmt.Println("get vpc subnet failed: ", err) +} else { + fmt.Println("get vpc subnet success. res: ", res) +} +``` + +## 智能卡实例绑定安全组 + +使用以下代码可以将智能卡实例绑定安全组: + +```go +args := &BindSecurityGroupsArgs{ + InstanceIds: ["instanceId"], + SecurityGroups: ["SecurityGroup"], +} +if err := bbcClient.BindSecurityGroups(args); err != nil { + fmt.Println("BindSecurityGroups failed: ", err) +} else { + fmt.Println("BindSecurityGroups success.") +} +``` +## 智能卡实例解绑安全组 + +使用以下代码可以将智能卡实例解绑安全组: + +```go +args := &UnBindSecurityGroupsArgs{ + InstanceId: "", + SecurityGroupId: "", +} +if err := bbcClient.UnBindSecurityGroups(args); err != nil { + fmt.Println("UnBindSecurityGroups failed: ", err) +} else { + fmt.Println("UnBindSecurityGroups success.") +} +``` + +## 批量增加辅助IP +使用以下代码对实例增加辅助IP: + +```go +batchAddIpArgs := &BatchAddIpArgs{ + // 实例ID + InstanceId string "instanceId" + // 辅助IP,和SecondaryPrivateIpAddressCount不可同时使用 + PrivateIps []string "privateIps" + // 自动分配IP数量,和PrivateIps不可同时使用 + SecondaryPrivateIpAddressCount int 1 + // 启用后主网卡新增ip地址为ipv6,请确认子网已分配IPv6网段,默认false + AllocateMultiIpv6Addr false + // 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 + ClietnToken string "clientToken" +} + +if res, err := bbcClient.BatchAddIP(batchAddIpArgs); err != nil { + fmt.Println("BatchAddIP failed: ", err) +} else { + fmt.Println("BatchAddIP success, result: ", res) +} +``` + +### 批量删除指定实例的ip +```go +privateIps := []string{"192.168.1.25"} +instanceId := "your-choose-instance-id" +// 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 +clientToken := "clientToken" +batchDelIpArgs := &BatchDelIpArgs{ + InstanceId: instanceId, + PrivateIps: privateIps, + ClientToken: clientToken, +} +if err := bbcClient.BatchDelIP(batchDelIpArgs); err != nil { + fmt.Println("delete ips failed: ", err) +} else { + fmt.Println("delete ips success.") +} +``` + +### 开通自动续费(包含关联产品) +自动续费仅限预付费产品 + +```go +bbcCreateAutoRenewArgs := &BbcCreateAutoRenewArgs{ + // 实例ID + InstanceId: instanceId, + // 续费单位,month,year + RenewTimeUnit: "month", + // 续费时长,单位:month,支持1, 2, 3, 4, 5, 6, 7, 8, 9;单位:year,支持1, 2, 3 + RenewTime: 1, +} + +if err := bbcClient.BatchCreateAutoRenewRules(bbcCreateAutoRenewArgs); err != nil { + fmt.Println("BatchCreateAutoRenewRules failed: ", err) +} else { + fmt.Println("BatchCreateAutoRenewRules success.") +} +``` + +### 关闭自动续费(包含关联产品) +自动续费仅限预付费产品 + +```go +bbcDeleteAutoRenewArgs := &BbcDeleteAutoRenewArgs{ + // 实例ID + InstanceId: instanceId, +} + +if err := bbcClient.BatchDeleteAutoRenewRules(bbcCreateAutoRenewArgs); err != nil { + fmt.Println("BatchDeleteAutoRenewRules failed: ", err) +} else { + fmt.Println("BatchDeleteAutoRenewRules success.") +} +``` + +### 查询实例绑定的弹性网卡列表 +使用以下代码可以查询实例绑定的弹性网卡列表 +```GO +// 设置你要操作的instanceId +instanceId := "" +if res, err := bbcClient.GetInstanceEni(instanceId); err != nil { + fmt.Println("Get specific instance eni failed: ", err) +} else { + fmt.Println("Get specific instance eni success, result: ", res) +} +``` + +## 标签 +### 实例解绑标签 +通过以下代码解绑实例已有的标签 +```go +unbindTagsArgs := &UnbindTagsArgs{ + // 设置您要解绑的标签 + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := BBC_CLIENT.UnbindTags(instanceId, unbindTagsArgs); err != nil { + fmt.Println("unbind instance tags failed: ", err) +} else { + fmt.Println("unbind instance tags success.") +} +``` + +## 套餐 +### 查询套餐列表 +使用以下代码查询所有BBC套餐的列表及详情信息 +```go +if res, err := bbcClient.ListFlavors(); err != nil { + fmt.Println("List flavors failed: ", err) +} else { + fmt.Println("List flavors success, result: ", res) +} +``` + +### 查询套餐详情 +使用以下代码可以查询指定套餐的详细信息 + +```go +// 设置你要操作的flavorId +flavorId := "your-choose-flavor-id" +if res, err := bbcClient.GetFlavorDetail(testFlavorId); err != nil { + fmt.Println("Get flavor failed: ", err) +} else { + fmt.Println("Get flavor success, result: ", res) +} +``` +### 查询RAID详情 +使用以下代码可以查询指定套餐的RAID方式及磁盘大小 + +```go +// 设置你要操作的flavorId +flavorId := "your-choose-flavor-id" +if res, err := bbcClient.GetFlavorRaid(testFlavorId); err != nil { + fmt.Println("Get raid failed: ", err) +} else { + fmt.Println("Get raid success, result: ", res) +} +``` + +### 查询套餐支持的可用区 +使用以下代码可以查询指定套餐支持的可用区列表 + +```go +// 设置你要操作的flavorId +flavorId := "" +queryArgs := &ListFlavorZonesArgs{ + FlavorId: flavorId, +} +if res, err := bbcClient.ListFlavorZones(queryArgs); err != nil { + fmt.Println("Get flavor zoneName failed: ", err) +} else { + fmt.Println("Get flavor zoneName success, result: ", res) +} +``` + +### 查询可用区支持的套餐 +使用以下代码可以查询指定可用区支持的套餐列表 + +```go +// 设置你要操作的zoneName,可以使用cn-bj-a 等 +zoneName := "" +queryArgs := &ListZoneFlavorsArgs{ + ZoneName: zoneName, +} +if res, err := bbcClient.ListZoneFlavors(queryArgs); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) +} else { + fmt.Println("Get the specific zone flavor success, result: ", res) +} + +``` + +## 镜像 +### 通过实例创建自定义镜像 +- 用于创建自定义镜像,默认每个账号配额20个,创建后的镜像可用于创建实例 +- 只有 Running 或 Stopped 状态的实例才可以执行成功 +使用以下代码可以从指定的实例创建镜像 +```go +// 用于创建镜像的实例ID +instanceId := "i-3EavdPl8" +// 设置创建镜像的名称 +imageName := "testCreateImage" +queryArgs := &CreateImageArgs{ + ImageName: testImageName, + InstanceId: testInstanceId, +} +if res, err := bbcClient.CreateImageFromInstanceId(queryArgs); err != nil { + fmt.Println("Create image failed: ", err) +} else { + fmt.Println("Create image success, result: ", res) +} +``` +### 查询镜像列表 +- 用于查询用户所有的镜像信息 +- 查询的镜像信息中包括系统镜像、自定义镜像和服务集成镜像 +- 支持按 imageType 来过滤查询,此参数非必需,未设置时默认为 All,即查询所有类型的镜像 +使用以下代码可以查询镜像列表 +```go +// 指定要查询何种类型的镜像 +// All(所有) +// System(系统镜像/公共镜像) +// Custom(自定义镜像) +// Integration(服务集成镜像) +// Sharing(共享镜像) +imageType := "All" +// 批量获取列表的查询的起始位置 +marker := "your-marker" +// 每页包含的最大数量 +maxKeys := 100 +queryArgs := &ListImageArgs{ + Marker: marker, + MaxKeys: maxKeys, + ImageType: imageType, +} +if res, err := bbcClient.ListImage(queryArgs); err != nil { + fmt.Println("List image failed: ", err) +} else { + fmt.Println("List image success, result: ", res) +} +``` +### 查询镜像详情 +- 用于根据指定镜像ID查询单个镜像的详细信息 +使用以下代码可以查询镜像详情 +```go +// 待查询镜像ID +image_id :="your-choose-image-id" +if res, err := bbcClient.GetImageDetail(testImageId); err != nil { + fmt.Println("Get image failed: ", err) +} else { + fmt.Println("Get image success, result: ", res.Result) +} +``` +### 删除自定义镜像 +- 用于删除用户自己的指定的自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能删除 +- 镜像删除后无法恢复,不能再用于创建、重置实例 +使用以下代码可以删除指定镜像 + +```go +// 待删除镜像ID +imageId := "your-choose-image-id" +if err := bbcClient.DeleteImage(testImageId); err != nil { + fmt.Println("Delete image failed: ", err) +} +``` + +### 获取套餐的公共镜像 +- 如果不传套餐id,获取所有套餐的镜像列表 +使用以下代码可以获取指定套餐可选的公共镜像列表 + +```go +// 物理机套餐Id列表 +flavorIds := []string{""} +queryArgs := &GetFlavorImageArgs{ + FlavorIds: flavorIds, +} +if res, err := bbcClient.GetCommonImage(queryArgs); err != nil { + fmt.Println("Get specific flavor common image failed: ", err) +} else { + fmt.Println("Get specific flavor common image success, result: ", res) +} +``` + +### 获取套餐的自定义镜像 +- 如果不传套餐id,获取所有套餐的镜像列表 +使用以下代码可以获取指定套餐可选的自定义镜像列表 + +```go +// 物理机套餐Id列表 +flavorIds := []string{"BBC-S3-02"} +queryArgs := &GetFlavorImageArgs{ + FlavorIds: flavorIds, +} +if res, err := bbcClient.GetCustomImage(queryArgs); err != nil { + fmt.Println("Get specific flavor common image failed: ", err) +} else { + fmt.Println("Get specific flavor common image success, result: ", res) +} +``` + +### 共享自定义镜像 + +- 该接口用于共享用户自己的指定的自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能共享。 +- imageId 所指定的镜像不存在,提示404错误。 +- 镜像共享后,被共享的用户可以使用此镜像创建、重置实例。 +- 请求参数中的account和accountId均为可选参数,但不能全部为空,当两个参数同时出现时,服务端会自动去重。 + +```go +// 待共享的用户id +accountId := "your-accountId" +//待共享的用户名 +account := "your-account" +// 待共享的镜像ID +imageId := "your-imageId" + +args := &api.SharedUser{ + AccountId: accountId, + Account: account, +} +if err := bbcClient.ShareImage(imageId,args); err != nil { + fmt.Println("ShareImage failed: ", err) +} else { + fmt.Println("ShareImage success") +} +``` + +### 取消共享自定义镜像 + +- 该接口用于取消共享用户自己的指定的自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能共享。 +- imageId 所指定的镜像不存在,提示404错误。 +- 镜像取消共享后,被取消共享的用户不能再使用此镜像创建、重置实例。 +- 请求参数中的account和accountId均为可选参数,但不能全部为空,当两个参数同时出现时,服务端会自动去重。 + +```go +// 待共享的用户id +accountId := "your-accountId" +//待共享的用户名 +account := "your-account" +// 待共享的镜像ID +imageId := "your-imageId" + +args := &api.SharedUser{ + AccountId: accountId, + Account: account, +} +if err := bbcClient.UnShareImage(imageId,args); err != nil { + fmt.Println("UnShareImage failed: ", err) +} else { + fmt.Println("UnShareImage success") +} +``` + +### 跨区域复制自定义镜像 +- 用于用户跨区域复制自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能复制 +- regions如北京"bj",广州"gz",苏州"su",可多选: +```go + args := RemoteCopyImageArgs{ + Name: "test2", + DestRegion: []string{"gz"}, + } + err := bbcClient.RemoteCopyImage(imageId, args) + if err != nil { + fmt.Println("remote copy image failed:", err) + } else { + fmt.Println("remote copy image success") + } +``` + +### 跨区域复制自定义镜像并返回目的region的镜像镜像id +- 用于用户跨区域复制自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能复制 +- regions如北京"bj",广州"gz",苏州"su",可多选: +```go +args := &api.RemoteCopyImageArgs{ + Name: "test2", + DestRegion: []string{"gz"}, + } +result, err := bbcClient.RemoteCopyImageReturnImageIds(imageId, args) + if err != nil { + fmt.Println("remote copy image failed:", err) + } else { + fmt.Println("remote copy image success") + } +``` + +### 取消跨区域复制自定义镜像 + +用于取消跨区域复制自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能复制: + +```go +err := bbcClient.CancelRemoteCopyImage(imageId) +if err != nil { + fmt.Println("cancel remote copy image failed:", err) +} else { + fmt.Println("cancel remote copy image success") +} +``` + +### 查询自定义镜像已共享的用户 + +- 该接口用于查询自定义镜像已共享的用户列表 +- imageId 待查询的自定义镜像Id + +```go +// 待查询的自定义镜像ID +imageId := "your-imageId" + +if users, err := bbcClient.GetImageSharedUser(imageId); err != nil { + fmt.Println("GetImageSharedUser failed: ", err) +} else { + fmt.Println("GetImageSharedUser success: ", users) +} +``` + +## 操作日志 +### 查询操作日志 +通过以下代码查询指定操作日志 + +```go +// 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +marker := "your-marker" +// 每页包含的最大数量,最大数量通常不超过1000。缺省值为100 +maxKeys := 100 +// 需查询物理机操作的起始时间(UTC时间),格式 yyyy-MM-dd'T'HH:mm:ss'Z' ,为空则查询当日操作日志 +startTime := "" +// 需查询物理机操作的终止时间(UTC时间),格式 yyyy-MM-dd'T'HH:mm:ss'Z' ,为空则查询当日操作日志 +endTime := "" +queryArgs := &GetOperationLogArgs{ + Marker: marker, + MaxKeys: maxKeys, + StartTime: startTime, + EndTime: endTime, +} +if res, err := bbcClient.ListImage(queryArgs); err != nil { + fmt.Println("Get Operation Log failed: ", err) +} else { + fmt.Println("Get Operation Log success, result: ", res) +} +``` + +## 部署集 +### 创建部署集 +通过以下代码根据指定的部署集策略和并发度创建部署集 +```go +// 设置创建部署集的名称 +deploySetName := "your-deploy-set-name" +// 设置创建的部署集的描述信息 +deployDesc := "your-deploy-set-desc" +// 设置部署集并发度,范围 [1,5] +concurrency := 1 +// 设置创建部署集的策略,BBC实例策略只支持:"tor_ha" +strategy := "tor_ha" +queryArgs := &CreateDeploySetArgs{ + Strategy: strategy, + Concurrency: concurrency, + Name: deploySetName, + Desc: deployDesc, +} +if res, err := bbcClient.CreateDeploySet(queryArgs); err != nil { + fmt.Println("Create deploy set failed: ", err) +} else { + fmt.Println("Create deploy set success, result: ", res) +} +``` + +### 查询部署集列表 +使用以下代码查询所有部署集实例的列表及详情信息 + +```go +if res, err := bbcClient.ListDeploySets(); err != nil { + fmt.Println("List deploy sets failed: ", err) +} else { + fmt.Println("List deploy sets success, result: ", res) +} +``` + +### 查询部署集列表 +使用以下代码分页过滤查询所有部署集实例的列表及详情页面 + +```go +queryArgs := &ListDeploySetsArgs{ + // 批量获取列表的查询起始位置,是一个由系统产生的字符串 + Marker: "your-marker", + // 设置返回数据大小,缺省为1000 + MaxKeys: 100, + // 通过internal Ip过滤维修任务列表 + Strategy: "your-choose-strategy", +} +if res, err := bbcClient.ListDeploySetsPage(queryArgs); err != nil { + fmt.Println("List deploy sets failed: ", err) +} else { + fmt.Println("List deploy sets success, result: ", res) +} +``` + +### 查询部署集详情 +使用以下代码可以查询指定套餐的详细信息 + +```go +// 设置你要查询的deploySetID +deploySetID := "your-choose-deploy-set-id" +if res, err := bbcClient.GetDeploySet(deploySetID); err != nil { + fmt.Println("Get deploy set failed: ", err) +} else { + fmt.Println("Get deploy set success, result: ", res) +} +``` +### 删除指定的部署集 +使用以下代码删除用户自己的指定的部署集 + +```go +// 设置你要删除的deploySetID +deploySetID := "your-choose-deploy-set-id" +if err := bbcClient.DeleteDeploySet(deploySetID); err != nil { + fmt.Println("Delete deploy set failed: ", err) +} +``` + +##标签 +### 实例绑定标签 +通过以下代码绑定实例想要绑定的标签 +```go +bindTagsArgs := &BindTagsArgs{ + // 设置您要绑定的标签 + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := BBC_CLIENT.BindTags(instanceId, bindTagsArgs); err != nil { + fmt.Println("bind instance tags failed: ", err) +} else { + fmt.Println("bind instance tags success.") +} +``` +### 实例解绑标签 +通过以下代码解绑实例已有的标签 +```go +unbindTagsArgs := &UnbindTagsArgs{ + // 设置您要解绑的标签 + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := BBC_CLIENT.UnbindTags(instanceId, unbindTagsArgs); err != nil { + fmt.Println("unbind instance tags failed: ", err) +} else { + fmt.Println("unbind instance tags success.") +} +``` +## 查询物理机套餐库存 +查询物理机套餐库存 +```go +// 套餐id +flavorId := "flavorId" +// 可用区名称 +zoneName := "zoneName" + +args := &api.CreateInstanceStockArgs{ + FlavorId: flavorId, + ZoneName: zoneName, +} +if res, err := bbcClient.GetInstanceCreateStock(args); err != nil { + fmt.Println("GetInstanceCreateStock failed: ", err) +} else { + fmt.Println("GetInstanceCreateStock success: ", res) +} +``` + + +## 查询物理机套餐价格 +套餐询价接口 +```go +// 套餐id +flavorId := "flavorId" +// 购买数量 +purchaseCount := "purchaseCount" +//价格相关参数 +billing: = Billing{ + PaymentTiming: "Prepaid", + Reservation: Reservation{ + Length: 4, + }, + }, + +args := &api.InstancePirceArgs{ + FlavorId: flavorId, + PurchaseCount: purchaseCount, + Billing: billing, +} +if res, err := bbcClient.GetInstancePirce(args); err != nil { + fmt.Println("GetInstancePirce failed: ", err) +} else { + fmt.Println("GetInstancePirce success: ", res) +} +``` + + +## 物理机额外套餐查询 +物理机套餐参数查询接口 +```go +// 物理机id +instanceIds := []string{"your-instanceId"} + +args := &api.SimpleFlavorArgs{ + InstanceIds: instanceIds, +} +if res, err := bbcClient.GetSimpleFlavor(args); err != nil { + fmt.Println("GetSimpleFlavor failed: ", err) +} else { + fmt.Println("GetSimpleFlavor success: ", res) +} +``` + + +### 查询BBC维修任务列表 +使用以下代码查询所有未关闭的故障bbc维修任务的列表及详情信息: +```go +listArgs := &ListRepairTaskArgs{ + // 批量获取列表的查询起始位置,是一个由系统产生的字符串 + Marker: "your-marker", + // 设置返回数据大小,缺省为1000 + MaxKeys: 100, + // 通过internal Ip过滤维修任务列表 + InstanceId: "your-choose-instance-id", + // 通过故障名称过滤维修任务列表 + ErrResult: "your-choose-errResult", +} +if res, err := bbcClient.ListRepairTasks(listArgs); err != nil { + fmt.Println("list tasks failed: ", err) +} else { + fmt.Println("list tasks success, result: ", res) +} +``` + +### 查询关闭的维修任务列表 +使用以下代码查询关闭的任务列表 +```go +args := &bbc.ListClosedRepairTaskArgs { + // 返回数据大小 + MaxKeys: 100, + } +if res, err := bbcClient.ListClosedRepairTasks(args); err != nil{ + fmt.Println("Get the closed repaired tasks failed: ", err) +} else { + fmt.Println("Get the closed repaired tasks success: ", res) +} +``` + +### 查询维修任务详情 +使用以下代码可以查询指定BBC维修任务的详细信息: +```go +// 设置你要查询的taskId +taskId := "your-choose-task-id" +if res, err := bbcClient.GetRepairTaskDetail(taskId); err != nil { + fmt.Println("get task detail failed: ", err) +} else { + fmt.Println("get task detail success, result: ", res) +} +``` + + +### 维修任务授权维修 +使用以下代码可以授权指定BBC维修任务,实例状态必须为 unauthorized 或 ignored,调用此接口才可以成功返回,否则提示409错误: +```go +taskIdArgs := &TaskIdArgs{ + // 设置你要操作的taskId + taskId : "your-choose-task-id", +} +if err := bbcClient.AuthorizeRepairTask(taskIdArgs); err != nil { + fmt.Println("authorize task failed: ", err) +} else { + fmt.Println("authorize task success.") +} +``` + +### 维修任务授权维修 +使用以下代码可以授权指定BBC维修任务,实例状态必须为 unauthorized 或 ignored,调用此接口才可以成功返回,否则提示409错误: +```go +taskIdArgs := &TaskIdArgs{ + // 设置你要操作的taskId + taskId : "your-choose-task-id", +} +if err := bbcClient.AuthorizeRepairTask(taskIdArgs); err != nil { + fmt.Println("authorize task failed: ", err) +} else { + fmt.Println("authorize task success.") +} +``` + + +### 维修任务暂不授权维修 +使用以下代码可以暂不授权指定BBC维修任务,实例状态必须为 unauthorized,调用此接口才可以成功返回,否则提示409错误: +```go +taskIdArgs := &TaskIdArgs{ + // 设置你要操作的taskId + taskId :"your-choose-task-id", +} +if err := bbcClient.UnAuthorizeRepairTask(taskIdArgs); err != nil { + fmt.Println("unauthorize task failed: ", err) +} else { + fmt.Println("unauthorize task success.") +} +``` + + +### 维修任务确认恢复 +使用以下代码可以确认指定BBC维修任务已恢复,实例状态必须为 processing,调用此接口才可以成功返回,否则提示409错误: +```go +taskIdArgs := &TaskIdArgs{ + // 设置你要操作的taskId + taskId :"your-choose-task-id", +} +if err := bbcClient.ConfirmRepairTask(taskIdArgs); err != nil { + fmt.Println("confirm task failed: ", err) +} else { + fmt.Println("confirm task success.") +} +``` + + +### 维修任务确认未恢复 +使用以下代码可以确认指定BBC维修任务未恢复,实例状态必须为 processing,调用此接口才可以成功返回,否则提示409错误: +```go +taskIdArgs := &TaskIdArgs{ + // 设置你要操作的taskId + taskId :"your-choose-task-id", + // 设置你要报修的新故障 + newErrResult :"your-new-errResult", +} +if err := bbcClient.DisconfirmTaskArgs(taskIdArgs); err != nil { + fmt.Println("disconfirm task failed: ", err) +} else { + fmt.Println("disconfirm task success.") +} +``` + + +### 维修任务操作详情 +使用以下代码可以查看指定BBC维修任务操作详情: +```go +taskIdArgs := &TaskIdArgs{ + // 设置你要操作的taskId + taskId :"your-choose-task-id", +} +if err := bbcClient.GetRepairTaskRecord(taskIdArgs); err != nil { + fmt.Println("get task record failed: ", err) +} else { + fmt.Println("get task record success.") +} +``` + +### 查询BBC已完成的维修任务列表 +使用以下代码查询所有已关闭的故障bbc维修任务的列表及详情信息: +```go +listArgs := &ListRepairTaskArgs{ + // 批量获取列表的查询起始位置,是一个由系统产生的字符串 + Marker: "your-marker", + // 设置返回数据大小,缺省为1000 + MaxKeys: 100, + // 通过internal Ip过滤维修任务列表 + InstanceId: "your-choose-instance-id", + // 通过故障名称过滤维修任务列表 + ErrResult: "your-choose-errResult", + // 通过任务id过滤维修任务列表 + TaskId: "your-choose-task-id", +} +if res, err := bbcClient.ListRepairTasks(listArgs); err != nil { + fmt.Println("list tasks failed: ", err) +} else { + fmt.Println("list tasks success, result: ", res) +} +``` + +### 获取维修平台预授权规则列表 +通过以下代码获取维修平台预授权规则列表 +```go +args := &ListRuleArgs{ + // 批量获取列表的查询起始位置,是一个由系统产生的字符串 + Marker: "your-marker", + // 设置返回数据大小,缺省为1000 + MaxKeys: 100, + // 通过rule name筛选规则列表 + RuleName: "your-choose-rule-name", + // 通过rule id筛选规则列表 + RuleId: "your-choose-rule-id", +} +if res, err := bbcClient.ListRule(args); err != nil { + fmt.Println("list rules failed: ", err) +} else { + fmt.Println("list rules success, result: ", res) +} +``` + +### 获取维修平台预授权规则详情 +通过以下代码获取维修平台预授权规则详情 +```go +// 设置查询rule id +ruleId := "your-choose-rule-id" +if res, err := bbcClient.GetRuleDetail(ruleId); err != nil { + fmt.Println("get rule failed: ", err) +} else { + fmt.Println("get rule success, result: ", res) +} +``` + +### 创建维修平台预授权规则 +通过以下代码创建维修平台预授权规则 +```go +args := &CreateRuleArgs{ + // 设置规则名称 + RuleName: "your-choose-rule-name", + // 设置授权上线 + Limit: 2, + // 规则是否启用,1表示启用,0表示禁用 + Enabled: 1, + // 设置规则关联标签,tagKey:tagValue + TagStr: "tagKey:tagValue", + // 设置备注 + Extra: "extra", +} +if res, err := bbcClient.CreateRule(args); err != nil { + fmt.Println("create rule failed: ", err) +} else { + fmt.Println("create rule success, result: ", res) +} +``` + +### 删除维修平台预授权规则 +- 规则Enabled时不能删除 + +通过以下代码删除维修平台预授权规则 +```go +args := &DeleteRuleArgs{ + // 设置要删除的rule id + RuleId: "your-choose-rule-id", +} +if err := bbcClient.DeleteRule(args); err != nil { + fmt.Println("delete rule failed: ", err) +} else { + fmt.Println("delete rule success") +} +``` + +### 禁用维修平台预授权规则 +通过以下代码禁用维修平台预授权规则 +```go +args := &DisableRuleArgs{ + // 设置要禁用的rule id + RuleId: "your-choose-rule-id", +} +if err := bbcClient.CreateRule(args); err != nil { + fmt.Println("disable rule failed: ", err) +} else { + fmt.Println("disable rule success") +} +``` + +### 获取bbc本地盘信息列表 +通过以下代码可以分页获取bbc本地盘信息列表 +```go +queryArgs := &ListCDSVolumeArgs{ + MaxKeys: 100, + InstanceId: "InstanceId", + Marker: "VolumeId", + ZoneName: "zoneName", +} +if res, err := BBC_CLIENT.ListCDSVolume(queryArgs); err != nil { + fmt.Println("list volume failed: ", err) +} else { + fmt.Println("list volume success, result: ", res) +} +``` + +### 启用维修平台预授权规则 +通过以下代码启用维修平台预授权规则 +```go +args := &EnableRuleArgs{ + // 设置要启用的rule id + RuleId: "your-choose-rule-id", +} +if err := bbcClient.EnableRule(args); err != nil { + fmt.Println("enable rule failed: ", err) +} else { + fmt.Println("enable rule success") +} +``` + +### 获取基于部署集粒度的bbc资源余量 +通过以下代码可以分页获取基于部署集粒度的bbc资源余量。由于bbc现只支持单部署集创建,要求部署集参数传一个。 +```go +queryArgs := &GetBbcStockArgs{ + Flavor: "BBC-S3-02", + DeploySetIds: []string{"dset-0RHZYUfF"}, + } +if res, err := BBC_CLIENT.GetBbcStockWithDeploySet(queryArgs); err != nil { + fmt.Println("get bbc stock failed: ", err) +} else { + fmt.Println("list volume success, result: ", res) +} +``` diff --git a/bce-sdk-go/doc/BCC.md b/bce-sdk-go/doc/BCC.md new file mode 100644 index 0000000..79135a4 --- /dev/null +++ b/bce-sdk-go/doc/BCC.md @@ -0,0 +1,3747 @@ +# BCC服务 + +# 概述 + +本文档主要介绍BCC GO SDK的使用。在使用本文档前,您需要先了解BCC的一些基本知识。若您还不了解BCC,可以参考[产品描述](https://cloud.baidu.com/doc/BCC/s/Jjwvymo32)和[入门指南](https://cloud.baidu.com/doc/BCC/s/ojwvymvfe)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BCC访问域名](https://cloud.baidu.com/doc/BCC/s/0jwvyo603)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云BCC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BCC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BCC Client + +BCC Client是BCC服务的客户端,为开发者与BCC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BCC Client + +通过AK/SK方式访问BCC,用户可以参考如下代码新建一个Bcc Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bcc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + AK, SK := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BCCClient + bccClient, err := bcc.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`AK`对应控制台中的“Access Key ID”,`SK`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BCC/s/ojwvynrqn)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BCC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建BCC Client + +**申请STS token** + +BCC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BCC,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建BCC Client** + +申请好STS后,可将STS Token配置到BCC Client中,从而实现通过STS Token创建BCC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BCC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/bcc" //导入BCC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BCC服务的Client对象,Endpoint使用默认值 + bccClient, err := bcc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create bcc client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + bccClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BCC Client时,无论对应BCC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问BCC + +BCC支持HTTPS传输协议,您可以通过在创建BCC Client对象时指定的Endpoint中指明HTTPS的方式,在BCC GO SDK中使用HTTPS访问BCC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcc" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +bccClient, _ := bcc.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BCC Client + +如果用户需要配置BCC Client的一些细节的参数,可以在创建BCC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BCC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcc" + +//创建BCC Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := bcc.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcc" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := bcc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcc" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := bcc.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BCC时,创建的BCC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BCC Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +BCC实例是一个虚拟的计算环境,包含CPU、内存等最基础的计算组件,是云服务器呈献给每个用户的实际操作实体。BCC实例是云服务器最为核心的概念,支持IP绑定,镜像和快照等功能,诸如CDS磁盘、SCS简单缓存服务只有挂载在BCC实例后才可使用。 + +- 每个用户最多可同时拥有20个BCC实例,若需要更多的配额,请发工单申请。 + +## 实例管理 + +### 创建实例 + +使用以下代码可以创建BCC实例,包括专属实例、普通型Ⅰ 型实例、普通型Ⅱ型实例、存储优化型BCC、计算优化型BCC +```go + +IsOpenHostnameDomain := true +AutoSeqSuffix := true +RelationTag := false +CdsAutoRenew := true +args := &api.CreateInstanceArgsV2{ + // 选择实例创建镜像ID + ImageId: "m-DpgNg8lO", + // 选择付款方式,可以选择预付费或后付费 + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + // 选择实例类型,可以选择N1, N2, N3等 + InstanceType: api.InstanceTypeN1, + // 选择1核CPU + CpuCount: 1, + // 选择1GB内存 + MemoryCapacityInGB: 1, + // 选择40GB磁盘空间 + RootDiskSizeInGb: 40, + // 选择待创建的实例系统盘介质为HP1 + RootDiskStorageType: api.StorageTypeCloudHP1, + // 临时盘数据盘大小 + EphemeralDisks []EphemeralDisk "ephemeralDisks" + // 选择创建100GB大小SSD类型CDS磁盘并挂载到实例上 + CreateCdsList: []api.CreateCdsModel{ + { + StorageType: api.StorageTypeSSD, + CdsSizeInGB: 100, + }, + }, + // 设置管理员密码 + AdminPass: "123qaz!@#", + // 设置实例名称 + Name: "terraform_sdkTest", + // 实例主机名,可选参数,若不选则主机名和实例名称保持一致(实例名称不包含中文名时) + // 仅支持小写字母、数字以及- . 特殊字符,不可连续使用特殊符号,不支持特殊符号开头或结尾,长度2-64 + Hostname: "your-choose-instance-hostname", + // 设置是否自动生成hostname和name有序后缀 是:true 否:false + AutoSeqSuffix: &AutoSeqSuffix, + // 设置是否开启hostname domain 是:true 否:false + IsOpenHostnameDomain: &IsOpenHostnameDomain, + // 设置创建BCC使用的网络带宽大小 + NetWorkCapacityInMbps int networkCapacityInMbps + // 设置需要创建BCC使用的DCC服务器id + DedicateHostId string "dedicatedHostId" + // 设置待查询的竞价实例的购买个数 + PurchaseCount int purchaseCount + // 设置可用区 + ZoneName string "zoneName" + // 指定子网和安全组创建,要求子网和安全组必须同时指定或同时不指定, + // 同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 + // 设置创建BCC使用的子网 + SubnetId string "subnetId" + // 设置创建BCC使用的安全组 + SecurityGroupId string "securityGroupId" + // 设置创建BCC使用的企业安全组,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupId string "enterpriseSecurityGroupId" + // 设置创建BCC使用的安全组列表 + SecurityGroupIds []string securityGroupIds + // 设置创建BCC使用的企业安全组列表,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupIds []string enterpriseSecurityGroupIds + // 设置需要创建GPU卡信息 + GpuCard string "gpuCard" + // 设置需要创建FPGA卡信息 + FpgaCard string "fpgaCard" + // 设置GPU卡或FPGA卡数量 + CardCount string "cardCount" + // 设置按月付费或者按年付费 月是"month",年是"year" + AutoRenewTimeUnit string "autoRenewTimeUnit" + // 设置自动续费的时间 按月是1-9 按年是 1-3 + AutoRenewTime int autoRenewTime + // cds是否自动续费 是:true 否:false + CdsAutoRenew bool &CdsAutoRenew + // 待创建实例指定的标签是否需要和已有标签键进行关联,默认为false。注意值为true时要保证该标签键已存在 + RelationTag bool &RelationTag + // 待创建的标签列表 + Tags []model.TagModel tags + // 指定实例所在的部署集id + DeployId string "deployId" + // 指定实例所在的部署集id 列表 + DeployIdList []string "deployIdList" + // 设置释放保护 默认0不启用,1启用 + DetetionProtection int "deletionProtection" + // 设置要绑定的密钥对ID + KeypairId string "keypairId" + // 设置要绑定的自动快照策略ID + AspId string "aspId" + // 公网带宽计费方式,若不指定internetChargeType,默认付费方式同BCC,预付费默认为包年包月按带宽,后付费默认为按使用带宽计费。(BANDWIDTH_PREPAID:预付费按带宽结算;TRAFFIC_POSTPAID_BY_HOUR:流量按小时后付费;BANDWIDTH_POSTPAID_BY_HOUR:带宽按小时后付费) + InternetChargeType string "internetChargeType" + // 设置内网IP + InternalIps []string internalIps + // 使用 uuid 生成一个长度不超过64位的ASCII字符串 + ClientToken string "random-uuid" + //创建实例支持幂等的token + RequestToken string "requestToken" + // 设置要绑定的资源组id + ResGroupId string "resGroupId" +} + +// 若要生成预付费实例,可以按以下配置生成一个月的预付费实例 +args.Billing = api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + } + } + +// 若要设置自动续费,可以按以下参数设置一年内自动续费 +args.AutoRenewTimeUnit = "year" +args.AutoRenewTime = 1 + +// 若要创建公网EIP,可以设置以下参数 +args.networkCapacityInMbps = 1 + +// 若要一次创建多个相同配置的实例,可以设置以下参数 +args.PurchaseCount = 2 + +result, err := client.CreateInstanceV2(args) +if err != nil { + fmt.Println("create instance failed:", err) +} else { + fmt.Println("create instance success: ", result) +} +``` + +> **提示:** +> 1. 创建BCC请求是一个异步请求,返回200表明订单生成,后续可以通过查询返回的实例id信息了解BCC虚机的创建进度。 +> 2. 本接口用于创建一个或多个同配虚拟机实例。 +> 3. 创建实例需要实名认证,没有通过实名认证的可以前往百度开放云官网控制台中的安全认证下的实名认证中进行认证。 +> 4. 创建计费方式为后付费的实例需要账户现金余额+通用代金券大于100;预付费方式的实例则需要账户现金余额大于等于实例费用。 +> 5. 支持批量创建,且如果创建过程中有一个实例创建失败,所有实例将全部回滚,均创建失败,如果创建时包含CDS,CDS也会回滚。 +> 6. 缺省情形下,一个实例最多只能挂载5个云磁盘。 +> 7. 创建CDS磁盘和临时数据盘时,磁盘容量大小限制为5的倍数。 +> 8. 创建实例支持创建和添加临时数据盘,但不支持单独创建或添加临时数据盘。 +> 9. 临时数据盘不支持挂载、卸载、删除。 +> 10. 普通实例的临时数据盘最大不能超过500G。 +> 11. 指定子网和安全组创建,要求子网和安全组必须同时指定或同时不指定,同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 +> 12. 指定公网IP带宽创建,计费方式为按照带宽计费。 +> 13. 创建接口为异步创建,可通过查询实例详情接口查询实例状态 +> 14. 可通过该接口指定专属服务器创建实例,专属实例不参与计费。专属实例只能通过ephemeralDisks创建临时盘并指定磁盘类型。 +> 15. 每个实例最多只能购买一块临时数据盘。 +> 16. 实例的临时数据盘默认只有hp1类型。 +> 17. 通过instanceType字段指定需要创建的虚机类型,目前API支持创建的虚机类型参见下述InstanceType。参数(instanceType,cpuCount,memoryCapacityInGB)可以确定需要的机型以及配置。 +> 18. 创建存储优化型实例必须购买临时数据盘,通过ephemeralDisks指定临时盘数据盘大小,默认nvme类型数据盘,无需指定。 +> 19. 创建请求详细使用请参考BCC API 文档[创建实例](https://cloud.baidu.com/doc/BCC/s/yjwvyoe0s) +> 20. 创建FPGA BCC虚机需要使用指定的(CPU、内存、本地数据盘、FPGA卡类型以及专用镜像), 详细请参考BCC API 文档[FPGA型BCC可选规格配置](https://cloud.baidu.com/doc/BCC/s/6jwvyo0q2#fpga%E5%9E%8Bbcc%E5%8F%AF%E9%80%89%E8%A7%84%E6%A0%BC%E9%85%8D%E7%BD%AE) +> 21. 创建GPU BCC虚机需要使用指定的(CPU、内存、本地数据盘、GPU卡类型), 详细请参考BCC API 文档[GPU型BCC可选规格配置](https://cloud.baidu.com/doc/BCC/s/6jwvyo0q2#gpu%E5%9E%8Bbcc%E5%8F%AF%E9%80%89%E8%A7%84%E6%A0%BC%E9%85%8D%E7%BD%AE) + +### 创建实例(通过指定实例套餐规格) +使用以下代码可以创建BCC实例,包括普通型BCC、存储优化型BCC、计算优化型BCC、大数据机型BCC、GPU机型BCC、FPGA机型BCC: + +```go + +IsOpenHostnameDomain := true +AutoSeqSuffix := true +RelationTag := false +CdsAutoRenew := true +createInstanceBySpecArgs := &api.CreateInstanceBySpecArgsV2{ + // 选择实例创建镜像ID + ImageId: "m-1PyVLtic", + // 选择创建BCC的套餐规格 + Spec: "bcc.g2.c2m8", + // 选择40GB磁盘空间 + RootDiskSizeInGb: 40, + // 选择待创建的实例系统盘介质为HP1 + RootDiskStorageType: api.StorageTypeCloudHP1, + // 选择创建100GB大小SSD类型CDS磁盘并挂载到实例上 + CreateCdsList: []api.CreateCdsModel{ + { + StorageType: api.StorageTypeSSD, + CdsSizeInGB: 100, + }, + }, + // 选择付款方式,可以选择预付费或后付费 + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + Name: "sdkTest", + // 实例主机名,可选参数,若不选则主机名和实例名称保持一致(实例名称不包含中文名时) + // 仅支持小写字母、数字以及- . 特殊字符,不可连续使用特殊符号,不支持特殊符号开头或结尾,长度2-64 + Hostname: "your-choose-instance-hostname", + // 设置是否自动生成hostname和name有序后缀 是:true 否:false + AutoSeqSuffix: &AutoSeqSuffix, + // 设置是否开启hostname domain 是:true 否:false + IsOpenHostnameDomain: &IsOpenHostnameDomain, + AdminPass: "123qaz!@#", + // 临时盘数据盘大小 + EphemeralDisks []EphemeralDisk "ephemeralDisks" + // 设置创建BCC使用的网络带宽大小 + NetWorkCapacityInMbps int networkCapacityInMbps + // 设置待查询的竞价实例的购买个数 + PurchaseCount int purchaseCount + // 开启部分交付,并设置最小交付虚机个数 + PurchaseMinCount int purchaseMinCount + // 设置可用区 + ZoneName string "zoneName" + // 指定子网和安全组创建,要求子网和安全组必须同时指定或同时不指定, + // 同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 + // 设置创建BCC使用的子网 + SubnetId string "subnetId" + // 设置创建BCC使用的安全组 + SecurityGroupId string "securityGroupId" + // 设置创建BCC使用的企业安全组,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupId string "enterpriseSecurityGroupId" + // 设置创建BCC使用的安全组列表 + SecurityGroupIds []string securityGroupIds + // 设置创建BCC使用的企业安全组列表,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupIds []string enterpriseSecurityGroupIds + // 设置按月付费或者按年付费 月是"month",年是"year" + AutoRenewTimeUnit string "autoRenewTimeUnit" + // 设置自动续费的时间 按月是1-9 按年是 1-3 + AutoRenewTime int autoRenewTime + // cds是否自动续费 是:true 否:false + CdsAutoRenew bool &CdsAutoRenew + // 指定实例所在的部署集id 列表 + DeployIdList []string "deployIdList" + // 设置释放保护 默认0不启用,1启用 + DetetionProtection int "deletionProtection" + // 待创建实例指定的标签是否需要和已有标签键进行关联,默认为false。注意值为true时要保证该标签键已存在 + RelationTag bool &RelationTag + // 待创建的标签列表 + Tags []model.TagModel tags + // 设置要绑定的密钥对ID + KeypairId string "keypairId" + // 设置要绑定的自动快照策略ID + AspId string "aspId" + // 公网带宽计费方式,若不指定internetChargeType,默认付费方式同BCC,预付费默认为包年包月按带宽,后付费默认为按使用带宽计费。(BANDWIDTH_PREPAID:预付费按带宽结算;TRAFFIC_POSTPAID_BY_HOUR:流量按小时后付费;BANDWIDTH_POSTPAID_BY_HOUR:带宽按小时后付费) + InternetChargeType string "internetChargeType" + // 设置内网IP + InternalIps []string internalIps + // 使用 uuid 生成一个长度不超过64位的ASCII字符串 + ClientToken string "random-uuid" + // 创建实例支持幂等的token,成功后永久有效 + RequestToken string "requestToken" + // 设置要绑定的资源组id + ResGroupId string "resGroupId" +} +result, err := client.CreateInstanceBySpecV2(args) +if err != nil { + fmt.Println("create instance failed:", err) +} else { + fmt.Println("create instance success: ", result) +} +``` +> **提示:** +> 1. 创建BCC请求是一个异步请求,返回200表明订单生成,后续可以通过查询返回的实例id信息了解BCC虚机的创建进度。 +> 2. 本接口用于创建一个或多个同配虚拟机实例。 +> 3. 创建实例需要实名认证,没有通过实名认证的可以前往百度开放云官网控制台中的安全认证下的实名认证中进行认证。 +> 4. 创建计费方式为后付费的实例需要账户现金余额+通用代金券大于100;预付费方式的实例则需要账户现金余额大于等于实例费用。 +> 5. 支持批量创建,且如果创建过程中有一个实例创建失败,所有实例将全部回滚,均创建失败,如果创建时包含CDS,CDS也会回滚。 +> 6. 缺省情形下,一个实例最多只能挂载5个云磁盘。 +> 7. 创建CDS磁盘和临时数据盘时,磁盘容量大小限制为5的倍数。 +> 8. 创建实例支持创建和添加临时数据盘,但不支持单独创建或添加临时数据盘。 +> 9. 临时数据盘不支持挂载、卸载、删除。 +> 10. 普通实例的临时数据盘最大不能超过500G。 +> 11. 指定子网和安全组创建,要求子网和安全组必须同时指定或同时不指定,同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 +> 12. 指定公网IP带宽创建,计费方式为按照带宽计费。 +> 13. 创建接口为异步创建,可通过查询实例详情接口查询实例状态 +> 14. 每个实例最多只能购买一块临时数据盘。 +> 15. 实例的临时数据盘默认只有hp1类型。 +> 16. 创建存储优化型实例必须购买临时数据盘,通过ephemeralDisks指定临时盘数据盘大小,默认nvme类型数据盘,无需指定。 + +### 创建实例(V3) +使用以下代码可以创建BCC实例,包括普通型BCC、存储优化型BCC、计算优化型BCC、大数据机型BCC、GPU机型BCC、FPGA机型BCC: + +```go +createInstanceV3Args := &api.CreateInstanceV3Args{ + // 选择创建BCC的套餐规格 + InstanceSpec: "bcc.ic3.c1m1", + // 系统盘类型,大小 + // 选择40GB大小的Cloud_SSD_General类型磁盘作为系统盘 + SystemVolume: api.SystemVolume{ + StorageType: api.StorageTypeV3CloudSSDGeneral, + VolumeSize: 40, + }, + // 本地盘&CDS数据盘 + // 选择创建5GB大小Cloud_Premium类型CDS云磁盘并挂载到实例上 + DataVolumes: []api.DataVolume{ + { + StorageType: api.StorageTypeV3CloudPremium, + VolumeSize: 5, + // 快照ID,当磁盘类型属于CDS云磁盘时,此属性有效 + SnapshotId: "snapshotId", + // 加密密钥,当磁盘类型属于CDS云磁盘时,此属性有效 + EncryptKey: "encryptKey", + }, + }, + // 实例名称 + InstanceName: "sdkTest", + // 实例购买数量 + PurchaseCount: 1, + // 实例主机名,可选参数,若不选则主机名和实例名称保持一致(实例名称不包含中文名时) + // 仅支持小写字母、数字以及- . 特殊字符,不可连续使用特殊符号,不支持特殊符号开头或结尾,长度2-64 + HostName: "hostName", + // 设置是否开启hostname domain 是:true 否:false + AutoSeqSuffix: false, + // 设置是否开启hostname domain 是:true 否:false + HostNameDomain: false, + // 实例管理员密码 + Password: "123qaz!@#", + // 选择付款方式,可以选择预付费:Prepaid,后付费:Postpaid,竞价付费:Spotpaid(选择竞价付费时需配置InstanceMarketOptions参数) + // 选择购买时长1,默认单位:月 + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + }, + }, + // 设置可用区 + ZoneName: "zoneName" + // 指定子网和安全组,要求子网和安全组必须同时指定或同时不指定, + // 同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 + // 设置创建BCC使用的子网 + SubnetId: "subnetId" + // 设置创建BCC使用的安全组 + SecurityGroupIds: []string{ + "securityGroup1", + "securityGroup2", + }, + // 联合购买资源CDS,EIP统一关联标签,默认:false + AssociatedResourceTag: false, + // 待创建的标签列表 + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + }, + // 设置要绑定的密钥对ID + KeypairId: "keypairId", + // 设置自动续费的时间,单位:月 + // 取值范围:1,2,3,4,5,6,7,8,9,12,24,36 + AutoRenewTime: 1, + // CDS数据盘是否自动续费 是:true 否:false + CdsAutoRenew: true, + // 设置要绑定的自动快照策略ID + AutoSnapshotPolicyId: "autoSnapshotPolicyId", + // 部署集 + DeploymentSetId: "deploymentSetId", + // 镜像id + ImageId: "imageId", + // 竞价实例出价模型 + // SpotOption. 市场价: "market" 自定义:"custom" + // SpotPrice. 竞价实例出价金额,若是自定义出价,且出价金额小于市场价,则不允许创建。当spotOption='custom'时才有效。 + InstanceMarketOptions: api.InstanceMarketOptions{ + SpotOption: "custom", + SpotPrice: "spotPrice", + }, + // 待创建实例是否开启ipv6,只有当镜像和子网都支持ipv6时才可开启,true表示开启,false表示关闭,不传表示自动适配镜像和子网的ipv6支持情况 + Ipv6: false, + // 专属服务器ID + DedicatedHostId: "dedicatedHostId", + // 公网带宽 + // InternetMaxBandwidthOut. 设置创建BCC使用的网络带宽大小,单位为Mbps。必须为0~200之间的整数,为0表示不分配公网IP,默认为0Mbps + // InternetChargeType. 公网带宽计费方式,若不指定internetChargeType,默认付费方式同BCC,预付费默认为包年包月按带宽, + // 后付费默认为按使用带宽计费。(BANDWIDTH_PREPAID:预付费按带宽结算;TRAFFIC_POSTPAID_BY_HOUR:流量按小时后付费; + // BANDWIDTH_POSTPAID_BY_HOUR:带宽按小时后付费) + InternetAccessible: api.InternetAccessible{ + InternetMaxBandwidthOut: 5, + InternetChargeType: api.TrafficPostpaidByHour, + }, + // 使用 uuid 生成一个长度不超过64位的ASCII字符串 + ClientToken: "random-uuid", + // 创建实例支持幂等的token,成功后永久有效 + RequestToken: "requestToken", + // 设置要绑定的资源组id + ResGroupId string "resGroupId" +} +result, err := client.CreateInstanceV3(args) +if err != nil { + fmt.Println("create instance failed:", err) +} else { + fmt.Println("create instance success: ", result) +} +``` +> **提示:** +> 1. 创建BCC请求是一个异步请求,返回200表明订单生成,后续可以通过查询返回的实例id信息了解BCC虚机的创建进度。 +> 2. 本接口用于创建一个或多个同配虚拟机实例。 +> 3. 创建实例需要实名认证,没有通过实名认证的可以前往百度开放云官网控制台中的安全认证下的实名认证中进行认证。 +> 4. 创建计费方式为后付费的实例需要账户现金余额+通用代金券大于100;预付费方式的实例则需要账户现金余额大于等于实例费用。 +> 5. 支持批量创建,且如果创建过程中有一个实例创建失败,所有实例将全部回滚,均创建失败,如果创建时包含CDS,CDS也会回滚。 +> 6. 缺省情形下,一个实例最多只能挂载5个云磁盘。 +> 7. 创建CDS磁盘和本地数据盘时,磁盘容量大小限制为5的倍数。 +> 8. 创建实例支持创建和添加本地数据盘,但不支持单独创建或添加临时数据盘。 +> 9. 本地数据盘不支持挂载、卸载、删除。 +> 10. 普通实例的临时数据盘最大不能超过500G。 +> 11. 指定子网和安全组创建,要求子网和安全组必须同时指定或同时不指定,同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 +> 12. 指定公网IP带宽创建,计费方式为按照带宽计费。 +> 13. 创建接口为异步创建,可通过查询实例详情接口查询实例状态 +> 14. 每个实例最多只能购买一块本地数据盘。 +> 15. 创建存储优化型实例必须购买本地数据盘,通过DataVolumes指定本地数据盘大小,需指定属于本地数据盘的磁盘类型。 + +## 创建竞价实例 +使用以下代码可以创建BCC实例: +```go +createInstanceArgs := &CreateInstanceArgs{ + // 输入你要创建instance使用的镜像ID + ImageId: "your-choose-image-id", + // BCC实例类型 + InstanceType: "InstanceType" + // BCC核数 + CpuCount: CpuCount + // BCC的内存大小GB + MemoryCapacityInGB: MemoryCapacityInGB + // 系统盘大小GB + RootDiskSizeInGb int "rootDiskSizeInGb" + // 设置待查询的竞价实例的系统盘介质 + RootDiskStorageType StorageType "rootDiskStorageType" + // 临时盘数据盘大小 + EphemeralDisks []EphemeralDisk "ephemeralDisks" + // 创建需要创建的CDS磁盘列表 + CreateCdsList []CreateCdsModel "createCdsList" + // 设置创建BCC使用的网络带宽大小 + NetWorkCapacityInMbps int networkCapacityInMbps + // 设置需要创建BCC使用的DCC服务器id + DedicateHostId string "dedicatedHostId" + // 设置待查询的竞价实例的购买个数 + PurchaseCount int purchaseCount + // 实例名称 + Name string "name" + // 实例主机名,可选参数,若不选则主机名和实例名称保持一致(实例名称不包含中文名时) + // 仅支持小写字母、数字以及- . 特殊字符,不可连续使用特殊符号,不支持特殊符号开头或结尾,长度2-64 + Hostname: "your-choose-instance-hostname", + // 设置是否自动生成hostname和name有序后缀 是:true 否:false + AutoSeqSuffix: false, + // 设置是否开启hostname domain 是:true 否:false + IsOpenHostnameDomain: false, + // 设置BCC虚机密码 + AdminPass string "adminPass" + // 设置可用区 + ZoneName string "zoneName" + // 指定子网和安全组创建,要求子网和安全组必须同时指定或同时不指定, + // 同时指定的子网和安全组必须同属于一个VPC,都不指定会使用默认子网和默认安全组。 + // 设置创建BCC使用的子网 + SubnetId string "subnetId" + // // 设置创建BCC使用的安全组 + SecurityGroupId string "securityGroupId" + // 设置创建BCC使用的企业安全组,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupId string "enterpriseSecurityGroupId" + // 设置创建BCC使用的安全组列表 + SecurityGroupIds []string securityGroupIds + // 设置创建BCC使用的企业安全组列表,不允许同时设置企业安全组和普通安全组 + EnterpriseSecurityGroupIds []string enterpriseSecurityGroupIds + // 设置需要创建GPU卡信息 + GpuCard string "gpuCard" + // 设置需要创建FPGA卡信息 + FpgaCard string "fpgaCard" + // 设置GPU卡或FPGA卡数量 + CardCount string "cardCount" + // 设置按月付费或者按年付费 月是"month",年是"year" + AutoRenewTimeUnit string "autoRenewTimeUnit" + // 设置自动续费的时间 按月是1-9 按年是 1-3 + AutoRenewTime int autoRenewTime + // cds是否自动续费 是:true 否:false + CdsAutoRenew bool cdsAutoRenew + // 待创建实例指定的标签是否需要和已有标签键进行关联,默认为false。注意值为true时要保证该标签键已存在 + RelationTag bool relationTag + // 待创建的标签列表 + Tags []model.TagModel tags + // 指定实例所在的部署集id + DeployId string "deployId" + // 设置创建BCC虚机使用的竞价模式:market 或者 custom + BidModel string "bidModel" + // 设置创建BCC虚机使用的竞价金额,只有当bidModel为custom时有效 + BidPrice string "bidPrice" + // 设置要绑定的密钥对ID + KeypairId string "keypairId" + // 设置要绑定的自动快照策略ID + AspId string "aspId" + // 公网带宽计费方式,若不指定internetChargeType,默认付费方式同BCC,预付费默认为包年包月按带宽,后付费默认为按使用带宽计费。(BANDWIDTH_PREPAID:预付费按带宽结算;TRAFFIC_POSTPAID_BY_HOUR:流量按小时后付费;BANDWIDTH_POSTPAID_BY_HOUR:带宽按小时后付费) + InternetChargeType string "internetChargeType" + // 设置内网IP + InternalIps []string internalIps + // 设置创建BCC虚机使用的竞价模式:market 或者 custom + BidModel string "bidModel" + // 设置创建BCC虚机使用的竞价金额,只有当bidModel为custom时有效 + BidPrice string "bidPrice" + // 使用 uuid 生成一个长度不超过64位的ASCII字符串 + ClientToken string "random-uuid" + // 创建实例支持幂等的token,成功后永久有效 + RequestToken string "requestToken" + // 设置要绑定的资源组id + ResGroupId string "resGroupId" +} +if res, err := bccClient.CreateBidInstance(createInstanceBySpecArgs); err != nil { + fmt.Println("create instance failed: ", err) +} else { + fmt.Println("create instance success, instanceId: ", res.InstanceIds[0]) +} +``` +## 取消竞价实例订单 +通过以下代码可以取消竞价实例订单 +```go +cancelBidOrderRequest := &CancelBidOrderRequest{ + // 订单ID + OrderId string "orderId" +} +if err := bccClient.CancelBidOrder(cancelBidOrderRequest); err != nil { + fmt.Println("CancelBidOrderRequest failed: ", err) +} else { + fmt.Println("CancelBidOrderRequest success.") +} +``` +## 查询竞价实例套餐 +通过以下代码可以查询竞价实例套餐 +```go +if res, err := bccClient.ListBidFlavor(); err != nil { + fmt.Println("List bidding instance flavors failed: ", err) +} else { + fmt.Println("List bidding instance flavors success, result: ", res) +} +``` +## 查询竞价实例市场价 +通过以下代码可以查询竞价实例市场价 +```go +createCdsList := []api.CreateCdsModel{{ + // 设置CDS磁盘容量,必须为大于0的整数,单位为GB,大小为0~5120G,可选参数 + CdsSizeInGB: 40, + // 设置CDS磁盘存储类别,默认为高性能型,可选参数 + StorageType: api.StorageTypeHP1, + // 设置快照ID + SnapshotId: "your-snapshot-id", + // 设置加密密钥,true或false + EncryptKey: true, +}} +tagList := []model.TagModel{{ + // 设置要查询的tagKey + TagKey: "your-tag-key", + // 设置要查询的tagValue + TagValue: "your-tag-value", +}} +args := &api.GetBidInstancePriceArgs{ + // 使用 uuid 生成一个长度不超过64位的ASCII字符串 + ClientToken: "random-uuid", + // 设置待查询的虚拟机实例类型,具体可选类型参见InstanceType + InstanceType: "your-choose-instance-type", + // 设置待查询虚拟机实例的CPU核数 + CpuCount: 1, + // 设置待查询虚拟机实例的内存容量 + MemoryCapacityInGB: 2, + // 设置待查询虚拟机实例的系统盘大小,单位GB,默认是40GB,范围为[40, 100]GB,超过40GB按照云磁盘价格收费。注意指定的系统盘大小需要满足所使用镜像最小磁盘空间限制。 + RootDiskSizeInGb: 45, + // 设置待查询虚拟机实例系统盘介质,默认使用SSD型云磁盘,可指定系统盘磁盘类型可参见StorageType + RootDiskStorageType: api.StorageTypeCloudHP1, + // 设置待查询的CDS磁盘列表 + CreateCdsList: createCdsList, + // 设置批量查询(购买)的虚拟机实例个数,必须为大于0的整数,可选参数,缺省为1 + PurchaseCount: 1, + // 设置虚拟机名字,可选参数 + Name: "your-choose-instance-name", + // 设置实例管理员密码(8-16位字符,英文,数字和符号必须同时存在,符号仅限!@#$%^*()),可选参数 + AdminPass: "your-admin-pass", + // 设置待查询实例所要绑定的密钥对ID,可选参数 + KeypairId: "your-keypair-id", + // 设置自动快照策略ID,可选参数 + AspId: "your-asp-id", + // 设置待查询虚拟机实例的镜像ID,可选参数 + ImageId: "your-image-id", + // 设置竞价实例出价模型, 市场价: "market" 自定义:"custom",可选参数 + BidModel: "your-bid-model", + // 设置竞价实例出价金额,若是自定义出价,且出价金额小于市场价,则不允许创建。当bidModel='custom'时才有效,可选参数 + BidPrice: "your-bid-price", + // 设置公网带宽,单位为Mbps。必须为0~200之间的整数,为0表示不分配公网IP,默认为0Mbps,可选参数 + NetWorkCapacityInMbps: 20, + // 设置待查询实例指定的标签是否需要和已有标签键进行关联,默认为false。注意值为true时要保证该标签键已存在,可选参数 + RelationTag: false, + // 设置待查询的标签列表,可选参数 + Tags: tagList, + // 设置securityGroup信息,为空时将使用默认安全组,可选参数 + SecurityGroupId: "your-security-group-id", + // 设置subnet信息,为空时将使用默认子网,可选参数 + SubnetId: "your-subnet-id", + // 设置指定zone信息,默认为空,由系统自动选择,可选参数 + ZoneName: "your-zone-name", + // 设置公网带宽计费方式,可选参数 + InternetChargeType: "your-internet-charge-type", +} +if res, err := bccClient.GetBidInstancePrice(args); err != nil { + fmt.Println("Get bidding instance price failed: ", err) +} else { + fmt.Println("Get bidding instance price success, result: ", res) +} +``` + +##查询实例套餐库存 + +查询实例资源套餐规格对应的库存。 +```go +// 实例类型 +instanceType := "instanceType" +// CPU核数 +cpuCount := cpuCount +// 内存容量(GB) +memoryCapacityInGB := memoryCapacityInGB +// 可用区名称 +zoneName := "zoneNamen" +// GPU卡类型,GPU和VGPU可填 +gpuCard := "gpuCard" +// GPU卡数量,GPU和VGPU可填 +cardCount := "cardCount" +//本地盘信息 +ephemeralDisks := []EphemeralDisks{{ + "storageType": "ssd", + "sizeInGB": sizeInGB, +}} + +args := &api.CreateInstanceStockArgs{ + InstanceType: instanceType, + CpuCount: cpuCount, + MemoryCapacityInGB: memoryCapacityInGB, + ZoneName: zoneName, + GpuCard: gpuCard, + CardCount: cardCount, + EphemeralDisks: ephemeralDisks, +} +if res, err := bccClient.GetInstanceCreateStock(args); err != nil { + fmt.Println("GetInstanceCreateStock failed: ", err) +} else { + fmt.Println("GetInstanceCreateStock success: ", res) +} + +``` +###实例扩缩容库存查询 + +实例变配余量查询 +```go +// 实例id +instanceId := "instanceId" +// CPU核数 +cpuCount := cpuCount +// 内存容量(GB) +memoryCapacityInGB := memoryCapacityInGB + +args := &api.CreateInstanceStockArgs{ + InstanceId: instanceId, + CpuCount: cpuCount, + MemoryCapacityInGB: memoryCapacityInGB, +} +if res, err := bccClient.ResizeInstanceStockArgs(args); err != nil { + fmt.Println("ResizeInstanceStockArgs failed: ", err) +} else { + fmt.Println("ResizeInstanceStockArgs success: ", res) +} + +``` +###查询带部署集相关字段实例详情 + 查询带部署集相关字段实例详情: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +//设置是否展示部署集字段,true or false +isDeploySet := "your-isDeploySet" + +if res, err := bccClient.GetInstanceDetailWithDeploySet(instanceId,isDeploySet); err != nil { +fmt.Println("get instance detail failed: ", err) +} else { +fmt.Println("get instance detail success, result: ", res) +} + +``` + +## 查询带部署集和失败相关字段实例详情 + +查询带部署集和失败相关字段实例详情 + +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +//设置是否展示部署集字段,true or false +isDeploySet := "your-isDeploySet" +//设置是否展示部署集字段,true or false +containsFailed := "your-containsFailed" + +if res, err := bccClient.GetInstanceDetailWithDeploySet(instanceId,isDeploySet,containsFailed); err != nil { +fmt.Println("get instance detail failed: ", err) +} else { +fmt.Println("get instance detail success, result: ", res) +} +``` +## 查询部署集详情 + +通过以下代码利用部署集ID查询部署集详情 + +```go +// 设置你要查询的deploySetID +deploySetID := "your-choose-deploy-set-id" +if res, err := bccClient.GetDeploySet(deploySetID); err != nil { + fmt.Println("Delete deploy set failed: ", err) +} else { + fmt.Println("Get deploy set success: ", res) +} +``` + +## 查询可关机不计费的实例列表 +查询可关机不计费的BCC实例列表: +```go +listInstanceArgs := &ListInstanceArgs{ + // 批量获取列表的查询起始位置,是一个由系统产生的字符串 + Marker string + // 设置返回数据大小,缺省为1000 + MaxKeys int + // 通过internal Ip过滤 + InternalIp string + // 通过DedicatedHostId过滤 + DedicatedHostId string + // 通过ZoneName过滤 + ZoneName string + // 通过KeypairId过滤 + KeypairId string +} + +if res, err := bccClient.GetInstanceNoChargeList(listInstanceArgs); err != nil { + fmt.Println("GetInstanceNoChargeList failed: ", err) +} else { + fmt.Println("GetInstanceNoChargeList success, result: ", res) +} +``` + +### 查询实例列表 + +以下代码可以查询BCC虚机实例列表,支持通过内网ip、专属服务器id、可用区名称进行筛选 +```go +args := &api.ListInstanceArgs{} + +// 若要查询某个内网IP对应的实例列表,可以配置以下参数 +args.InternalIp = "1.1.1.1" + +result, err := client.ListInstances(args) +if err != nil { + fmt.Println("list instance failed:", err) +} else { + fmt.Println("list instance success: ", result) +} +``` +### 查询实例列表V3 +以下代码可以查询BCC虚机实例列表,支持通过实例ID、实例名称、内网ip、实例公网IP、专属服务器id、私有网络名称、 +子网名称、子网ID、是否自动续费、密钥对ID、密钥对名称、部署集ID、部署集名称、资源分组、标签、可用区名称进行筛选 +```go +args := &api.ListServerRequestV3Args{ +Marker: "", +MaxKeys: 3, +} +result, err := BCC_CLIENT.ListServersByMarkerV3(args) +if err != nil { +fmt.Println("list instance failed: ", err) +} else { +fmt.Println("list instance success") +data, e := json.Marshal(result) +if e != nil { +fmt.Println("json marshal failed!") +return +} +fmt.Printf("list instance : %s", data) +} +``` + +### 查询回收站实例列表 + +以下代码可以查询回收站中的BCC虚机实例列表,支持通过虚机id,名字进行筛选 +```go +// 批量获取列表的查询的起始位置,是一个由系统生成的字符串,可选参数 +marker := "your-marker" +// 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000,可选参数 +maxKeys := your-maxKeys +// 设置想要查询的付费类型,可选参数 Prepaid表示预付费,Postpaid表示后付费,不传表示都选 +paymentTiming := "Postpaid" +// 设置想要查询的虚机id,可选参数 +instanceId := "your-choose-instance-id" +// 设置想要查询的虚机名称,可选参数 +name := "your-choose-name" +// 设置想要查询虚机的回收开始时间(北京时间),可选参数 (闭区间) +recycleBegin := "2020-11-19T09:12:35Z" +// 设置想要查询虚机的回收结束时间(北京时间),可选参数 (开区间) +recycleEnd := "2020-11-26T09:12:35Z" +args := &api.ListRecycleInstanceArgs{ + Marker: marker, + MaxKeys: maxKeys, + PaymentTiming: paymentTiming, + InstanceId: instanceId, + Name: name, + RecycleBegin: recycleBegin, + RecycleEnd: recycleEnd, +} +result, err := client.ListRecycleInstances(args) +if err != nil { + fmt.Println("list instance failed:", err) +} else { + fmt.Println("list instance success: ", result) +} +``` + + +### 查询指定实例详情 + +使用以下代码可以查询指定BCC虚机的详细信息 +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +result, err := client.GetInstanceDetail(instanceId) +if err != nil { + fmt.Println("get instance detail failed:", err) +} else + fmt.Println("get instance detail success ", result) +} +``` + +### 启动实例 + +如下代码可以启动一个实例 +```go +err := client.StartInstance(instanceId) +if err != nil { + fmt.Println("start instance failed:", err) +} else { + fmt.Println("start instance success") +} +``` + +> **提示:** +> - 实例状态必须为Stopped,调用此接口才能成功返回,否则返回409错误 +> - 该接口调用后,实例会进入Starting状态 + +### 停止实例 + +如下代码可以停止一个实例 +```go +// 以下代码可以强制停止一个实例 +err := client.StopInstance(instanceId, true) +if err != nil { + fmt.Println("stop instance failed:", err) +} else { + fmt.Println("stop instance success") +} +``` + +## 停止实例(支持强制停止&关机不计费) +使用以下代码停止实例: + +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +// 设置是否强制停止,强制停止等同于断电处理,可能丢失实例操作系统中未写入磁盘的数据 +forceStop := false +// 设置是否关机不计费,TRUE为关机不计费,FALSE为关机计费。注意:只有白名单用户才可以实行关机不计费 +stopWithNoCharge := false + +if err := bccClient.StopInstanceWithNoCharge(instanceId, forceStop, stopWithNoCharge); err != nil { + fmt.Println("Stop instance failed: ", err) +} else { + fmt.Println("Stop instance success.") +} +``` + +> **提示:** +> - 系统后台会在实例实际 Stop 成功后进入“已停止”状态。 +> - 只有状态为 Running 的实例才可以进行此操作,否则提示 409 错误。 +> - 实例支持强制停止,强制停止等同于断电处理,可能丢失实例操作系统中未写入磁盘的数据。 + +### 重启实例 + +如下代码可以重启实例 +```go +// 以下代码可以强制重启一个实例 +err := client.RebootInstance(instanceId, true) +if err != nil { + fmt.Println("reboot instance failed:", err) +} else { + fmt.Println("reboot instance success") +} +``` + +> **提示:** +> - 只有状态为 Running 的实例才可以进行此操作,否则提示 409 错误。 +> - 接口调用成功后实例进入 Starting 状态。 +> - 支持强制重启,强制重启等同于传统服务器的断电重启,可能丢失实例操作系统中未写入磁盘的数据。 + +### 修改实例密码 + +如下代码可以修改实例密码 +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +args := &api.ChangeInstancePassArgs{ + AdminPass: "321zaq#@!", +} +err := client.ChangeInstancePass(instanceId, args) +if err != nil { + fmt.Println("change instance password failed:", err) +} else { + fmt.Println("change instance password success") +} +``` + +> **提示:** +> 只有 Running 和 Stopped 状态的实例才可以用调用接口,否则提示 409 错误。 + +### 修改实例属性 + +如下代码可以修改实例属性 +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +args := &api.ModifyInstanceAttributeArgs{ + Name: "newInstanceName", + NetEthQueueCount: "new eth queue count", +} +err := client.ModifyInstanceAttribute(instanceId, args) +if err != nil { + fmt.Println("modify instance failed:", err) +} else { + fmt.Println("modify instance success") +} +``` + +> **提示:** +> - 目前该接口仅支持修改实例名称 + +### 修改实例描述 + +如下代码可以修改实例描述 +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +args := &api.ModifyInstanceDescArgs{ + Description: "new Instance description", +} +err := client.ModifyInstanceDesc(instanceId, args) +if err != nil { + fmt.Println("modify instance failed:", err) +} else { + fmt.Println("modify instance success") +} +``` + +### 修改实例主机名 + +如下代码可以修改实例主机名 +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +args := &api.ModifyInstanceHostnameArgs{ + // 设置想要修改的新主机名 + Hostname: "new Instance hostname", + // 设置是否开启domain,可选参数 true表示开启 false和null 表示关闭 + IsOpenHostnameDomain: true, + // 设置是否自动重启,可选参数 true表示重启,false和null表示不重启 + Reboot: true, +} +err := client.ModifyInstanceHostname(instanceId, args) +if err != nil { + fmt.Println("modify instance hostname failed:", err) +} else { + fmt.Println("modify instance hostname success") +} +``` + +### 重装实例 + +如下代码可以重装实例 +```go +IsOpenHostEye := true +IsPreserveData := true +args := &api.RebuildInstanceArgs{ + ImageId: "m-***", + AdminPass: "***", + // 设置要绑定的密钥对ID + KeypairId: "keypairId", + // 是否开启hosteye服务,选填 + IsOpenHostEye: &IsOpenHostEye, + // 以下参数机型相关,使用部分ebc套餐时选填 + IsPreserveData: &IsPreserveData, + // 此参数在isPreserveData为false时为必填,在isPreserveData为true时不生效 + RaidId: "your_raid_id", + // 系统盘根分区大小,默认为20G,取值范围为20-100。此参数在isPreserveData为true时不生效 + SysRootSize: 20, + // 指定系统盘文件系统,当前合法值:xfs,ext4 + RootPartitionType: "your-choose-rootPartitionType", + // 指定数据盘文件系统,当前合法值:xfs,ext4 + DataPartitionType: "your-choose-dataPartitionType", +} +err := client.RebuildInstance(instanceId, args) +if err != nil { + fmt.Println("rebuild instance failed:", err) +} else { + fmt.Println("rebuild instance success") +} +``` + +## 重装实例(批量) +使用以下代码重装实例: + +```go +IsOpenHostEye := true +IsPreserveData := true +rebuildBatchInstanceArgs := &api.RebuildBatchInstanceArgs{ + // 输入你要重装instance使用的镜像ID + ImageId: "imageId", + // 设置BCC虚机密码 + AdminPass: "***", + // 设置要绑定的密钥对ID + KeypairId: "keypairId", + // 实例ID集合 + InstanceIds: []string{"instanceIds"}, + // 是否开启hosteye服务,选填 + IsOpenHostEye: &IsOpenHostEye, + // 以下参数机型相关,使用部分ebc套餐时选填 + IsPreserveData: &IsPreserveData, + // 此参数在isPreserveData为false时为必填,在isPreserveData为true时不生效 + RaidId: "your_raid_id", + // 系统盘根分区大小,默认为20G,取值范围为20-100。此参数在isPreserveData为true时不生效 + SysRootSize: 20, + // 指定系统盘文件系统,当前合法值:xfs,ext4 + RootPartitionType: "your-choose-rootPartitionType", + // 指定数据盘文件系统,当前合法值:xfs,ext4 + DataPartitionType: "your-choose-dataPartitionType", +} + +if err := bccClient.BatchRebuildInstances(rebuildBatchInstanceArgs); err != nil { + fmt.Println("rebuild batch instance failed: ", err) +} else { + fmt.Println("rebuild batch instance success.") +} +``` + +> **提示:** +> - 实例重装后,基于原系统盘的快照会自动删除,基于原系统盘的自定义镜像会保留。 + +### 释放实例 + +如下代码可以释放实例 +```go +err := client.DeleteInstance(instanceId) +if err != nil { + fmt.Println("delete instance failed:", err) +} else { + fmt.Println("delete instance success") +} +``` + +### 释放实例(POST) +使用以下代码释放实例: +```go +deleteInstanceWithRelateResourceArgs := &api.DeleteInstanceWithRelateResourceArgs{ + // 设置释放的时候是否关联释放当前时刻,实例挂载的eip+数据盘 false代表否 true代表是 + // (只有该字段为true时 deleteCdsSnapshotFlag字段才会有效,若该字段为false,deleteCdsSnapshotFlag字段的值无效) + RelatedReleaseFlag: true, + //设置是否释放弹性网卡 false代表否 true代表是,默认false + DeleteRelatedEnisFlag: true, + // 设置是否释放云磁盘快照 false代表否 true代表是 + DeleteCdsSnapshotFlag: true, + // 设置是否进入回收站 true表示进入回收站, false和null表示不进入回收站 + BccRecycleFlag: true, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.DeleteInstanceWithRelateResource(instanceId, deleteInstanceWithRelateResourceArgs); err != nil { + fmt.Println("release instance failed: ", err) +} else { + fmt.Println("release instance success.") +} +``` +### 批量释放实例(POST) +使用以下代码批量释放实例: +```go +deleteInstanceWithRelateResourceArgs := &api.BatchDeleteInstanceWithRelateResourceArgs{ + // 设置释放的时候是否关联释放当前时刻,实例挂载的eip+数据盘 false代表否 true代表是 + // (只有该字段为true时 deleteCdsSnapshotFlag字段才会有效,若该字段为false,deleteCdsSnapshotFlag字段的值无效) + RelatedReleaseFlag: true, + //设置是否释放弹性网卡 false代表否 true代表是,默认false + DeleteRelatedEnisFlag: true, + // 设置是否释放云磁盘快照 false代表否 true代表是 + DeleteCdsSnapshotFlag: true, + // 设置是否进入回收站 true表示进入回收站, false和null表示不进入回收站 + BccRecycleFlag: true, + // 批量释放的实例id + InstanceIds: []string{"i-tzKEY***"}, +} +if err := bccClient.BatchDeleteInstanceWithRelateResource(deleteInstanceWithRelateResourceArgs); err != nil { + fmt.Println("release instance failed: ", err) +} else { + fmt.Println("release instance success.") +} +``` + +### 释放实例(包含预付费实例) +不区分后付费还是预付费实例,释放bcc以及关联的资源,可以使用以下代码将其释放: +```go + args := &api.DeleteInstanceIngorePaymentArgs{ + InstanceId: "instanceid", + //设置是否释放eip和cds false代表eip和cds与实例解绑,实例进回收站;true代表eip解绑,cds与实例绑定进回收站 + RelatedReleaseFlag: true, + //设置是否释放弹性网卡 false代表否 true代表是,默认false + DeleteRelatedEnisFlag:true, + //设置是否释放云磁盘快照 false代表否 true代表是,默认false,释放预付费bcc时DeleteCdsSnapshotFlag和RelatedReleaseFlag存在绑定关系, + RelatedReleaseFlag为true时,DeleteCdsSnapshotFlag必须为true + // 选择DeleteCdsSnapshotFlag=true即会释放虚机绑定的各种快照 + // 释放后付费bcc时,DeleteCdsSnapshotFlag和RelatedReleaseFlag之间逻辑和之前逻辑保持一致 + DeleteCdsSnapshotFlag:true, + //设置是否立即释放,默认false,保持释放进入回收站逻辑;为true时,实例和设置了关联释放的cds资源,一起立即释放 + DeleteImmediate: false, + + } + if res, err := BCC_CLIENT.DeleteInstanceIngorePayment(args); err != nil { + fmt.Println("delete instance failed: ", err) + } else { + fmt.Printf("delete instance success, result: %s", res.String()) + } + +``` + +### 释放回收站实例 +回收站实例7天后自动释放,清理回收站资源,可以使用以下代码将其释放: +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +if err := bccClient.DeleteRecycledInstance(instanceId); err != nil { + fmt.Println("release instance failed: ", err) +} else { + fmt.Println("release instance success.") +} +``` + +> **提示:** +> - 释放单个云服务器实例,释放后实例所使用的物理资源都被收回,相关数据全部丢失且不可恢复。 +> - 只有付费类型为Postpaid或者付费类型为Prepaid且已过期的实例才可以释放。 +> - 实例释放后,已挂载的CDS磁盘自动卸载,,基于此CDS磁盘的快照会保留。 +> - 实例释放后,基于原系统盘的快照会自动删除,基于原系统盘的自定义镜像会保留。 + +### 定时释放 (限定后付费实例) + +后付费实例定时释放,到达预设时间后自动释放bcc,自动释放时间可查询实例详情ReleaseTime。设定空字符串可以取消定时释放。请谨慎使用该功能,避免遗忘定时设置 +```go +err := bccClient.AutoReleaseInstance(instanceId, "2021-05-01T07:58:09Z") +if err != nil { + fmt.Println("set instance autoRelease failed:", err) +} else { + fmt.Println("set instance autoRelease success") +} +``` + +> **提示:** +> - 只有付费类型为Postpaid的后付费实例允许设定自动释放 +> - 本实例系统盘快照及实例快照都会被释放 +> - 本实例已挂载CDS云磁盘都会被自动卸载,不会被释放 +> - 实例释放后不可恢复 +> - 关联的网卡资源会被自动卸载,且被释放 + +### 释放保护 +使用以下代码可以为BCC实例设置释放保护,实例当前设置可查询实例详情DeletionProtection,默认0不保护,1释放保护中(创建和查询入口限v2版本使用): + +```go +args := &api.DeletionProtectionArgs { +// 释放保护状态 0不启用,1启用 + DeletionProtection : 0, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.ModifyDeletionProtection(instanceId, args); err != nil { + fmt.Println("modifyDeletionProtection failed: ", err) +} else { + fmt.Println("modifyDeletionProtection success.") +} +``` + +> **提示:** +> - 后付费和预付费均可开启释放保护 +> - 已开启释放保护的实例将无法通过控制台或API释放,只有在关闭的情况下才能被手动释放。定时释放,欠费释放以及实例过期释放不受释放保护属性的影响 +> - 实例释放保护默认不开启 + +### 变配实例 +使用以下代码可以选择CPU,MemoryCapacityInGB,EphemeralDisks变配指定BCC实例: + +```go +resizeInstanceArgs := &ResizeInstanceArgs{ + // BCC核数 + CpuCount: CpuCount + // BCC的内存大小GB + MemoryCapacityInGB: MemoryCapacityInGB + // 临时盘数据盘大小 + EphemeralDisks []EphemeralDisk "ephemeralDisks" +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.ResizeInstance(instanceId, resizeInstanceArgs); err != nil { + fmt.Println("resize instance failed: ", err) +} else { + fmt.Println("resize instance success.") +} +``` +### 变配实例(通过实例套餐规格) +使用以下代码可以选择CPU,MemoryCapacityInGB,EphemeralDisks变配指定BCC实例: + +```go +resizeInstanceArgs := &ResizeInstanceArgs{ + // 实例套餐规格 + Spec string "spec" +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.ResizeInstanceBySpec(instanceId, resizeInstanceArgs); err != nil { + fmt.Println("resize instance failed: ", err) +} else { + fmt.Println("resize instance success.") +} +``` + +### 绑定安全组 +使用以下代码绑定安全组: + +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +// 设置BCC绑定的安全组 +SecurityGroupId := "SecurityGroupId" + +if err := bccClient.BindSecurityGroup(instanceId, SecurityGroupId); err != nil { + fmt.Println("Bind Security Group failed: ", err) +} else { + fmt.Println("Bind Security Group success.") +} +``` +### 解绑安全组 +使用以下代码解绑安全组: + +```go +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" +// 设置BCC解绑的安全组 +SecurityGroupId := "SecurityGroupId" + +if err := bccClient.UnBindSecurityGroup(instanceId, SecurityGroupId); err != nil { + fmt.Println("UnBind Security Group failed: ", err) +} else { + fmt.Println("UnBind Security Group success.") +} +``` + +> **提示:** +> - 每个实例至少关联一个安全组,默认关联默认安全组。 +> - 如果实例仅属于一个安全组,尝试移出时,请求会报 403 错。 + +### 实例扩缩容 + +```go +args := &api.ResizeInstanceArgs{ + CpuCount: 2, + MemoryCapacityInGB: 4, + LiveResize: true, +} +err := client.ResizeInstance(instanceId, args) +if err != nil { + fmt.Println("resize instance failed:", err) +} else { + fmt.Println("resize instance success") +``` + +> **提示:** +> - 实例计费方式为预付费时,不能进行缩容操作 +> - 实例计费方式为后付费时,可弹性扩缩容 +> - 只有实例Running或Stopped状态时可以进行扩缩容操作 +> - 实例扩缩容之后会重启一次,可选择热升级进行扩缩容,不影响业务中断,热升级的限制请参考文档[热升级的限制](https://cloud.baidu.com/doc/BCC/s/gjwvyohty#%E5%9C%A8%E7%BA%BF%E6%94%B9%E9%85%8D%EF%BC%88%E7%83%AD%E5%8D%87%E7%BA%A7%EF%BC%89%E7%9A%84%E9%99%90%E5%88%B6%E6%9C%89%E5%93%AA%E4%BA%9B%EF%BC%9F) +> - 异步接口,可通过查询实例详情接口查看扩缩容状态是否完成 +> - 专属实例可以通过指定的cpu、内存以及临时盘大小,专属实例临时盘大小只支持扩容而不支持缩容,具体请参考API文档 [实例扩缩容](https://cloud.baidu.com/doc/BCC/s/1jwvyoc9l) +### 查询实例VNC地址 + +如下代码可以查询实例的VNC地址 +```go +result, err := client.GetInstanceVNC(instanceId) +if err != nil { + fmt.Println("get instance VNC url failed:", err) +} else { + fmt.Println("get instance VNC url success: ", result) +} +``` + +> **提示:** +> - VNC地址一次使用后即失效 +> - URL地址有效期为10分钟 + +### 实例续费 + +对BCC虚机的续费操作,可以延长过期时长,以下代码可以对实例及关联产品进行续费 +```go +args := &api.PurchaseReservedArgs{ + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + // 设置实例关联续费标识,默认为空字符串。 + RelatedRenewFlag: "CDS", +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +result, err := bccClient.InstancePurchaseReserved(instanceId, args) +if err != nil { + fmt.Println("Purchase Reserved Instance failed: ", err) +} else { + fmt.Println("Purchase Reserved Instance success: ", result) +} +``` +> **注意:** +> +> 关联续费产品(relatedRenewFlag)可选: +> +> - CDS 只对BCC实例关联的预付费CDS进行续费 +> - EIP 只对BCC实例关联的预付费EIP进行续费 +> - MKT 只对BCC实例关联的预付费MKT进行续费 +> - CDS_EIP 只对BCC实例关联的预付费CDS、EIP进行续费 +> - CDS_MKT 只对BCC实例关联的预付费CDS、MKT进行续费 +> - EIP_MKT 只对BCC实例关联的预付费EIP、MKT进行续费 +> - CDS_EIP_MKT 只对BCC实例关联的预付费CDS、EIP、MKT进行续费 + +> **提示:** +> - BCC虚机实例扩缩容期间不能进行续费操作。 +> - 续费时若实例已欠费停机,续费成功后有个BCC虚机实例启动的过程。 +> - 该接口是一个异步接口。 +> - 专属实例不支持续费。 + +### 实例变更子网 + +如下代码可以变更实例的子网 +```go +args := &api.InstanceChangeSubnetArgs{ + InstanceId: instanceId, + SubnetId: subnetId, + InternalIp: internalIp, + Reboot: false, +} +err := client.InstanceChangeSubnet(args) +if err != nil { + fmt.Println("change instance subnet failed:", err) +} else { + fmt.Println("change instance subnet success") +} +``` + +> **提示:** +> - 变更子网后默认自动重启,用户选择是否执行该操作。 +> - 变更子网的范围目前仅支持在同AZ下变更子网,不支持跨AZ或跨VPC变更子网,如果从普通子网变更至NAT专属子网请先手动解绑EIP。 + +### 实例变更VPC + +如下代码可以变更实例的VPC +```go +args := &api.InstanceChangeVpcArgs{ + InstanceId: instanceId, + SubnetId: subnetId, + InternalIp: internalIp, + Reboot: true, + SecurityGroupIds: securityGroupId, + EnterpriseSecurityGroupIds: enterpriseSecurityGroupId +} +err := client.InstanceChangeVpc(args) +if err != nil { + fmt.Println("change instance vpc failed:", err) +} else { + fmt.Println("change instance vpc success") +} +``` + +> **提示:** +> - 变更VPC后默认自动重启,用户选择是否执行该操作。 +> - 变更VPC后仅保留主网卡主IP(在新子网中自动分配),实例上的辅助IP、弹性网卡和安全组等信息不跟随主体迁移。 +> - 安全组和企业安全组不能同时指定。 + +### 向指定实例批量添加指定ip + +```go +batchAddIpArgs := &api.BatchAddIpArgs{ + // 实例ID + InstanceId: "instanceId", + // 辅助IP,和SecondaryPrivateIpAddressCount不可同时使用 + PrivateIps: []string{"privateIps"}, + // 自动分配IP数量,和PrivateIps不可同时使用 + SecondaryPrivateIpAddressCount: 1, + // 是否是创建ipv6,ipv6必须是true,默认为false,创建ipv4 + AllocateMultiIpv6Addr: true, + // 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 + ClientToken: "clientToken", +} + +if res, err := bccClient.BatchAddIP(batchAddIpArgs); err != nil { + fmt.Println("BatchAddIP failed: ", err) +} else { + fmt.Println("BatchAddIP success, result: ", res) +} +``` + +### 批量删除指定实例的ip + +```go +privateIps := []string{"192.168.1.25"} +instanceId := "your-choose-instance-id" +// 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 +clientToken := "clientToken" +batchDelIpArgs := &api.BatchDelIpArgs{ + InstanceId: instanceId, + PrivateIps: privateIps, + ClientToken: clientToken, +} +if err := client.BatchDelIP(batchDelIpArgs); err != nil { + fmt.Println("delete ips failed: ", err) +} else { + fmt.Println("delete ips success.") +} +``` + +### 开通自动续费(包含关联产品) +自动续费仅限预付费产品 + +```go +bccCreateAutoRenewArgs := &api.BccCreateAutoRenewArgs{ + // 实例ID + InstanceId: instanceId, + // 续费单位,month,year + RenewTimeUnit: "month", + // 续费时长,单位:month,支持1, 2, 3, 4, 5, 6, 7, 8, 9;单位:year,支持1, 2, 3 + RenewTime: 1, +} + +if err := bccClient.BatchCreateAutoRenewRules(bccCreateAutoRenewArgs); err != nil { + fmt.Println("BatchCreateAutoRenewRules failed: ", err) +} else { + fmt.Println("BatchCreateAutoRenewRules success.") +} +``` + +### 关闭自动续费(包含关联产品) +自动续费仅限预付费产品 + +```go +bccDeleteAutoRenewArgs := &api.BccDeleteAutoRenewArgs{ + // 实例ID + InstanceId: instanceId, +} + +if err := bccClient.BatchDeleteAutoRenewRules(bccDeleteAutoRenewArgs); err != nil { + fmt.Println("BatchDeleteAutoRenewRules failed: ", err) +} else { + fmt.Println("BatchDeleteAutoRenewRules success.") +} +``` + +### 后付费资源从回收站恢复计费 +仅限后付费产品,预付费资源走续费接口 + +```go +args := &api.RecoveryInstanceArgs{ + InstanceIds: []api.RecoveryInstanceModel{ + { + InstanceId: instanceId, + }, + }, +} +if err := BCC_CLIENT.RecoveryInstance(args); err != nil { + fmt.Println("recovery instance failed: ", err) +} else { + fmt.Println("recovery instance success") +} + +``` + +### 计费变更-转预付费 +使用以下代码对实例计费变更-转预付费: + +```go +changeToPrepaidRequest := &ChangeToPrepaidRequest{ + // 设置将要变更预付费的时长,单位为月 + Duration int "duration" + // 设置是否变更关联的数据盘,TRUE表示变更,FLASE表示不变更 + RelationCds bool "relationCds" +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.ChangeToPrepaid(instanceId, changeToPrepaidRequest); err != nil { + fmt.Println("ChangeToPrepaid failed: ", err) +} else { + fmt.Println("ChangeToPrepaid success.") +} +``` + +### 实例绑定标签 +使用以下代码对实例绑定标签: + +```go +bindTagsRequest := &api.BindTagsRequest{ + // 设置想要绑定的标签 + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.BindInstanceToTags(instanceId, bindTagsRequest); err != nil { + fmt.Println("BindInstanceToTags failed: ", err) +} else { + fmt.Println("BindInstanceToTags success.") +} +``` + +### 实例解绑标签 +使用以下代码对实例解绑标签: + +```go +unBindTagsRequest := &api.UnBindTagsRequest{ + // 设置想要解绑的标签 + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, +} +// 设置你要操作的instanceId +instanceId := "your-choose-instance-id" + +if err := bccClient.UnBindInstanceToTags(instanceId, unBindTagsRequest); err != nil { + fmt.Println("UnBindInstanceToTags failed: ", err) +} else { + fmt.Println("UnBindInstanceToTags success.") +} +``` + +### 查询可以变配的实例规格 +使用以下代码可以查询可以变配的实例规格 +```go + listAvailableResizeSpecsArgs := &api.ListAvailableResizeSpecsArgs{ + Spec: "bcc.ic5.c1m1", + Zone: "cn-bj-a", + } + res, _ := BCC_CLIENT.ListAvailableResizeSpecs(listAvailableResizeSpecsArgs) + fmt.Println(res) +``` + +### 批量转预付费 +使用以下代码可以将实例批量转预付费,若需要对实例关联的cds变更,则必须在CdsList中传入所有需要转为预付费的cdsId,若所有cds均变更计费传入all。 +```go + batchChangeInstanceToPrepayArgs := &api.BatchChangeInstanceToPrepayArgs{ + Config: []api.PrepayConfig{ + { + InstanceId: "i-fYumyWOx", + Duration: 1, + CdsList: []string{ + "v-tP2MJ3YI", + "v-9eLRwv8n", + } + }, + { + InstanceId: "i-Q2pAyWOx", + Duration: 1, + CdsList: []string{ + "all", + } + }, + }, + } + result, err := BCC_CLIENT.BatchChangeInstanceToPrepay(batchChangeInstanceToPrepayArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +``` + +### 批量转后付费 +使用以下代码可以将实例批量转后付费, 若需要对实例关联的cds变更,则必须在CdsList中传入所有需要转为后付费的cdsId,若所有cds均变更计费传入all。 +```go + batchChangeInstanceToPostArgs := &api.BatchChangeInstanceToPostpayArgs{ + Config: []api.PostpayConfig{ + { + InstanceId: "i-IWxCA6HH", + CdsList: []string{ + "v-buE5Cm3m", + "v-rEcWwELY", + } + }, + { + InstanceId: "i-Q2pAyWOx", + CdsList: []string{ + "all", + } + }, + }, + } + result, err := BCC_CLIENT.BatchChangeInstanceToPostpay(batchChangeInstanceToPostArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +``` + +### 获取实例角色列表 +使用以下代码可以获取实例角色列表 +```go + res, _ := BCC_CLIENT.ListInstanceRoles() + fmt.Println(res) +``` + + +### 绑定角色 +使用以下代码可以为BCC实例绑定角色 +``` + bindInstanceRoleArgs := &api.BindInstanceRoleArgs{ + RoleName: "Test_BCC", + Instances: []api.Instances{ + { + InstanceId: BCC_TestBccId, + }, + }, + } + + result, _ := BCC_CLIENT.BindInstanceRole(bindInstanceRoleArgs) + fmt.Println(result) +``` + +### 解绑角色 +使用以下代码可以为BCC实例解绑角色 +``` + unbindInstanceRoleArgs := &api.UnBindInstanceRoleArgs{ + RoleName: "Test_BCC", + Instances: []api.Instances{ + { + InstanceId: BCC_TestBccId, + }, + }, + } + + result, _ := BCC_CLIENT.UnBindInstanceRole(unbindInstanceRoleArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +``` + +### 添加Ipv6 +使用以下代码可以为BCC实例添加Ipv6 +```go + addIpv6Args := &api.AddIpv6Args{ + InstanceId: BCC_TestBccId, + Reboot: true, + Ipv6Address: "2400:da00:e003:0:41c:4100:0:2", + } + + result, _ := BCC_CLIENT.AddIpv6(addIpv6Args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +``` + +### 释放Ipv6 +使用以下代码可以为BCC实例释放Ipv6 +``` go +deleteIpv6Args := &api.DeleteIpv6Args{ + InstanceId: BCC_TestBccId, + Reboot: true, + } + + err := BCC_CLIENT.DeleteIpv6(deleteIpv6Args) + fmt.Println(err) +``` + +### 根据实例ID批量查询实例列表 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &api.ListInstanceByInstanceIdArgs{ + // 待查询的实例id列表 + InstanceIds: []string{ + "i-c2sXa***", + "i-kcLZB***", + }, +} +result, err := BCC_CLIENT.ListInstanceByInstanceIds(args) +if err != nil { + fmt.Println("list instance failed:", err) +} else { + fmt.Println("list instance success: ", result) +} +``` + +### 批量查询实例是否删除完成 +以下代码可以根据实例ID批量查询实例是否删除完成 +```go + bccId := "bccId" + args := &api.GetInstanceDeleteProgressArgs{ + InstanceIds: []string{ + bccId, + }, + } + + res, err := BCC_CLIENT.GetInstanceDeleteProgress(args) + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +``` + +### 查询实例绑定的弹性网卡列表 + +使用以下代码可以查询实例绑定的弹性网卡列表 + +```go +// 设置你要操作的instanceId +instanceId := "instanceId" +if res, err := BCC_CLIENT.ListInstanceEnis(instanceId); err != nil { + fmt.Println("Get specific instance eni failed: ", err) +} else { + fmt.Println("Get specific instance eni success, result: ", res) +} +``` + +## 磁盘管理 + +### 查询可用区的磁盘信息 +使用以下代码可以查询指定可用区的磁盘信息 +```GO +// 设置你要操作的zoneName +zoneName := "cn-bj-a" +if res, err := bccClient.GetAvailableDiskInfo(zoneName); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) +} else { + fmt.Println("Get the specific zone flavor success, result: ", res) +} +``` + +### 创建CDS磁盘 + +支持新建空白CDS磁盘或者从CDS数据盘快照创建CDS磁盘,参考以下代码可以创建CDS磁盘: + +```go +// 新建CDS磁盘 +args := &api.CreateCDSVolumeArgs{ + // 创建一个CDS磁盘,若要同时创建多个相同配置的磁盘,可以修改此参数 + PurchaseCount: 1, + // 磁盘空间大小 + CdsSizeInGB: 40, + // 设置磁盘存储介质 + StorageType: api.StorageTypeSSD, + // 设置磁盘付费模式为后付费 + Billing: &api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + // 设置磁盘名称 + Name: "sdkCreate", + // 设置磁盘描述 + Description: "sdk test", + // 快照ID + SnapshotId string "snapshotId" + // 可用区 + ZoneName string "zoneName" + // 设置磁盘加密密钥 + EncryptKey string "encryptKey" +} +result, err := client.CreateCDSVolume(args) +if err != nil { + fmt.Println("create CDS volume failed:", err) +} else { + fmt.Println("create CDS volume success: ", result) +} +``` + +> **提示:** +> - 创建CDS磁盘接口为异步接口,可通过[查询磁盘详情](#查询磁盘详情)接口查询磁盘状态,详细接口使用请参考BCC API 文档[查询磁盘详情](https://cloud.baidu.com/doc/BCC/s/1jwvyo4ly) + + +### 释放预付费CDS磁盘 +支持释放预付费的磁盘,参考以下代码可以释放磁盘: +```go +args := &api.VolumePrepayDeleteRequestArgs{ + VolumeId: "v-tVDW1NkK", + RelatedReleaseFlag: false, + } + result, err := BCC_CLIENT.DeletePrepayVolume(args) + if err != nil { + fmt.Println("delete volume failed: ", err) + } else { + fmt.Println("delete volume success") + data, e := json.Marshal(result) + if e != nil { + fmt.Println("json marshal failed!") + return + } + fmt.Printf("delete volume : %s", data) + } +``` + +### 创建CDS磁盘(V3) + +支持新建空白CDS磁盘或者从CDS数据盘快照创建CDS磁盘,参考以下代码可以创建CDS磁盘: + +```go +// 新建CDS磁盘 +args := &api.CreateCDSVolumeV3Args{ + // 创建一个CDS磁盘,若要同时创建多个相同配置的磁盘,可以修改此参数 + PurchaseCount: 1, + // 磁盘空间大小 + VolumeSize: 50, + // 设置磁盘存储介质 + StorageType: api.StorageTypeV3CloudSSDGeneral, + // 设置磁盘付费模式为后付费 + Billing: &api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + // 设置磁盘名称 + VolumeName: "sdkCreate", + // 设置磁盘描述 + Description: "sdk test", + // 快照ID + SnapshotId string "snapshotId", + // 可用区 + ZoneName string "zoneName", + // 设置磁盘加密密钥 + EncryptKey string "encryptKey", + // 自动续费的时间单位,按月付费或者按年付费 月是"month",年是"year" + RenewTimeUnit string "renewTimeUnit" + // 自动续费的时间 按月是1-9 按年是 1-3 + RenewTime int "renewTime" + // 设置自动快照策略id + AutoSnapshotPolicyId string "autoSnapshotPolicyId", +} +result, err := client.CreateCDSVolumeV3(args) +if err != nil { + fmt.Println("create CDS volume failed:", err) +} else { + fmt.Println("create CDS volume success: ", result) +} +``` + +> **提示:** +> - 创建CDS磁盘接口为异步接口,可通过[查询磁盘详情](#查询磁盘详情)接口查询磁盘状态 + +### 查询磁盘列表 + +以下代码可以查询所有的磁盘列表,支持分页查询以及通过次磁盘所挂载的BCC实例id进行过滤筛选: + +```go +args := &api.ListCDSVolumeArgs{} + +// 设置查询绑定了特定实例的CDS磁盘 +args.InstanceId = instanceId + +result, err := client.ListCDSVolume(args) +if err != nil { + fmt.Println("list CDS volume failed:", err) +} else { + fmt.Println("list CDS volume success: ", result) +} +``` + +### 查询磁盘列表(V3) + +以下代码可以查询所有的磁盘列表,支持分页查询以及通过次磁盘所挂载的BCC实例id进行过滤筛选: + +```go +args := &api.ListCDSVolumeArgs{} + +// 设置查询绑定了特定实例的CDS磁盘 +args.InstanceId = instanceId + +result, err := client.ListCDSVolumeV3(args) +if err != nil { + fmt.Println("list CDS volume failed:", err) +} else { + fmt.Println("list CDS volume success: ", result) +} +``` + +### 查询磁盘详情 + +通过磁盘id可以获取对应磁盘的详细信息,以下代码可以查询磁盘详情: + +```go +result, err := client.GetCDSVolumeDetail(volumeId) +if err != nil { + fmt.Println("get CDS volume detail failed:", err) +} else { + fmt.Println("get CDS volume detail success: ", result) +} +``` + +### 查询磁盘详情(V3) + +通过磁盘id可以获取对应磁盘的详细信息,以下代码可以查询磁盘详情: + +```go +result, err := client.GetCDSVolumeDetailV3(volumeId) +if err != nil { + fmt.Println("get CDS volume detail failed:", err) +} else { + fmt.Println("get CDS volume detail success: ", result.Volume) +} +``` + +### 挂载CDS磁盘 + +可以将未挂载的磁盘挂载在对应的BCC虚机下,以下代码将一个CDS挂载在对应的BCC虚机下: + +```go +args := &api.AttachVolumeArgs{ + InstanceId: instanceId, +} +result, err := client.AttachCDSVolume(volumeId, args) +if err != nil { + fmt.Println("attach CDS volume to instance failed:", err) +} else { + fmt.Println("attach CDS volume to instance success: ", result) +} +``` + +> **提示:** +> - CDS磁盘需要挂载在与其处在相同zone下的虚机实例上,否则将返回403错误。 +> - 只有磁盘状态为 Available 且实例状态为 Running 或 Stopped 时才允许挂载,否则调用此接口将返回 409 错误。 + +### 卸载CDS磁盘 + +可以将已挂载的磁盘从对应的BCC虚机上卸载下来,以下代码卸载CDS磁盘: + +```go +args := &api.DetachVolumeArgs{ + InstanceId: instanceId, +} +err := client.DetachCDSVolume(volumeId, args) +if err != nil { + fmt.Println("detach CDS volume from instance failed:", err) +} else { + fmt.Println("detach CDS volume from instance success") +} +``` + +> **提示:** +> - 只有实例状态为 Running 或 Stopped 时,磁盘才可以执行此操作,否则将提示 409 错误。 +> - 如果 volumeId 的磁盘不挂载在 instanceId 的实例上,该操作失败,提示 404 错误。 + +### 释放CDS磁盘 + +用于释放未挂载的CDS磁盘,可指定是否删除磁盘关联的快照,缺省情况下,该磁盘的所有快照将保留,但会删除与磁盘的关联关系: + +```go +err = client.DeleteCDSVolume(volumeId) +if err != nil { + fmt.Println("delete CDS volume failed:", err) +} else { + fmt.Println("delete CDS volume success") +} +``` + +> **提示:** +> - 已挂载的CDS磁盘不能释放,系统盘不能释放。 +> - 磁盘释放后不可恢复。缺省情况下,该磁盘的所有快照将保留,但会删除与磁盘的关联关系。 +> - 只有磁盘状态为 Available 或 Expired 或 Error 时才可以执行此操作,否则将提示 409 错误。 + +## 释放磁盘(POST) +使用以下代码可以释放磁盘: +```go +deleteCDSVolumeArgs := &DeleteCDSVolumeArgs{ + AutoSnapshot: "on", // 是否删除磁盘关联的自动快照,取值为"on"时,会删除磁盘关联的手动快照 + ManualSnapshot: "on", // 是否删除磁盘关联的手动快照,取值为"on"时,会删除磁盘关联的自动快照 + Recycle: "off", // 是否将磁盘回收至回收站,为off时直接释放,不进入回收站 +} +// 设置你要操作的volumeId +volumeId := "your-choose-volume-id" +if err := bccClient.DeleteCDSVolumeNew(volumeId, deleteCDSVolumeArgs); err != nil { + fmt.Println("DeleteCDSVolumeNew failed: ", err) +} else { + fmt.Println("DeleteCDSVolumeNew success") +} +``` + +### 磁盘重命名 + +如下代码可以给一个CDS磁盘重命名 +```go +args := &api.RenameCSDVolumeArgs{ + Name: "testVolume", +} +err := client.RenameCDSVolume(volumeId, args) +if err != nil { + fmt.Println("rename CDS volume failed", err) +} else { + fmt.Println("rename CDS volume success") +} +``` + +### 修改磁盘属性 + +可以使用以下代码修改指定磁盘名称、描述信息: + +```go +args := &api.ModifyCSDVolumeArgs{ + CdsName: "aaa", + Desc: "desc", +} +err := client.ModifyCDSVolume(volumeId, args) +if err != nil { + fmt.Println("modify CDS volume failed: ", err) +} else { + fmt.Println("modify CDS volume success") +} +``` + +### 磁盘计费变更 + +可以使用以下代码变更磁盘计费方式,仅支持后付费转预付费、预付费转后付费两种方式。变更为预付费需要指定购买时长。 + +```go +args := &api.ModifyChargeTypeCSDVolumeArgs{ + Billing: &api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + } + } +} +err := client.ModifyChargeTypeCDSVolume(volumeId, args) +if err != nil { + fmt.Println("modify CDS volume charge type failed:", err) +} else { + fmt.Println("modify CDS volume charge type success") +} +``` + +## 磁盘开通自动续费 +通过以下代码可以开通磁盘自动续费 +```go +// 设置要开通自动续费的磁盘id +volumeId := "your-volume-id" +// 设置按月付费或者按年付费 月是"month",年是"year" +renewTimeUnit := "your-renew-time-unit" +// 设置自动续费的时间 按月是1-9 按年是 1-3 +renewTime := 3 +args := &api.AutoRenewCDSVolumeArgs{ + VolumeId: volumeId, + RenewTimeUnit: renewTimeUnit, + RenewTime: renewTime, +} +if err := bccClient.AutoRenewCDSVolume(args); err != nil { + fmt.Println("Auto renew cds volume failed: ", err) +} else { + fmt.Println("Auto renew cds volume success") +} +``` +>- 注意数据盘才能进行自动续费操作 +>- 注意过期状态磁盘不能进行自动续费操作 +>- 异步接口,可通过查询磁盘详情接口查询磁盘到期时间 + +## 磁盘取消自动续费 +通过以下代码可以取消磁盘自动续费 +```go +// 设置要取消自动续费的磁盘id +volumeId := "your-volume-id" +args := &api.CancelAutoRenewCDSVolumeArgs{ + VolumeId: volumeId, +} +if err := bccClient.CancelAutoRenewCDSVolume(args); err != nil { + fmt.Println("Cancel auto renew cds volume failed: ", err) +} else { + fmt.Println("Cancel auto renew cds volume success") +} +``` +>- 注意数据盘才能取消进行自动续费操作 +>- 异步接口,可通过查询磁盘详情接口查询磁盘到期时间 + +### 磁盘扩容 + +使用以下代码可以对磁盘进行扩大容量操作: + +```go +args := &api.ResizeCSDVolumeArgs{ // 请求扩容参数 + NewCdsSizeInGB: 60, // 扩容大小,单位为GB + NewVolumeType: api.StorageTypeEnhancedPl1, // 扩容类型 +} + +err := client.ResizeCDSVolume(volumeId, args) +if err != nil { + fmt.Println("resize CDS volume failed:", err) +} else { + fmt.Println("resize CDS volume success") +} +``` + +> **提示:** +> - 磁盘只能进行扩大容量,不支持缩小容量。 +> - 只有Available状态的磁盘,才能进行扩容操作 +> - 磁盘扩容是一个异步接口,可通过[查询磁盘详情](#查询磁盘详情)接口查询磁盘扩容状态。 + +### 回滚磁盘 + +可以使用指定磁盘自身的快照回滚磁盘内容,使用以下代码可以对磁盘进行回滚: + +```go +args := &api.RollbackCSDVolumeArgs{ + SnapshotId: snapshotId +} +err := client.RollbackCDSVolume(volumeId, args) +if err != nil { + fmt.Println("rollback CDS volume failed:", err) +} else { + fmt.Println("rollback CDS volume success") +} +``` + +> **提示:** +> - 磁盘状态必须为 Available 才可以执行回滚磁盘操作。 +> - 指定快照id必须是由该磁盘id创建的快照。 +> - 若是回滚系统盘,实例状态必须为 Running 或 Stopped 才可以执行此操作。 +> - 回滚系统盘快照,自本次快照以来的系统盘数据将全部丢失,不可恢复。 + +### 磁盘续费 + +对磁盘的续费操作,可以延长过期时长,以下代码可以对磁盘进行续费: + +```go +args := &api.PurchaseReservedCSDVolumeArgs{ + Billing: &api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + } + } +} +err := client.PurchaseReservedCDSVolume(volumeId, args) +if err != nil { + fmt.Println("purchase reserve CDS volume failed:", err) +} else { + fmt.Println("purchase reserve CDS volume success") +} +``` + +### 释放CDS磁盘(新) + +如下代码可以释放一个CDS磁盘及相关联的快照 +```go +args := &api.DeleteCDSVolumeArgs{ + // 删除与磁盘关联的手动快照 + ManualSnapshot: "on", + // 删除与磁盘关联的自动快照 + AutoSnapshot: "on", + // 是否将磁盘回收至回收站,为off时直接释放,不进入回收站 + Recycle: "off", +} +err := client.DeleteCDSVolumeNew(volumeId, args) +if err != nil { + fmt.Println("create instance failed:", err) +} else { + fmt.Println("create instance ", ) +} +``` + +> **提示:** +> - 该接口用于释放未挂载的CDS磁盘,系统盘不能释放。 +> - 与老接口功能上的区别在于,可以控制是否删除与磁盘关联的快照。 + +### 查询可用区的磁盘信息 +使用以下代码可以查询指定可用区的磁盘信息 +```GO +// 可用区名称;当传入zoneName为空串或为非法zone时,会返回全部可用区的可购买磁盘信息。 +zoneName := "cn-bj-a" +if res, err := bccClient.GetAvailableDiskInfo(zoneName); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) +} else { + fmt.Println("Get the specific zone flavor success, result: ", res) +} +``` + +### 磁盘绑定标签 +使用以下代码可以给指定磁盘绑定标签 +```go +tagArgs := &api.TagVolumeArgs{ + RelationTag: false, // 是否为关联资源绑定标签 + ChangeTags: []api.Tag{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, +} + +BCC_CLIENT.TagVolume("v-SKy***", tagArgs) +``` + +### 磁盘解绑标签 +使用以下代码可以给指定磁盘绑定标签 +```go +tagArgs := &api.TagVolumeArgs{ + RelationTag: false, // 是否为关联资源解绑标签 + ChangeTags: []api.Tag{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, +} + + BCC_CLIENT.UntagVolume("v-Crt***", tagArgs) +``` + +## 镜像管理 + +### 创建自定义镜像 +- 该接口用于创建自定义镜像,默认配额20个每账号,创建后的镜像可用于创建实例。 +- 支持通过实例创建和通过快照创建两种方式。 +- 当通过实例创建时,只有 Running 或 Stopped 状态的实例才可以执行成功,否则会提示 409 错误。 +- 仅限通过系统盘快照创建自定义镜像。 +- 当通过快照创建时,只有 Available 状态的快照才可以执行成功,否则会提示 409 错误 +```go +// 待创建的自定义镜像名称,支持大小写字母、数字、中文以及-_ /.特殊字符,必须以字母开头,长度1-65。 +imageName := "your-imageName" +// 当从实例创建镜像时,此参数是指用于创建镜像的实例ID。可选参数,与 snapshotId 不同时存在,同时存在时只取instanceId +instanceId := "your-instanceId" +// 当从快照创建镜像时,此参数是指用于创建镜像的快照ID。可选参数,与 instanceId 不同时存在,同时存在时只取instanceId +snapshotId := "your-snapshotId" +// 是否关联CDS,默认为false +relateCds := true or false +args := &api.CreateImageArgs{ + ImageName: imageName, + InstanceId: instanceId, + SnapshotId: snapshotId, + RelateCds: relateCds, +} +if res, err := bccClient.CreateImage(args); err != nil { + fmt.Println("create image failed: ", err) +} else { + fmt.Println("create image success:", res) +} +``` + +> 注意,创建自定义镜像,默认配额20个每账号。 + +### 查询镜像列表 +- 使用以下代码可以查询有权限的镜像列表。 +- 查询的镜像信息中包括系统镜像、自定义镜像和服务集成镜像。 +- 支持按 imageType 来过滤查询,此参数非必需,缺省为 All,即查询所有类型的镜像。 +- 支持按 imageName 来过滤查询自定义镜像,返回名称中包含该字符串的镜像。此参数非必需,设定ImageName时,必须同时指定ImageType为'Custom'。 +```go +// 批量获取列表的查询的起始位置,是一个由系统生成的字符串,可选参数 +marker := "your-marker" +// 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000,可选参数 +maxKeys := your-maxKeys +// 指定要查询何种类型的镜像,包括All(所有),System(系统镜像/公共镜像),Custom(自定义镜像),Integration(服务集成镜像),Sharing(共享镜像),GpuBccSystem(GPU专用公共镜像),GpuBccCustom(GPU专用自定义镜像),FpgaBccSystem(FPGA专用公共镜像),FpgaBccCustom(FPGA专用自定义镜像),缺省值为All +imageType := "your-imageType" + +args := &api.ListImageArgs{ + Marker: marker, + MaxKeys: maxKeys, + ImageType: imageType, +} + +// 指定过滤查询的自定义镜像名称 +imageName := "your-imageName" + +args := &api.ListImageArgs{ + Marker: marker, + MaxKeys: maxKeys, + ImageType: "Custom", + ImageName: imageName, +} + +if res, err := bccClient.ListImage(args); err != nil { + fmt.Println("get image list failed: ", err) +} else { + fmt.Println("get image list success,res: ", res) +} +``` + +> 具体的镜像类型可详细参考BCC API文档[查询镜像列表](https://cloud.baidu.com/doc/BCC/s/Ajwvynu5r) + +### 查询镜像详情 + +以下代码可以查询镜像详细信息: + +```go +result, err := client.GetImageDetail(imageId) +if err != nil { + fmt.Println("get image detail failed:", err) +} else { + fmt.Println("get image detail success: ", result.Image) +} +``` + +### 删除自定义镜像 +- 该接口用于删除用户自己的指定的自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能删除。 +- imageId 所指定的镜像不存在,提示404错误。 +- 镜像删除后无法恢复,不能再用于创建、重置实例。 + +以下代码可以删除一个自定义镜像: + +```go +err := client.DeleteImage(imageId) +if err != nil { + fmt.Println("delete image failed:", err) +} else { + fmt.Println("delete image success") +} +``` + +### 跨区域复制自定义镜像 +- 用于用户跨区域复制自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能复制 +- regions如北京"bj",广州"gz",苏州"su",可多选: +```go + args := &api.RemoteCopyImageArgs{ + Name: "test2", + DestRegion: []string{"gz"}, + } + err := client.RemoteCopyImage(imageId, args) + if err != nil { + fmt.Println("remote copy image failed:", err) + } else { + fmt.Println("remote copy image success") + } +``` + +### 跨区域复制自定义镜像并返回目的region的镜像镜像id +- 用于用户跨区域复制自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能复制 +- regions如北京"bj",广州"gz",苏州"su",可多选: +```go +args := &api.RemoteCopyImageArgs{ + Name: "test2", + DestRegion: []string{"gz"}, + } +result, err := client.RemoteCopyImageReturnImageIds(imageId, args) + if err != nil { + fmt.Println("remote copy image failed:", err) + } else { + fmt.Println("remote copy image success") + } +``` + +### 取消跨区域复制自定义镜像 + +用于取消跨区域复制自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能复制: + +```go +err := client.CancelRemoteCopyImage(imageId) +if err != nil { + fmt.Println("cancel remote copy image failed:", err) +} else { + fmt.Println("cancel remote copy image success") +} +``` + +### 共享自定义镜像 + +- 该接口用于共享用户自己的指定的自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能共享。 +- imageId 所指定的镜像不存在,提示404错误。 +- 镜像共享后,被共享的用户可以使用此镜像创建、重置实例。 +- 请求参数中的account和accountId均为可选参数,但不能全部为空,当两个参数同时出现时,服务端会自动去重。 + +```go +// 待共享的用户id +accountId := "your-accountId" +//待共享的用户名 +account := "your-account" +// 待共享的镜像ID +imageId := "your-imageId" + +args := &api.SharedUser{ + AccountId: accountId, + Account: account, +} +if err := bccClient.ShareImage(imageId,args); err != nil { + fmt.Println("ShareImage failed: ", err) +} else { + fmt.Println("ShareImage success") +} +``` + +### 取消共享自定义镜像 + +- 该接口用于取消共享用户自己的指定的自定义镜像,仅限自定义镜像,系统镜像和服务集成镜像不能共享。 +- imageId 所指定的镜像不存在,提示404错误。 +- 镜像取消共享后,被取消共享的用户不能再使用此镜像创建、重置实例。 +- 请求参数中的account和accountId均为可选参数,但不能全部为空,当两个参数同时出现时,服务端会自动去重。 + +```go +// 待共享的用户id +accountId := "your-accountId" +//待共享的用户名 +account := "your-account" +// 待共享的镜像ID +imageId := "your-imageId" + +args := &api.SharedUser{ + AccountId: accountId, + Account: account, +} +if err := bccClient.UnShareImage(imageId,args); err != nil { + fmt.Println("UnShareImage failed: ", err) +} else { + fmt.Println("UnShareImage success") +} +``` + +### 查询镜像已共享用户列表 +- mageId 所指定的镜像不存在,提示404错误。 +用于查询镜像已共享的用户列表: + +```go +result, err := client.GetImageSharedUser(imageId) +if err != nil { + fmt.Println("get image shared user list failed: ", err) +} else { + fmt.Println("get image shared user list success: ", result) +} +``` + +### 根据实例ID批量查询OS信息 + +如下代码可以根据实例的ID来查询相应OS的信息 +```go +args := &api.GetImageOsArgs{ + InstanceIds: []string{instanceId}, +} +result, err := client.GetImageOS(args) +if err != nil { + fmt.Println("get image os failed:", err) +} else { + fmt.Println("get image os success: ", result) +} +``` + +### 镜像链绑定标签 +使用以下代码可以给指定镜像绑定标签 +```go + args := &api.BindTagsRequest{ + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, + } + + BCC_CLIENT.BindImageToTags("your-image-id", args) +``` + +### 镜像解绑标签 +使用以下代码可以给指定镜像绑定标签 +```go + args := &api.BindTagsRequest{ + ChangeTags: []model.TagModel{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, + } + + BCC_CLIENT.UnBindImageToTags("your-image-id", args) +``` + +### 导入镜像 +使用以下代码可以导入个镜像 +```go + args := &api.ImportCustomImageArgs{ + OsName: "Centos", + OsArch: "32", + OsType: "linux", + OsVersion: "6.5", + Name: "import_image_test", + BosURL: "http://cloud.baidu.com/testurl", + } + + result, _ := BCC_CLIENT.ImportCustomImage(args) + fmt.Println(result) +``` + +## 快照管理 + +### 创建快照 + +如下代码可以创建一个快照 +```go +args := &api.CreateSnapshotArgs{ + VolumeId: volumeId, + SnapshotName: "sdk", + Description: "create by sdk", +} +result, err := client.CreateSnapshot(args) +if err != nil { + fmt.Println("create snapshot failed:", err) +} else { + fmt.Println("create snapshot success: ", result) +} +``` + +### 查询快照列表 + +如下代码可以查询当前账户下所有快照的列表 +```go +args := &api.ListSnapshotArgs{} +result, err := client.ListSnapshot(args) +if err != nil { + fmt.Println("list all snapshot failed:", err) +} else { + fmt.Println("list all snapshot success: ", result) +} +``` + +### 查询快照详情 + +如下代码可以查询特定快照的详细信息 +```go +result, err := client.GetSnapshotDetail(snapshotId) +if err != nil { + fmt.Println("get snapshot detail failed:", err) +} else { + fmt.Println("get snapshot detail success: ", result) +} +``` + +### 删除快照 + +如下代码可以删除一个快照 +```go +err := client.DeleteSnapshot(snapshotId) +if err != nil { + fmt.Println("delete snapshot failed:", err) +} else { + fmt.Println("delete snapshot success") +} +``` +### 查询快照链列表 +通过以下代码可以查询快照链列表 +```go +// 设置排序属性:chainId(快照链id,默认值),chainSize(快照链大小),volumeSize(磁盘大小)。可选参数 +orderBy := "your-order-by" +// 设置排序方式:asc(正序,默认值), desc(倒序)。可选参数 +order := "your-order" +// 设置每页容量,默认值为1000,可选参数 +pageSize := 100 +// 设置页数,默认为1,可选参数 +pageNo := 1 +// 设置磁盘ID,该字段非空则只返回这个磁盘的快照链信息,可选 +volumeId := "your-volume-id" +args := &api.ListSnapshotChainArgs{ + OrderBy: orderBy, + Order: order, + PageSize: pageSize, + PageNo: pageNo, + VolumeId: volumeId, +} +if res, err := bccClient.ListSnapshotChain(args); err != nil { + fmt.Println("get snapshot chain list failed: ", err) +} else { + fmt.Println("get snapshot chain list success, SnapshotId: ", res.Snapshot.Id) +} +``` + + +### 快照链绑定标签 +使用以下代码可以给指定快照链绑定标签 +```go + tagArgs := &api.TagSnapshotChain{ + ChangeTags: []api.Tag{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, + } + + BCC_CLIENT.TagVolume("your-chain-id", tagArgs) +``` + +### 快照链解绑标签 +使用以下代码可以给指定快照链绑定标签 +```go + tagArgs := &api.TagVolumeArgs{ + ChangeTags: []api.Tag{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, + } + + BCC_CLIENT.UntagSnapshotChain("your-chain-id", tagArgs) +``` + +### 跨区域复制快照 +使用以下代码可以将一份磁盘快照从一个地域复制到其他地域 +```go +args := &api.RemoteCopySnapshotArgs{ + ClientToken: "ClientTokenForTest", + DestRegionInfos: []api.DestRegionInfo{ + { + Name: "NewSnapshotNameInBj", // 快照名称 + DestRegion: "bj", // 目标地域 + }, + { + Name: "NewSnapshotNameInFwh", // 快照名称 + DestRegion: "fwh", // 目标地域 + }, + }, + } + result, _ := BCC_CLIENT.CreateRemoteCopySnapshot("s-S9Hd*****", args) + fmt.Println(result) +``` + +## 自动快照策略管理 + +### 创建自动快照策略 + +如下代码可以创建一个自动快照策略 +```go +args := &api.CreateASPArgs{ + Name: "sdkCreate", + // 设置一天中做快照的时间点,取值为0~23,0为午夜12点 + // 例如设置做快照的时间点为下午两点: + TimePoints: []string{"14"}, + // 设置一周中做快照的时间,取值为0~6,0代表周日,1~6代表周一到周六 + // 例如设置做快照的时间为礼拜五: + RepeatWeekdays: []string{"5"}, + // 设置自动快照保留天数,取-1则永久保留 + RetentionDays: "7", +} +result, err := client.CreateAutoSnapshotPolicy(args) +if err != nil { + fmt.Println("create auto snapshot policy failed:", err) +} else { + fmt.Println("create auto snapshot policy success: ", result) +} +``` + +### 绑定自动快照策略 + +如下代码可以将自动快照策略绑定到某个CDS磁盘 +```go +args := &api.AttachASPArgs{ + // 设置需要绑定的磁盘ID列表 + VolumeIds: []string{volumeId}, +} +err := client.AttachAutoSnapshotPolicy(aspId, args) +if err != nil { + fmt.Println("attach auto snapshot policy with CDS volume failed:", err) +} else { + fmt.Println("attach auto snapshot policy with CDS volume success") +} +``` + +### 解绑自动快照策略 + +如下代码可以将自动快照策略与特定CDS磁盘解除绑定 +```go +args := &api.DetachASPArgs{ + // 设置需要解绑的磁盘ID列表 + VolumeIds: []string{volumeId}, +} +err := client.DetachAutoSnapshotPolicy(aspId, args) +if err != nil { + fmt.Println("detach auto snapshot policy from CDS volume failed:", err) +} else { + fmt.Println("detach auto snapshot policy from CDS volume success") +} +``` + +### 删除自动快照策略 + +如下代码可以删除自动快照策略 +```go +err := client.DeleteAutoSnapshotPolicy(aspId) +if err != nil { + fmt.Println("delete auto snapshot policy failed:", err) +} else { + fmt.Println("delete auto snapshot policy success") +} +``` + +### 查询自动快照策略列表 + +如下代码可以查询到当前账户下当前区域所有自动快照策略的列表 +```go +args := &api.ListASPArgs{} +result, err := client.ListAutoSnapshotPolicy(args) +if err != nil { + fmt.Println("list all auto snapshot policy failed:", err) +} else { + fmt.Println("list all auto snapshot policy success: ", result) +} +``` + +### 查询自动快照策略详情 + +如下代码可以查询到特定自动快照策略的详细信息 +```go +result, err := client.GetAutoSnapshotPolicy(aspId) +if err != nil { + fmt.Println("get auto snapshot policy detail failed:", err) +} else { + fmt.Println("get auto snapshot policy detail success", result) +} +``` + +### 自动快照策略变更 + +如下代码可以更新一个自动快照策略 +```go +args := &api.UpdateASPArgs{ + Name: "testUpdate", + TimePoints: []string{"10"}, + RepeatWeekdays: []string{"0", "1", "7"}, + RetentionDays: "2", + AspId: aspId, +} +err := client.UpdateAutoSnapshotPolicy(args) +if err != nil { + fmt.Println("update auto snapshot policy failed:", err) +} else { + fmt.Println("update auto snapshot policy success") +} +``` + + +## 安全组管理 + +### 查询安全组列表 + + 以下代码可以查询安全组列表: + +```go +args := &api.ListSecurityGroupArgs{} + +// 设置筛选的实例Bcc实例id +args.InstanceId = instanceId + +// 设置筛选的安全组绑定的VPC实例ID +args.VpcId = vpcId + +result, err := client.ListSecurityGroup(args) +if err != nil { + fmt.Println("list all security group failed:", err) +} else { + fmt.Println("list all security group success: ", result) +} +``` + +### 创建安全组 + +以下代码可以创建一个安全组: + +```go +args := &api.CreateSecurityGroupArgs{ + // 设置安全组名称 + Name: "sdk-create", + // 设置安全组规则 + Rules: []api.SecurityGroupRuleModel{ + { + // 设置安全组规则备注 + Remark: "备注", + // 设置协议类型 + Protocol: "tcp", + // 设置端口范围,默认空时为1-65535,可以指定80等单个端口 + PortRange: "1-65535", + // 设置入站出站,取值ingress/egress + Direction: "ingress", + // 设置源IP地址,与sourceGroupId不能同时设置 + SourceIp: "", + }, + }, +} +result, err := client.CreateSecurityGroup(args) +if err != nil { + fmt.Println("create security group failed:", err) +} else { + fmt.Println("create security group success: ", result) +} +``` + +> 同一安全组中的规则以remark、protocol、direction、portRange、sourceIp|destIp、sourceGroupId|destGroupId唯一性索引,重复记录报409错误。 +> protocol的取值(tcp|udp|icmp),默认值为空,代表all。 +> 具体的创建安全组规则接口描述BCC API 文档[创建安全组](https://cloud.baidu.com/doc/BCC/s/0jwvynwij)。 + +### 删除安全组 + +以下代码可以删除指定的安全组: + +```go +err := client.DeleteSecurityGroup(securityGroupId) +if err != nil { + fmt.Println("delete security group failed:", err) +} else { + fmt.Println("delete security group success") +} +``` + +### 授权安全组规则 + +使用以下代码可以在指定安全组中添加授权安全组规则: + +```go +args := &api.AuthorizeSecurityGroupArgs{ + Rule: &api.SecurityGroupRuleModel{ + Remark: "备注", + Protocol: "udp", + PortRange: "1-65535", + Direction: "ingress", + }, +} +err := client.AuthorizeSecurityGroupRule(securityGroupId, args) +if err != nil { + fmt.Println("authorize security group new rule failed:", err) +} else { + fmt.Println("authorize security group new rule success") +} +``` + +> - 同一安全组中的规则以remark、protocol、direction、portRange、sourceIp|destIp、sourceGroupId|destGroupId六元组作为唯一性索引,若安全组中已存在相同的规则将报409错误。 +> - 具体的接口描述BCC API 文档[授权安全组规则](https://cloud.baidu.com/doc/BCC/s/pjwvynxvl)。 + +### 撤销安全组规则 + +使用以下代码可以在指定安全组中撤销指定安全组规则授权: + +```go +args := &api.RevokeSecurityGroupArgs{ + Rule: &api.SecurityGroupRuleModel{ + Remark: "备注", + Protocol: "udp", + PortRange: "1-65535", + Direction: "ingress", + SourceIp: "", + }, +} +err := client.RevokeSecurityGroupRule(securityGroupId, args) +if err != nil { + fmt.Println("revoke security group rule failed:", err) +} else { + fmt.Println("revoke security group rule success") +} +``` + +> - 同一安全组中的规则以remark、protocol、direction、portRange、sourceIp|destIp、sourceGroupId|destGroupId六元组作为唯一性索引,若安全组中不存在对应的规则将报404错误。 +> - 具体的接口描述BCC API 文档[撤销安全组规则](https://cloud.baidu.com/doc/BCC/s/yjwvynxk0)。 + +### 更新普通安全组规则 + +使用以下代码可以在指定普通安全组中更新安全组规则: + +```go +args := &api.UpdateSecurityGroupRuleArgs{ + SecurityGroupRuleId: SecurityGroupRuleId, + Remark: Remark, +} +err := client.UpdateSecurityGroupRule(args) +if err != nil { + fmt.Println("update security group new rule failed:", err) +} else { + fmt.Println("update security group new rule success") +} +``` + +### 删除普通安全组规则 + +使用以下代码可以在指定普通安全组中删除指定安全组规则: + +```go +args := &api.DeleteSecurityGroupRuleArgs{ + SecurityGroupRuleId: SecurityGroupRuleId, +} +err := client.DeleteSecurityGroupRule(args) +if err != nil { + fmt.Println("delete security group rule failed:", err) +} else { + fmt.Println("delete security group rule success") +} +``` + +## 部署集 +### 创建部署集 + +通过以下代码可以根据指定的部署集策略创建部署集 + +```go +// 设置创建部署集的名称 +deploySetName := "your-deploy-set-name" +// 设置创建的部署集的描述信息 +deployDesc := "your-deploy-set-desc" +// 设置创建部署集的策略,BBC实例策略只支持:"tor_ha" +strategy := "tor_ha" +queryArgs := &CreateDeploySetArgs{ + Strategy: strategy, + Name: deploySetName, + Desc: deployDesc, +} +if res, err := bccClient.CreateDeploySet(queryArgs); err != nil { + fmt.Println("Create deploy set failed: ", err) +} else { + fmt.Println("Create deploy set success, result: ", res) +} +``` + +### 查询部署集列表 + +通过以下代码可以查询所有部署集实例的列表及详情信息 + +```go +if res, err := bccClient.ListDeploySets(); err != nil { + fmt.Println("List deploy sets failed: ", err) +} else { + fmt.Println("List deploy sets success, result: ", res) +} +``` +### 修改部署集属性 + +使用以下代码可以修改指定部署集的属性值 + +```go + // 设置创建部署集的名称 + testDeploySetName := "testName" + // 设置创建的部署集的描述信息 + testDeployDesc := "goDesc" + queryArgs := &api.ModifyDeploySetArgs{ + Name: testDeploySetName, + Desc: testDeployDesc, + } + BCC_TestDeploySetId = "DeploySetId" + rep, err := BCC_CLIENT.ModifyDeploySet(BCC_TestDeploySetId, queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +``` + +### 删除指定的部署集 + +使用以下代码删除用户自己的指定的部署集 + +```go +// 设置你要删除的deploySetID +deploySetID := "your-choose-deploy-set-id" +if err := bccClient.DeleteDeploySet(deploySetID); err != nil { + fmt.Println("Delete deploy set failed: ", err) +} +``` + +### 绑定指定的部署集 + +使用以下代码白能搞定用户自己指定的部署集 + +```go + queryArgs := &api.UpdateInstanceDeployArgs{ + // 设置你要绑定的InstanceId + InstanceId: "InstanceId", + // 设置你要绑定的DeploySetIds + DeploySetIds: []string{"DeploySetId"}, + } + rep, err := BCC_CLIENT.UpdateInstanceDeploySet(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +``` + +### 解绑指定的部署集 + +使用以下代码解绑用户自己指定的部署集 + +```go + queryArgs := &api.DelInstanceDeployArgs{ + // 设置你要解绑的DeploySetId + DeploySetId: "DeploySetId", + // 设置你要解绑的InstanceIds + InstanceIds: []string{"InstanceId"}, + } + rep, err := BCC_CLIENT.DelInstanceDeploySet(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +``` + +## 密钥对接口 +### 创建密钥对 + +该接口用于创建密钥对,创建后的密钥对可植入实例以实现远程登录虚机。 + +```go +// 待创建的密钥对名称 +name := "your-keypair-name" +// 待创建的密钥对的描述,可选参数 +description := "your-keypair-desc" +args := &api.CreateKeypairArgs{ + Name: name, + Description: description, +} +if res, err := bccClient.CreateKeypair(args); err != nil { + fmt.Println("create keypair failed: ", err) +} else { + fmt.Println("create keypair success,res: ", res) +} +``` + +### 导入密钥对 + +该接口用于用户自行导入创建密钥对。 + +```go +// 待创建的密钥对名称 +name := "your-keypair-name" +// 待创建的密钥对的描述,可选参数 +description := "your-keypair-desc" +publicKey := "your-publickey" +args := &api.ImportKeypairArgs{ + Name: name, + Description: description, + PublicKey: publicKey, +} +if res, err := bccClient.ImportKeypair(args); err != nil { + fmt.Println("create keypair failed: ", err) +} else { + fmt.Println("create keypair success,res: ", res) +} +``` + +### 绑定密钥对 + +该接口用于将所选密钥对(限单个)绑定到所选虚机(支持多台)。 目前一台虚机只能绑定一个密钥对,若操作的虚机已经绑定密钥对,则此操作将替换该虚机原有的密钥对。此操作仅适用于linux系统的虚机,且所选虚机必须处于运行中或关机状态。 + +```go +instanceIds := []string{"your-instanceId"} +keypairId:= "your-keypair-id" +args := &api.AttackKeypairArgs{ + InstanceIds: instanceIds, + KeypairId: keypairId, +} +if err := bccClient.AttachKeypair(args); err != nil { + fmt.Println("attach keypair failed: ", err) +} else { + fmt.Println("attach keypair success") +} +``` + +### 解绑密钥对 + +该接口用于将所选虚机与它们各自绑定的密钥对解绑。 目前一台虚机只能绑定一个密钥对,此操作将使所选虚机与其通过百度云控制台操作所绑定的密钥对解绑,若该虚机不存在这种密钥对,则不进行处理。 此操作仅适用于linux系统的虚机,且所选虚机必须处于运行中或关机状态。 +注: 1)用户所选虚机可能并未绑定任何密钥对,则此操作对该虚机无任何作用; 2)用户可能对所选虚机手动绑定了密钥对,则此操作对其手动绑定的密钥对不产生任何影响; 3)用户如若此前通过百度云控制台操作,为所选虚机绑定过密钥对,且该密钥对状态正常,则此操作将从该虚机中删除该密钥对 +```go +instanceIds := []string{"your-instanceId"} +keypairId:= "your-keypair-id" +args := &api.DetachKeypairArgs{ + InstanceIds: instanceIds, + KeypairId: keypairId, +} +if err := bccClient.DetachKeypair(args); err != nil { + fmt.Println("detach keypair failed: ", err) +} else { + fmt.Println("detach keypair success") +} +``` + +### 删除密钥对 + +该接口用于删除密钥对,已经绑定虚机的密钥对无法被删除。 +```go +keypairId:= "your-keypair-id" +args := &api.DetachKeypairArgs{ + KeypairId: keypairId, +} +if err := bccClient.DeleteKeypair(args); err != nil { + fmt.Println("detach keypair failed: ", err) +} else { + fmt.Println("detach keypair success") +} +``` + +### 查询密钥对详情 + +该接口用于查询单个密钥对的详细信息。 +```go +keypairId:= "your-keypair-id" +if res, err := bccClient.GetKeypairDetail(keypairId); err != nil { + fmt.Println("get keypair failed: ", err) +} else { + fmt.Println("get keypair success,res: ", res) +} +``` + +### 查询密钥对列表 + +该接口用于查询密钥对列表。 +```go +// 批量获取列表的查询的起始位置,是一个由系统生成的字符串,可选参数 +marker := "your-marker" +// 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000,可选参数 +maxKeys := your-maxKeys +// 根据name过滤keypair列表,返回精确匹配结果 +name := "your-keyPairName" + +args := &api.ListKeypairArgs{ + Marker marker, + MaxKeys maxKeys, + Name name, +} +if res, err := bccClient.ListKeypair(args); err != nil { + fmt.Println("get keypair list failed: ", err) +} else { + fmt.Println("get keypair list success,res: ", res) +} +``` + +### 重命名密钥对 + +该接口用于重命名密钥对。 +```go +name := "your-keypair-name" +keypairId:= "your-keypair-id" +args := &api.RenameKeypairArgs{ + Name: name, + KeypairId: keypairId, +} +if err := bccClient.RenameKeypair(args); err != nil { + fmt.Println("update keypair name failed: ", err) +} else { + fmt.Println("update keypair name success") +} +``` + +### 更改密钥对描述 + +该接口用于更改密钥对描述,若用户提供的新的描述内容为空,则删除所操作虚机的描述。 +```go +description := "your-keypair-desc" +keypairId:= "your-keypair-id" +args := &api.KeypairUpdateDescArgs{ + Description: description, + KeypairId: keypairId, +} +if err := bccClient.UpdateKeypairDescription(args); err != nil { + fmt.Println("create keypair failed: ", err) +} else { + fmt.Println("update keypair desc success") +} +``` + +## 其他接口 +### 查询实例套餐规格 + +如下代码可以查询当前可以创建的实例的套餐的规格 +```go +result, err := client.ListSpec() +if err != nil { + fmt.Println("list specs failed: ", err) +``` + +### 查询实例套餐规格(新) + +通过以下代码可以查询实例资源套餐规格列表信息 +```go +// 设置可用区名称,可选 +zoneName := "your-zone-name" +args := &api.ListFlavorSpecArgs{ + ZoneName: zoneName, +} +if res, err := bccClient.ListFlavorSpec(args); err != nil { + fmt.Println("Get specified flavor list failed: ", err) +} else { + fmt.Println("Get specified flavor list success, result: ", res) +} +``` +>- 创建虚机时建议使用参数(spec)指定需要的机型以及配置。 + +### 查询实例套餐价格 +通过以下代码可以查询实例资源套餐规格对应的价格 +```go +// 设置实例规格族 +specId := "your-spec-id" +// 设置实例套餐规格 +spec := "your-spec" +// 设置付费方式,包括Postpaid(后付费),Prepaid(预付费)两种 +paymentTiming := "your-payment-timing" +// 设置可用区名称 +zoneName := "your-zone-name" +// 设置所要购买的实例数量,缺省值为1,可选参数 +purchaseCount := 1 +// 设置时长,[1,2,3,4,5,6,7,8,9,12,24,36],单位:月 +reservationLength := 9 +args := &api.GetPriceBySpecArgs{ + SpecId: specId, + Spec: spec, + PaymentTiming: paymentTiming, + ZoneName: zoneName, + PurchaseCount: purchaseCount, + PurchaseLength: reservationLength, +} +if res, err := bccClient.GetPriceBySpec(args); err != nil { + fmt.Println("Get specified instance's price failed: ", err) +} else { + fmt.Println("Get specified intstance's price success, result: ", res) +} +``` + +### 查询机型的可用区 + +使用以下代码可以查询指定机型支持的可用区列表 +```go +args := &api.ListTypeZonesArgs{ + InstanceType: "", + ProductType: "", + Spec: "bcc.g3.c2m12", + SpecId: "", +} +if res, err := BCC_CLIENT.ListTypeZones(args); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) +} else { + fmt.Println("Get the specific zone flavor success, result: ", res) +} +``` + +### 查询可用区列表 + +如下代码可以所有的可用区的列表 +```go +result, err := client.ListZone() +if err != nil { + fmt.Println("list zone failed: ", err) +} else { + fmt.Println("list zone success: ", result) +} +``` + +### 查询机型的可用区 + +使用以下代码可以查询指定机型支持的可用区列表 +```go +args := &api.ListTypeZonesArgs{ + // 选择实例类型,可以选择N1, N2, N3等 + InstanceType: "", + // 产品类型, 可以选择Prepaid,Postpaid + ProductType: "", + // 实例套餐规格,可以选择bcc.g3.c2m12等 + Spec: "", + // 实例套餐规格族,可以选择g3,ic4等 + SpecId: "", +} +if res, err := BCC_CLIENT.ListTypeZones(args); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) +} else { + fmt.Println("Get the specific zone flavor success, result: ", res) +} +``` + +### 查询bcc、bbc套餐库存 +同时查询bcc、bbc套餐的最大库存。 +只查询用户在console界面上可见的套餐库存。 +查询时需要用户开启查询库存白名单。 +```go +if res, err := BCC_CLIENT.GetAllStocks(); err != nil { + fmt.Println("get all stocks failed: ", err) +} else { + fmt.Println("get all stocks success, result: ", res) +} +``` + +### 部署集粒度实例套餐库存 +查询部署集粒度的实例套餐库存 +```go +// 套餐规格(不需要传本地盘参数,自动解析) +spec := "bcc.l3.c32m128" +// 部署集短id,最多传两个短id(目前一个bcc实例最多绑定两个部署集) +deploySetIds := []string{"dset-12345678"} +args := &api.GetStockWithDeploySetArgs{ + Spec: spec, + DeploySetIds: deploySetIds, +} +if res, err := bccClient.GetStockWithDeploySet(args); err != nil { + fmt.Println("GetStockWithDeploySet failed: ", err) +} else { + fmt.Println("GetStockWithDeploySet success: ", res) +} +``` + +### 通过spec查询实例套餐库存 +通过spec查询实例套餐库存 +```go +// 套餐规格(不需要传本地盘参数,自动解析) +spec := "bcc.l3.c32m128" +// 部署集短id,最多传两个短id,可选参数(目前一个bcc实例最多绑定两个部署集) +deploySetIds := []string{"dset-12345678"} +args := &api.GetStockWithSpecArgs{ + Spec: spec, + DeploySetIds: deploySetIds, +} +if res, err := bccClient.GetStockWithSpec(args); err != nil { + fmt.Println("GetStockWithSpec failed: ", err) +} else { + fmt.Println("GetStockWithSpec success: ", res) +} +``` + +### 查询实例套餐库存 +查询实例资源套餐规格对应的库存。 +```go +// 实例类型 +instanceType := "instanceType" +// CPU核数 +cpuCount := cpuCount +// 内存容量(GB) +memoryCapacityInGB := memoryCapacityInGB +// 可用区名称 +zoneName := "zoneNamen" +// GPU卡类型,GPU和VGPU可填 +gpuCard := "gpuCard" +// GPU卡数量,GPU和VGPU可填 +cardCount := "cardCount" +//本地盘信息 +ephemeralDisks := []EphemeralDisks{{ + "storageType": "ssd", + "sizeInGB": sizeInGB, +}} + +args := &api.CreateInstanceStockArgs{ + InstanceType: instanceType, + CpuCount: cpuCount, + MemoryCapacityInGB: memoryCapacityInGB, + ZoneName: zoneName, + GpuCard: gpuCard, + CardCount: cardCount, + EphemeralDisks: ephemeralDisks, +} +if res, err := bccClient.GetInstanceCreateStock(args); err != nil { + fmt.Println("GetInstanceCreateStock failed: ", err) +} else { + fmt.Println("GetInstanceCreateStock success: ", res) +} +``` + + +### 实例扩缩容库存查询 +实例变配余量查询 +```go +// 实例id +instanceId := "instanceId" +// CPU核数 +cpuCount := cpuCount +// 内存容量(GB) +memoryCapacityInGB := memoryCapacityInGB + +args := &api.CreateInstanceStockArgs{ + InstanceId: instanceId, + CpuCount: cpuCount, + MemoryCapacityInGB: memoryCapacityInGB, +} +if res, err := bccClient.ResizeInstanceStockArgs(args); err != nil { + fmt.Println("ResizeInstanceStockArgs failed: ", err) +} else { + fmt.Println("ResizeInstanceStockArgs success: ", res) +} +``` + +## 磁盘专属集群 +### 创建磁盘专属集群 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &CreateVolumeClusterArgs{ + // 创建一个磁盘磁盘专属集群,若要同时创建多个,可以修改此参数 + PurchaseCount: 1, + // 集群大小,支持最小容量:85TB(87040GB),支持最大容量:1015TB(1039360GB),购买步长:10TB + ClusterSizeInGB: 97280, + // 集群名称 + ClusterName: "dbsc", + // 集群磁盘类型:通用型HDD,通用型SSD + StorageType: StorageTypeHdd, + Billing: &Billing{ + // 只支持预付费 + Reservation: &Reservation{ + // 购买时长 + ReservationLength: 6, + ReservationTimeUnit: "MONTH", + }, + }, + // 自动续费时长 + RenewTimeUnit: "MONTH", + RenewTime: 6, +} +result, err := DBSC_CLIENT.CreateVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +clusterId := result.ClusterIds[0] +fmt.Print(clusterId) +``` + +### 磁盘专属集群列表 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &ListVolumeClusterArgs{ +} +result, err := DBSC_CLIENT.ListVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +fmt.Println(result) +``` + +### 磁盘专属集群详情 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +result, err := DBSC_CLIENT.GetVolumeClusterDetail(clusterId) +if err != nil { + fmt.Println(err) +} +fmt.Println(result) +``` + +### 磁盘专属集群扩容 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +args := &ResizeVolumeClusterArgs{ + NewClusterSizeInGB int `json:"newClusterSizeInGB"` +} +err := DBSC_CLIENT.ResizeVolumeCluster(clusterId, args) +if err != nil { + fmt.Println(err) +} +``` + +### 磁盘专属集群续费 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &PurchaseReservedVolumeClusterArgs{ + Billing: &Billing{ + Reservation: &Reservation{ + // 续费时长 + ReservationLength: 6, + ReservationTimeUnit: "MONTH", + }, + }, +} +clusterId := "clusterId" +err := DBSC_CLIENT.PurchaseReservedVolumeCluster(clusterId, args) +if err != nil { + fmt.Println(err) +} +``` + +### 磁盘专属集群自动续费 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +args := &AutoRenewVolumeClusterArgs{ + ClusterId: clusterId, + RenewTime: 6, + RenewTimeUnit: "month", +} +err := DBSC_CLIENT.AutoRenewVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +``` + +### 磁盘专属集群取消自动续费 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +args := &CancelAutoRenewVolumeClusterArgs{ + ClusterId: clusterId, +} +err := DBSC_CLIENT.CancelAutoRenewVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +``` + + +# 错误处理 + +GO语言以error类型标识错误,BCC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | BCC服务返回的错误 + +用户使用SDK调用BCC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// bccClient 为已创建的BCC Client对象 +instanceDetail, err := bccClient.GetInstanceDetail(instanceId) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get instance detail success: ", instanceDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向BCC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当BCC服务端出现异常时,BCC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BCC错误返回](https://cloud.baidu.com/doc/BCC/s/Ojwvyo6nc) + +# 版本变更记录 + +## v0.9.1 [2019-09-26] + +首次发布: + + - 创建、查看、列表、启动、停止、重启、重装、删除实例,修改实例密码、安全组、属性、子网等,为实例续费 + - 创建、查看、列表、挂载、卸载、扩容、回滚、重命名、删除CDS磁盘,为磁盘续费,修改磁盘属性和计费方式等 + - 创建、查看、列表、删除、跨区域复制、取消跨区域复制、共享、取消共享镜像,删除自定义镜像,查询已共享的用户列表及根据实例ID查询OS信息等 + - 创建、查看、列表、删除快照 + - 创建、查看、列表、绑定、解绑、变更、删除自动快照策略 + - 创建、查询、删除安全组,为安全组授权和撤销规则 + - 查询实例套餐规格和查询可用区列表 diff --git a/bce-sdk-go/doc/BCI.md b/bce-sdk-go/doc/BCI.md new file mode 100644 index 0000000..cbfde40 --- /dev/null +++ b/bce-sdk-go/doc/BCI.md @@ -0,0 +1,565 @@ +# BCI服务 + +# 概述 + +本文档主要介绍BCI GO SDK的使用。在使用本文档前,您需要先了解BCI的一些基本知识,并已开通了BCI服务。若您还不了解BCI,可以参考[产品描述](https://cloud.baidu.com/doc/BCI/s/Ujxessavb)和[操作指南](https://cloud.baidu.com/doc/BCI/s/elc8ri0af)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BCI服务域名](https://cloud.baidu.com/doc/BCI/s/Qlf0qoqw1)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”和“华北-保定”四个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BD | bci.bd.baidubce.com | HTTP and HTTPS +GZ | bci.gz.baidubce.com | HTTP and HTTPS +SU | bci.su.baidubce.com | HTTP and HTTPS +BD | bci.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云BCI,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BCI做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BCI Client + +BCI Client是BCI服务的客户端,为开发者与BCI服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BCI Client + +通过AK/SK方式访问BCI,用户可以参考如下代码新建一个BCI Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bci" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BCIClient + bciClient, err := bci.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BCI的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bci.bj.baidubce.com`。 + +### 使用STS创建BCI Client + +**申请STS token** + +BCI可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BCI,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建BCI Client** + +申请好STS后,可将STS Token配置到BCI Client中,从而实现通过STS Token创建BCI Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BCI Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/bci" //导入BCI服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BCI服务的Client对象,Endpoint使用默认值 + bciClient, err := bci.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bci.bj.baidubce.com") + if err != nil { + fmt.Println("create bci client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + bciClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BCI Client时,无论对应BCI服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问BCI + +BCI支持HTTPS传输协议,您可以通过在创建BCI Client对象时指定的Endpoint中指明HTTPS的方式,在BCI GO SDK中使用HTTPS访问BCI服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +ENDPOINT := "https://bci.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +bciClient, _ := bci.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BCI Client + +如果用户需要配置BCI Client的一些细节的参数,可以在创建BCI Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BCI服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +//创建BCI Client对象 +AK, SK := , +ENDPOINT := "bci.bj.baidubce.com" +client, _ := bci.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +AK, SK := , +ENDPOINT := "bci.bj.baidubce.com" +client, _ := bci.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +AK, SK := , +ENDPOINT := "bci.bj.baidubce.com" +client, _ := bci.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BCI时,创建的BCI Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BCI Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +百度智能云容器实例(Baidu Container Instance,即BCI)提供无服务器化的容器资源。您只需提供容器镜像及启动容器所需的配置参数,即可运行容器,而无需关心这些容器如何被调度部署到底层的物理服务器资源中。BCI服务将为您完成IaaS层资源的调度和运维工作,从而简化您对容器的使用流程,降低部署和维护成本。同时BCI只会对您创建容器时申请的资源计费,因此实现真正的按需付费。结合容器本身秒级启动的特性,BCI可以帮助您在百度智能云上构建灵活弹性且易于维护的大规模容器集群。 + +> 注意: +> - BCI使用限制可以参考[BCI使用限制](https://cloud.baidu.com/doc/BCI/s/jjxv2cma2)。 +> - 创建BCI需要实名认证,若未通过实名认证可以前往[百度智能云官网控制台](https://console.bce.baidu.com/qualify/#/qualify/result)中的安全认证下的实名认证中进行认证。 + +## 创建实例 + +使用以下代码可以创建一个BCI实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +args := &CreateInstanceArgs{ + // 保证请求幂等性 + ClientToken: "random-uuid", + // BCI实例名称 + Name: "instanceName", + // 可用区名称 + ZoneName: "zoneC", + // 实例所属于的安全组Id + SecurityGroupIds: []string{"g-59gf44p4jmwe"}, + // 实例所属的子网Id + SubnetIds: []string{"sbn-g463qx0aqu7q"}, + // 实例重启策略 + RestartPolicy: "Always", + // 弹性公网IP + EipIp: "106.13.234.xx", + // 自动创建EIP + AutoCreateEip: false, + // 弹性公网名称 + EipName: "zwj-test-eip", + // EIP线路类型 + EipRouteType: "BGP", + // 公网带宽,单位为Mbps + EipBandwidthInMbps: 1, + // 计费方式 + EipBillingMethod: "ByTraffic", + // 实例所需的 GPU 资源型号 + GPUType: "Nvidia A10 PCIE", + // 程序的缓冲时间,用于处理关闭之前的操作 + TerminationGracePeriodSeconds: 0, + // 主机名称 + HostName: "zwj-go-sdktest", + // 用户标签列表 + Tags: []Tag{ + { + TagKey: "appName", + TagValue: "zwj-test", + }, + }, + // 镜像仓库凭证信息 + ImageRegistryCredentials: []ImageRegistryCredential{ + { + Server: "docker.io/wywcoder", + UserName: "wywcoder", + Password: "Qaz123456", + }, + }, + // 业务容器组 + Containers: []Container{ + { + Name: "container01", + Image: "registry.baidubce.com/bci-zjm-public/ubuntu:18.04", + Memory: 0.5, + CPU: 0.25, + GPU: 0, + WorkingDir: "", + ImagePullPolicy: "IfNotPresent", + Commands: []string{"/bin/sh"}, + Args: []string{"-c", "sleep 30000 && exit 0"}, + VolumeMounts: []VolumeMount{ + { + MountPath: "/usr/local/nfs", + ReadOnly: false, + Name: "nfs", + Type: "NFS", + }, + { + MountPath: "/usr/local/share", + ReadOnly: false, + Name: "emptydir", + Type: "EmptyDir", + }, + { + MountPath: "/config", + ReadOnly: false, + Name: "configfile", + Type: "ConfigFile", + }, + }, + Ports: []Port{ + { + Port: 8099, + Protocol: "TCP", + }, + }, + EnvironmentVars: []Environment{ + { + Key: "java", + Value: "/usr/local/jre", + }, + }, + LivenessProbe: &Probe{ + InitialDelaySeconds: 0, + TimeoutSeconds: 0, + PeriodSeconds: 0, + SuccessThreshold: 0, + FailureThreshold: 0, + TerminationGracePeriodSeconds: 0, + Exec: &ExecAction{ + Command: []string{"echo 0"}, + }, + }, + Stdin: false, + StdinOnce: false, + Tty: false, + SecurityContext: &ContainerSecurityContext{}, + }, + }, + // Init 容器 + InitContainers: []Container{}, + // 数据卷信息 + Volume: &Volume{ + Nfs: []NfsVolume{ + { + Name: "nfs", + Server: "xxx.cfs.gz.baidubce.com", + Path: "/", + }, + }, + EmptyDir: []EmptyDirVolume{ + { + Name: "emptydir", + }, + }, + ConfigFile: []ConfigFileVolume{ + { + Name: "configfile", + ConfigFiles: []ConfigFileDetail{ + { + Path: "podconfig", + File: "filenxx", + }, + }, + }, + }, + }, +} +result, err := client.CreateInstance(args) +if err != nil { + fmt.Printf("CreateInstance error: %+v \n", err) + return +} +fmt.Printf("CreateInstance success, bci instance id: %+v \n", result.InstanceId) +``` + +> 注意: +> - 保证请求幂等性。从您的客户端生成一个参数值,确保不同请求间该参数值唯一。只支持ASCII字符,且不能超过64个字符。 +> - BCI实例名称,即容器组名称;支持长度为2~253个英文小写字母、数字或者连字符(-),不能以连接字符开始或结尾。如果填写大写字母,后台会自动转为小写。 +> - 实例重启策略。取值范围:Always:总是重启,Never:从不重启,OnFailure:失败时重启。默认值:Always。 +> - 自动创建EIP,并绑定到BCI实例上。只有当eipIp为空的情况下,此字段才生效。默认值为:false。 +> - EIP线路类型,包含标准BGP(BGP)和增强BGP(BGP_S),默认标准BGP。当autoCreateEip为true时,此字段才生效。默认值为:BGP。 +> - 公网带宽,单位为Mbps。对于预付费以及按使用带宽计费的后付费EIP,标准型BGP限制为1~500之间的整数,增强型BGP限制为100~5000之间的整数(代表带宽上限);对于按使用流量计费的后付费EIP,标准型BGP限制为1~200之间的整数(代表允许的带宽流量峰值)。如果填写浮点数会向下取整。当autoCreateEip为true时,此字段才生效。默认值为100。 +> - 付款时间,预支付(Prepaid)和后支付(Postpaid)当autoCreateEip为true时,此字段才生效。默认值为Postpaid。 +> - 计费方式,按流量(ByTraffic)、按带宽(ByBandwidth)、按增强95(ByPeak95)(只有共享带宽后付费支持)。当autoCreateEip为true时,此字段才生效。增强型BGP_S不支持按流量计费(ByTraffic),需要按带宽计费(ByBandwidth)。默认值为ByTraffic。 +> - 支持创建 EIP同时开通自动续费单位,取值为 month 获 year (默认 month)。当autoCreateEip为true时,此字段才生效。默认值为month。 +> - 支持创建 EIP同时开通自动续费时间。根据autoRenewTimeUnit的取值有不同的范围,month 为1到9,year 为1到3。当autoCreateEip为true时,此字段才生效。默认值为1。 +> - 实例所需的 GPU 资源型号。目前仅支持:Nvidia A10 PCIE。 + +## 查询实例列表 + +使用以下代码可以查询BCI实例列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +args := &ListInstanceArgs{ + // 查询关键字名称 + KeywordType: "podId", + // 查询关键字值 + keyword: "p-xxx", + // 表示下一个查询开始的marker,marker为空表示没有下一个 + Marker: "", + // 每页包含的最大数量 + MaxKeys: 5, +} +result, err := client.ListInstances(args) +fmt.Printf("ListInstances result: %+v, err: %+v \n", result, err) +``` + +> 注意: +> - 查询关键字名称,取值范围:name、podId。 +> - 表示下一个查询开始的marker,marker为空表示没有下一个。说明:首次查询时无需设置该参数,后续查询的marker从返回结果中获取。 +> - 每页包含的最大数量,最大数量通常不超过1000,缺省值为10。maxKeys的取值范围:[1, 1000]之间的正整数。 + +## 查询实例详情 + +使用以下代码可以查询BCI实例详情。 +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +args := &GetInstanceArgs{ + // BCI实例ID + InstanceId: "p-xxx", +} +result, err := client.GetInstance(args) +fmt.Printf("ListInstances result: %+v, err: %+v \n", result, err) +``` + +## 删除实例 + +使用以下代码可以删除BCI实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +args := &DeleteInstanceArgs{ + // 待删除的BCI实例ID + InstanceId: "p-xxxx", + // 释放关联资源 + RelatedReleaseFlag: true, +} +err := client.DeleteInstance(args) +fmt.Printf("DeleteInstance err: %+v\n", err) +``` + +> 注意: +> - 释放关联资源,目前只有EIP资源,默认值为false。 + +## 批量删除实例 + +使用以下代码可以批量删除BCI实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/bci" + +args := &BatchDeleteInstanceArgs{ + // 待删除的BCI实例ID列表 + InstanceIds: []string{"p-axxx", "p-bxxx"}, + // 释放关联资源 + RelatedReleaseFlag: true, +} +err := client.BatchDeleteInstance(args) +fmt.Printf("BatchDeleteInstance err: %+v\n", err) +``` + +> 注意: +> - 释放关联资源,目前只有EIP资源,默认值为false。 + +# 错误处理 + +GO语言以error类型标识错误,BCI支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | BCI服务返回的错误 + +用户使用SDK调用BCI相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` go +// client 为已创建的BCI Client对象 +args := &bci.ListInstanceArgs{} +result, err := client.ListInstances(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向BCI发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当BCI服务端出现异常时,BCI服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BCI错误码](https://cloud.baidu.com/doc/BCI/s/Vlf18flyw) + +## SDK日志 + +BCI GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +BCI GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +```go +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +```go +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the BCI go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the BCI go sdk") +``` + + +# 版本变更记录 + +首次发布: + + - 支持创建实例、查询实例列表、查询实例详情、删除实例、批量删除实例接口。 \ No newline at end of file diff --git a/bce-sdk-go/doc/BCM.md b/bce-sdk-go/doc/BCM.md new file mode 100644 index 0000000..b5d5ddd --- /dev/null +++ b/bce-sdk-go/doc/BCM.md @@ -0,0 +1,289 @@ +# BCM服务 + +# 概述 + +本文档主要介绍BCM GO SDK的使用。在使用本文档前,您需要先了解 +[BCM的基本知识](https://cloud.baidu.com/doc/BCM/index.html)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BCM域名](https://cloud.baidu.com/doc/BCM/s/5jwvym49g)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云BCM,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BCM做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BCM Client + +BCM Client是BCM控制面服务的客户端,为开发者与BCM控制面服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BCM Client + +通过AK/SK方式访问BCM,用户可以参考如下代码新建一个BCM Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bcm" //导入BCM服务模块 +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BcmClient + bcmClient, err := bcm.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BCM/index.html)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BCM的控制面服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcm.bj.baidubce.com`。 + +### 使用STS创建BCM Client + +**申请STS token** + +BCM可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BCM,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建BCM Client** + +申请好STS后,可将STS Token配置到BCM Client中,从而实现通过STS Token创建BCM Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BCM Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/bcm" //导入BCM服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BCM控制面服务的Client对象,Endpoint使用默认值 + bcmClient, err := bcm.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create bcm client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + bcmClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BCM Client时,无论对应BCM服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问BCM + +BCM支持HTTPS传输协议,您可以通过在创建BCM Client对象时指定的Endpoint中指明HTTPS的方式,在BCM GO SDK中使用HTTPS访问BCM服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcm" + +ENDPOINT := "https://bcm.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +bcmClient, _ := bcm.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BCM Client + +如果用户需要配置BCM Client的一些细节的参数,可以在创建BCM Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BCM服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcm" + +//创建BCM Client对象 +AK, SK := , +ENDPOINT := "bcm.bj.baidubce.com +client, _ := bcm.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcm" + +AK, SK := , +ENDPOINT := "bcm.bj.baidubce.com" +client, _ := bcm.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bcm" + +AK, SK := , +ENDPOINT := "bcm.bj.baidubce.com" +client, _ := bcm.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BCM时,创建的BCM Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BCM Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +云监控BCM(Cloud Monitor),是针对于云平台的监控服务,包括云产品监控、站点监控、自定义监控、应用监控、报警管理等产品功能,实时监控您云平台中的各种资源。 + +## 查询数据接口 + +### 接口描述 +获取指定指标的一个或多个统计数据的时间序列数据。可获取云产品监控数据、站点监控数据或您推送的自定义监控数据。 + +### 接口限制 +一次返回的数据点数目不能超过1440个。 + +### 请求示例 + +```go +dimensions := map[string]string{ + "InstanceId": "xxx", +} +req := &bcm.GetMetricDataRequest{ + UserId: "xxx", + Scope: "BCE_BCC", + MetricName: "vCPUUsagePercent", + Dimensions: dimensions, + Statistics: strings.Split(bcm.Average, ","), + PeriodInSecond: 60, + StartTime: time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02T15:04:05Z"), + EndTime: time.Now().UTC().Add(-1 * time.Hour).Format("2006-01-02T15:04:05Z"), +} +resp, err := bcmClient.GetMetricData(req) +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BCM API 文档[查询数据接口](https://cloud.baidu.com/doc/BCM/s/9jwvym3kb) + +### 批量查询数据接口 + +### 接口描述 +可获取批量实例数据的接口,支持多维度多指标查找。可获取云产品监控数据、站点监控数据或您推送的自定义监控数据。 + +### 接口限制 +一个实例的任意一个指标一次返回的数据点数目不能超过1440个。 + +### 请求示例 +```go +dimensions := map[string]string{ + "InstanceId": "xxx", +} +req := &bcm.BatchGetMetricDataRequest{ + UserId: "xxx", + Scope: "BCE_BCC", + MetricNames: []string{"vCPUUsagePercent", "CpuIdlePercent"}, + Dimensions: dimensions, + Statistics: strings.Split(bcm.Average + "," + bcm.Sum, ","), + PeriodInSecond: 60, + StartTime: time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02T15:04:05Z"), + EndTime: time.Now().UTC().Add(-1 * time.Hour).Format("2006-01-02T15:04:05Z"), +} +resp, err := bcmClient.BatchGetMetricData(req) +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BCM API 文档[查询数据接口](https://cloud.baidu.com/doc/BCM/s/9jwvym3kb) + + + +## 客户端异常 + +客户端异常表示客户端尝试向BCM发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当BCM服务端出现异常时,BCM服务端会返回给用户相应的错误信息,以便定位问题 + diff --git a/bce-sdk-go/doc/BEC.md b/bce-sdk-go/doc/BEC.md new file mode 100644 index 0000000..fd286f0 --- /dev/null +++ b/bce-sdk-go/doc/BEC.md @@ -0,0 +1,1434 @@ +# BEC服务 + +# 概述 + +本文档主要介绍BEC GO SDK的使用。在使用本文档前,您需要先了解BEC的一些基本知识。若您还不了解BEC,可以参考[产品描述](https://cloud.baidu.com/doc/BEC/s/xk0p0rsgc)和[入门指南](https://cloud.baidu.com/doc/BEC/s/wk0q5mrcc)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BEC访问域名](https://cloud.baidu.com/doc/BEC/s/Tk41077qy)的部分,理解Endpoint相关的概念。 + +## 获取密钥 + +要使用百度云BEC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BEC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建普通型BEC Client + +BEC Client是BEC服务的客户端,为开发者与BEC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建普通型BEC Client + +通过AK/SK方式访问BEC,用户可以参考如下代码新建一个BEC Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bec" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BECClient + becClient, err := bec.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb)》。 + +> **注意:**`ENDPOINT`BEC域名为bec.baidubce.com,更多信息参考:https://cloud.baidu.com/doc/BEC/s/Tk41077qy + + +## 配置HTTPS协议访问BEC + +BEC支持HTTPS传输协议,您可以通过在创建BEC Client对象时指定的Endpoint中指明HTTPS的方式,在BEC GO SDK中使用HTTPS访问BEC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bec" + +ENDPOINT := "https://bec.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +becClient, _ := bec.NewClient(AK, SK, ENDPOINT) +``` + +# 主要接口 + +bec服务为用户提供边缘测vm和边缘测容器的计算服务,支持绑定lb,配置cpu,内存等资源,镜像服务等功能。 + +## vm实例管理 + +### 创建虚机实例 + +通过以下代码,可以创建bec虚机服务 +```go +args := &api.CreateVmServiceArgs{ + // 虚机服务名称 + ServiceName: "xxxxxxx@", + // 镜像id + ImageId: "im-dikfttnj-3-u-guangzhou", + // 密码 + AdminPass: "x123xxx@", + // 系统盘配置 + SystemVolume: &api.SystemVolumeConfig{VolumeType: api.DiskTypeNVME}, + // cpu大小,必须大于1 + Cpu: 1, + // memory大小,必须大于1 + Memory: 2, + // 部署区域,支持创建vpc虚机 + DeployInstances: &[]api.DeploymentInstance{api.DeploymentInstance{City: "HANGZHOU", Region: "EAST_CHINA", ServiceProvider: "CHINA_MOBILE", Replicas: 1,NetworkType: "vpc",}}, + // 镜像类型(默认为bcc、仅使用bec虚机自定义镜像时为bec) + ImageType: "bec", + // 密码或密钥配置 + KeyConfig: &api.KeyConfig{Type: "password", AdminPass: "xxxx123@"} +} + +result, err := client.CreateVmService(args) +if err != nil { + fmt.Println("create bec failed:", err) +} else { + fmt.Println("create bec success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[CreateVmService创建虚机实例](https://cloud.baidu.com/doc/BEC/s/Mkbsrt2yv) + +### 更新BEC虚机服务 + +通过以下代码,可以更新BEC虚机服务 +```go +args := &api.UpdateVmServiceArgs{ + UpdateBecVmForm: api.UpdateBecVmForm{ + // 更新类型,包括 password,replicas,resource,serviceName + Type: bec.api.UpdateVmTypeServiceName, + // 虚机名称 + VmName: "vm-xxxxx"}, + // 服务名称 + ServiceName: "xxxxtest-2", + // 部署区域列表 + DeployInstances: &[]bec.api.DeploymentInstance{bec.api.DeploymentInstance{Region: "SOUTH_CHINA", City: "GUANGZHOU", Replicas: 1, ServiceProvider: api.ServiceChinaUnicom,NetworkType: "vpc",}} +} + +err := client.UpdateVmService(serviceId, args) +if err != nil { + fmt.Println("update bec failed:", err) +} else { + fmt.Println("update bec success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[UpdateVmService更新BEC虚机服务](https://cloud.baidu.com/doc/BEC/s/jkbsxwduk) + +### 获取BEC虚机实例详情 + +通过以下代码,可以获取BEC虚机实例详情 +```go + +result, err := client.GetVmServiceDetail(serviceId) +if err != nil { + fmt.Println("get bec failed:", err) +} else { + fmt.Println("get bec success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[GetVmServiceDetail获取BEC虚机实例详情](https://cloud.baidu.com/doc/BEC/s/Ekbst85ty) + +### 获取BEC虚机服务列表 + +通过以下代码,可以获取BEC虚机服务列表 +```go +args := &api.ListVmServiceArgs{ + // 第几页,默认值1,最小值1 + PageNo: 1, + // 每页个数,默认值1000,最小1,最大1000 + pageSize: 100, +} + +result, err := client.GetVmServiceList(args) +if err != nil { + fmt.Println("list bec failed:", err) +} else { + fmt.Println("list bec success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[DescribeLoadBalancerDetail获取BEC虚机服务列表](https://cloud.baidu.com/doc/BEC/s/Okbssrahc) + +### 删除BEC虚机服务 + +通过以下代码,可以删除BEC虚机服务 +```go +err := client.DeleteVmService(serviceId) +if err != nil { + fmt.Println("delete bec failed:", err) +} else { + fmt.Println("delete bec success") +} +``` + +### 操作BEC虚机实例 + +通过以下代码,可以操作BEC虚机实例 +```go +err := client.OperateVmDeployment(vmId, action) +if err != nil { + fmt.Println("operate bec failed:", err) +} else { + fmt.Println("operate bec success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[OperateVmDeployment操作BEC虚机实例](https://cloud.baidu.com/doc/BEC/s/Fkbroisf0) + +### 重装BEC虚机实例系统 + +通过以下代码,可以重装BEC虚机实例系统 +```go +args := &api.ReinstallVmInstanceArg{ + // 镜像id + ImageId: "im-dikfxxxx", + // 密码 + AdminPass: "1xxAxxx@", + // 镜像类型(默认为bcc、仅使用bec虚机自定义镜像时为bec) + ImageType: api.ImageTypeBec, + KeyConfig: &api.KeyConfig{Type: "password", AdminPass: "1xxAxxx@"} +} + +err := client.ReinstallVmInstance(vmId, args) +if err != nil { + fmt.Println("reinstall bec failed:", err) +} else { + fmt.Println("reinstall bec success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[ReinstallVmInstance重装BEC虚机实例系统](https://cloud.baidu.com/doc/BEC/s/Ekbrqqv9j) + +### 更新BEC虚机实例 + +通过以下代码,可以更新BEC虚机实例 +```go +args := &api.UpdateVmDeploymentArgs{ + // 更新类型(password,replicas,resource) + Type: "resource", + // cpu大小 + Cpu: 2, + VmName: "xxxxx-test", + // 系统盘配置 + SystemVolume: &api.SystemVolumeConfig{VolumeType: api.DiskTypeNVME, Name: "sys", PvcName: "lvm-xxxxxx-rootfs"} +} + +err := client.UpdateVmDeployment(vmId, args) +if err != nil { + fmt.Println("update bec instance failed:", err) +} else { + fmt.Println("update bec instance bec success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[UpdateVmDeployment更新BEC虚机实例](https://cloud.baidu.com/doc/BEC/s/wkbroqu5a) + +### 获取BEC虚机实例详情 + +通过以下代码,可以获取BEC虚机实例详情 +```go +err := client.GetVirtualMachine(vmId) +if err != nil { + fmt.Println("get bec instance failed:", err) +} else { + fmt.Println("get bec instance bec success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[GetVirtualMachine获取BEC虚机实例详情](https://cloud.baidu.com/doc/BEC/s/Fkbro0yld) + +### 获取BEC虚机实例列表 + +通过以下代码,可以获取BEC虚机实例列表 +```go +args := &api.ListRequest{ + // 查询实例的关键字类型,instanceId或serviceId,缺省为serviceId + KeywordType: "instanceId", + // 查询实例的关键字 + Keyword: "vm-xxx" +} + +err := client.GetVmInstanceList(args) +if err != nil { + fmt.Println("get bec instance list failed:", err) +} else { + fmt.Println("get bec instance list success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[GetVmInstanceList更新BEC虚机实例](https://cloud.baidu.com/doc/BEC/s/Qkbrebfbz) + +## 容器相关服务 + +### 创建BEC容器服务 + +通过以下代码,可以创建BEC容器服务 +```go +args := &api.CreateServiceArgs{ + // 服务名称 + ServiceName: "xxxx-1-test", + // 付费方式,只支持后付费postpay + PaymentMethod: "postpay", + // 容器组名称 + ContainerGroupName: "cg1", + // 当needPublicIp为true时,用于设置外网带宽,范围为1Mps到2048Mps,可开通白名单上限增加到5120Mps + Bandwidth: 100, + // 是否购买公网IP,缺省否 + NeedPublicIp: false, + // 容器组信息 + Containers: &[]api.ContainerDetails{ + api.ContainerDetails{ + Name: "container01", + Cpu: 1, + Memory: 2, + ImageAddress: "hub.baidubce.com/public/mysql", + ImageVersion: "5.7", + Commands: []string{"sh", + "-c", + "echo OK!&& sleep 3660"}, + VolumeMounts: &[]api.V1VolumeMount{ + api.V1VolumeMount{ + MountPath: "/temp", + Name: "emptydir01", + }, + },}, + }, + // 部署地域信息 + DeployInstances: &[]api.DeploymentInstance{ + api.DeploymentInstance{ + Region: "EAST_CHINA", + Replicas: 1, + City: "SHANGHAI", + ServiceProvider: "CHINA_TELECOM"}, + }, + // 存储卷信息 + Volumes: &api.Volume{ + EmptyDir: &[]api.EmptyDir{ + api.EmptyDir{Name: "emptydir01"}, + }, + }, + // 标签信息 + Tags: &[]api.Tag{ + api.Tag{ + TagKey: "a", + TagValue: "1" + }, + }, +} +err := client.CreateService(args) +if err != nil { + fmt.Println("create bec service failed:", err) +} else { + fmt.Println("create bec service success: ") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[CreateService创建BEC容器服务](https://cloud.baidu.com/doc/BEC/s/Wk3zawt4x) + +### 删除BEC容器服务 + +通过以下代码,可以删除BEC容器服务 +```go +err := client.DeleteService(serviceId) +if err != nil { + fmt.Println("delete bec service failed:", err) +} else { + fmt.Println(""delete bec service success: ") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[DeleteService删除BEC容器服务](https://cloud.baidu.com/doc/BEC/s/Uk3zb1nwe) + +### 更新BEC服务 + +通过以下代码,可以更新BEC服务 +```go +getReq := &api.UpdateServiceArgs{ServiceName: "s-f9ngbkbc", Type: api.UpdateServiceTypeReplicas, DeployInstances: &[]api.DeploymentInstance{ + api.DeploymentInstance{Region: api.RegionEastChina, Replicas: 1, City: "HANGZHOU", ServiceProvider: api.ServiceChinaMobile}, +}} +res, err := CLIENT.UpdateService("s-f9ngbkbc", getReq) +if err != nil { + fmt.Println("update bec service failed:", err) +} else { + fmt.Println("update bec service success: ") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[更新BEC服务](https://cloud.baidu.com/doc/BEC/s/Tk3zaz9by) + +### 启动BEC服务 + +通过以下代码,可以启动BEC服务 +```go +res, err := CLIENT.ServiceAction("s-xxx", api.ServiceActionStart) +if err != nil { + fmt.Println("start bec service failed:", err) +} else { + fmt.Println("start bec service success: ") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[启动BEC服务](https://cloud.baidu.com/doc/BEC/s/sk3zb12kh) + +### 停止BEC服务 + +通过以下代码,可以停止BEC服务 +```go +res, err := CLIENT.ServiceAction("s-xxx", api.ServiceActionStop) +if err != nil { + fmt.Println("stop bec service failed:", err) +} else { + fmt.Println("stop bec service success: ") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[停止BEC服务](https://cloud.baidu.com/doc/BEC/s/gk412paz1) + + + + +### 获取BEC容器服务详情 + +通过以下代码,可以获取BEC容器服务详情 +```go +result, err := client.GetService(serviceId) +if err != nil { + fmt.Println("get bec pod service failed:", err) +} else { + fmt.Println("get bec pod service success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[GetService获取BEC容器服务详情](https://cloud.baidu.com/doc/BEC/s/Hk413e70s) + +### 查询部署详情 + +通过以下代码,可以查询部署详情 +```go +result, err := CLIENT.GetPodDeployment("sts-xxxx") +if err != nil { + fmt.Println("get bec pod deployment failed:", err) +} else { + fmt.Println("get bec pod deployment success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询部署详情](https://cloud.baidu.com/doc/BEC/s/Lk3fmy6v2) + +### 查询部署资源监控 + +通过以下代码,可以获取查询部署资源监控 +```go +res, err := CLIENT.GetPodDeploymentMetrics("sts-xxxx", api.MetricsTypeMemory, "", 1661270400, 1661356800, 0) +if err != nil { + fmt.Println("get bec pod deployment failed:", err) +} else { + fmt.Println("get bec pod deployment success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询部署资源监控](https://cloud.baidu.com/doc/BEC/s/Wk3h9n5n1) +### 更新部署副本数 + +通过以下代码,可以获取更新部署副本数 +```go +getReq := &api.UpdateDeploymentReplicasRequest{ + Replicas: 2, +} +res, err := CLIENT.UpdatePodDeploymentReplicas("sts-xxxx", getReq) +if err != nil { + fmt.Println("update bec pod deployment replicas failed:", err) +} else { + fmt.Println("update bec pod deployment replicas success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[更新部署副本数](https://cloud.baidu.com/doc/BEC/s/Wk3h9n5n1) + +### 删除部署 + +通过以下代码,可以删除部署 +```go +getReq := &[]string{"sts-xxxx"} +res, err := CLIENT.DeletePodDeployment(getReq) +if err != nil { + fmt.Println("delete bec pod deployment failed:", err) +} else { + fmt.Println("delete bec pod deployment success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除部署](https://cloud.baidu.com/doc/BEC/s/jk3h9bcr5) + +### 查询pod列表 + +通过以下代码,可以查询pod列表 +```go +res, err := CLIENT.GetPodList(1, 100, "", "", "", "", "") +if err != nil { + fmt.Println("get bec pod list failed:", err) +} else { + fmt.Println("get bec pod list success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询pod列表](https://cloud.baidu.com/doc/BEC/s/2k3i3ucrh) + +### 查询pod资源监控 + +通过以下代码,可以查询pod资源监控 +```go +res, err := CLIENT.GetPodMetrics("sts-xxx-0", api.MetricsTypeMemory, "", 1661270400, 1661356800, 0) + +if err != nil { + fmt.Println("get bec pod metrics failed:", err) +} else { + fmt.Println("get bec pod metrics success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询pod资源监控](https://cloud.baidu.com/doc/BEC/s/Rk3ibrrdu) + +### 查询pod详情 + +通过以下代码,可以查询pod详情 +```go +res, err := CLIENT.GetPodDetail("sts-xzzxxxx-0") +if err != nil { + fmt.Println("get bec pod detail failed:", err) +} else { + fmt.Println("get bec pod detail success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询pod详情](https://cloud.baidu.com/doc/BEC/s/Ok3i3vgl7) + +### 重启容器组 + +通过以下代码,可以重启容器组 +```go +err := CLIENT.RestartPod("sts-xxxxx-0") +if err != nil { + fmt.Println("restart bec pod failed:", err) +} else { + fmt.Println("restart bec pod success: ", res) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[重启容器组](https://cloud.baidu.com/doc/BEC/s/Jk3ib7df8) + + +## 负载均衡器 + +### 创建负载均衡 + +通过以下代码,可以创建负载均衡 +```go +args := &api.CreateBlbArgs{ + // 负载均衡名称 + BlbName: "xxxx-test", + // 负载均衡所在区域信息 + Region: api.RegionEastChina, + // 负载均衡所在城市信息 + City: "HANGZHOU", + LbType: "vm", + ServiceProvider: api.ServiceChinaMobile + // 创建applb + NetworkType: "vpc", +} +err := client.CreateBlb(args) +if err != nil { + fmt.Println("remove backend servers failed:", err) +} else { + fmt.Println("remove backend servers success: ") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[CreateBlb创建负载均衡](https://cloud.baidu.com/doc/BEC/s/zkbrnvg6w) + +### 删除负载均衡 + +通过以下代码,可以删除负载均衡 +```go + +err := client.DeleteBlb(BLBID) +if err != nil { + fmt.Println("create TCP Listener failed:", err) +} else { + fmt.Println("create TCP Listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[DeleteBlb删除负载均衡](https://cloud.baidu.com/doc/BEC/s/qkbrnx86o) + +### 查看负载均衡详情 + +通过以下代码,可以查看负载均衡详情 +```go +err := client.GetBlbDetail(BLBID) +if err != nil { + fmt.Println("update TCP Listener failed:", err) +} else { + fmt.Println("update TCP Listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[GetBlbDetail查看负载均衡详情](https://cloud.baidu.com/doc/BEC/s/ekbrnvz0c) + +### 创建监听设置 + +通过以下代码,可以创建监听设置 +```go +args := &api.BlbMonitorArgs{ + // 转发规则 + LbMode: api.LbModeWrr, + // 负载均衡端口 + FrontendPort: &api.Port{Protocol: api.ProtocolUdp,Port: 80}, + // 后端端口 + BackendPort: 80, + // 健康检查设置 + HealthCheck: &api.HealthCheck{HealthCheckString: "", HealthCheckType: "udp", HealthyThreshold: 1000, + UnhealthyThreshold: 1000, + TimeoutInSeconds: 900, + IntervalInSeconds: 3} +} + +result, err := client.CreateBlbMonitorPort(BLBID, args) +if err != nil { + fmt.Println("describe TCP Listener failed:", err) +} else { + fmt.Println("describe TCP Listener success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[CreateBlbMonitorPort创建监听设置](https://cloud.baidu.com/doc/BEC/s/ikbrnxqnj) + +### 删除监听设置 + +通过以下代码,可以删除监听设置 +```go +// 负载均衡监听端口列表 +args := &[]api.Port{{ + Protocol: api.ProtocolUdp, + Port: 80}, +} +err := client.DeleteBlbMonitorPort(BLBID, args) +if err != nil { + fmt.Println("create UDP Listener failed:", err) +} else { + fmt.Println("create UDP Listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[DeleteBlbMonitorPort删除监听设置](https://cloud.baidu.com/doc/BEC/s/dkbrnxzcw) + +### 创建后端服务器 + +通过以下代码,可以创建后端服务器 +```go +args := &&api.CreateBlbBindingArgs{ + // 创建后端服务器请求 + BindingForms: &[]api.BlbBindingForm{api.BlbBindingForm{DeploymentId: "xxxx", PodWeight: &[]api.Backends{api.Backends{Name: "xxxxxx", Ip: "172.xx.x.xx", Weight: 100}}, +}}} +err := client.CreateBlbBinding(BLBID, args) +if err != nil { + fmt.Println("update UDP Listener failed:", err) +} else { + fmt.Println("update UDP Listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[CreateBlbBinding创建后端服务器](https://cloud.baidu.com/doc/BEC/s/Ckbrnyb8q) + +### 删除后端服务器 + +通过以下代码,可以删除后端服务器 +```go +args := &api.DeleteBlbBindPodArgs{ + // 删除后端服务器请求 + PodWeightList: &[]api.Backends{ + api.Backends{Name: "vm-xxx", Ip: "172.16.9xxx.xxx", Weight: 10}}, + DeploymentIds: []string{"vmrs-xxxx"}, +} + +result, err := client.DeleteBlbBindPod(BLBID, args) +if err != nil { + fmt.Println("describe UDP Listener failed:", err) +} else { + fmt.Println("describe UDP Listener success: ", result) +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[DeleteBlbBindPod删除后端服务器](https://cloud.baidu.com/doc/BEC/s/2kbrnz2wi) + +## 镜像相关 + +### 创建BEC虚机镜像 + +通过以下代码,可以创建BEC虚机镜像 +```go +args := &api.CreateVmImageArgs{ + // 虚机实例id + VmId: "vm-xxxx-1", + // 镜像名称(长度1-65) + Name: "xxxx-test" +} +err := client.CreateVmImage(args) +if err != nil { + fmt.Println("create HTTP Listener failed:", err) +} else { + fmt.Println("create HTTP Listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[CreateVmImage创建BEC虚机镜像](https://cloud.baidu.com/doc/BEC/s/Uklg7azo0) + +### 批量删除BEC虚机镜像 + +通过以下代码,可以批量删除BEC虚机镜像 +```go +args := []string{"xxxxxx-1", "xxxxxx-2"} +err := client.DeleteVmImage(args) +if err != nil { + fmt.Println("update HTTP Listener failed:", err) +} else { + fmt.Println("update HTTP Listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[DeleteVmImage批量删除BEC虚机镜像](https://cloud.baidu.com/doc/BEC/s/Sklgbqn7g) + +## 部署集相关 +### 创建部署集 + +通过以下代码,可以创建部署集 +```go +getReq := &api.CreateDeploySetArgs{ +Name: "xxx_test", +Desc: "xxx-test", +} +res, err := CLIENT.CreateDeploySet(getReq) +if err != nil { + fmt.Println("create deploy set failed:", err) +} else { + fmt.Println("create deploy set success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建部署集](https://cloud.baidu.com/doc/BEC/s/Sl0t89s48) + +### 修改部署集 + +通过以下代码,可以修改部署集 +```go +getReq := &api.CreateDeploySetArgs{ + Name: "xxx_test", + Desc: "xxx-test", +} +err := CLIENT.UpdateDeploySet("dset-xxx", getReq) +res, err := CLIENT.CreateDeploySet(getReq) +if err != nil { + fmt.Println("update deploy set failed:", err) +} else { + fmt.Println("update deploy set success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[修改部署集](https://cloud.baidu.com/doc/BEC/s/Ml0tb0d5s) + +### 获取部署集列表 + +通过以下代码,可以获取部署集列表 +```go +getReq := &api.ListRequest{} +res, err := CLIENT.GetDeploySetList(getReq) +if err != nil { + fmt.Println("get deploy set list failed:", err) +} else { + fmt.Println("get deploy set list success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[获取部署集列表](https://cloud.baidu.com/doc/BEC/s/Cl0t8xm4g) + +### 获取部署集详情 + +通过以下代码,可以获取部署集详情 +```go +res, err := CLIENT.GetDeploySetDetail("dset-xxxx") +if err != nil { + fmt.Println("get deploy set details failed:", err) +} else { + fmt.Println("get deploy set details success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[获取部署集详情](https://cloud.baidu.com/doc/BEC/s/9l0talan1) + +### 删除部署集 + +通过以下代码,可以删除部署集 +```go +err := CLIENT.DeleteDeploySet("dset-y4tumnel") +if err != nil { + fmt.Println("delete deploy set failed:", err) +} else { + fmt.Println("delete deploy set success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除部署集](https://cloud.baidu.com/doc/BEC/s/1l0ulgpsv) + +### 虚机实例调整部署集 + +通过以下代码,可以调整虚机实例的部署集 +```go +getReq := &api.UpdateVmDeploySetArgs{ +InstanceId: "vm-xxxx", +DeploysetIdList: []string{"dset-xxxx"}, +} +err := CLIENT.UpdateVmInstanceDeploySet(getReq) +if err != nil { + fmt.Println("update vm instance deploy set failed:", err) +} else { + fmt.Println("update vm instance deploy set success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[虚机实例调整部署集](https://cloud.baidu.com/doc/BEC/s/nl0um3hvs) + +### 部署集移除虚机实例 + +通过以下代码,可以将虚机实例从部署集移除 +```go +getReq := &api.DeleteVmDeploySetArgs{ + DeploysetId: "dset-y4tumnel", + InstanceIdList: []string{"vm-dstkrmda-cn-langfang-ct-4thbz"}, +} +err := CLIENT.DeleteVmInstanceFromDeploySet(getReq) +if err != nil { + fmt.Println("remove vm instance from deploy set failed:", err) +} else { + fmt.Println("remove vm instance from deploy set success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[部署集移除实例](https://cloud.baidu.com/doc/BEC/s/Ml0ulrz5z) +## APPBLB相关 +### 创建APPBLB实例 + +通过以下代码,可以创建APPBLB实例 +```go +getReq := &api.CreateAppBlbRequest{ + Name: "xxx_test_applb", + Desc: "xxx-test", + RegionId: "cn-hangzhou-cm", + NeedPublicIp: true, + SubnetId: "sbn-xx", + VpcId: "vpc-xx", +} +res, err := CLIENT.CreateAppBlb("testCreateAppBlb", getReq) + +if err != nil { + fmt.Println("create app blb instance failed:", err) +} else { + fmt.Println("create app blb instance success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建APPBLB实例](https://cloud.baidu.com/doc/BEC/s/zl4nug4yg) + +### 修改APPBLB实例 +通过以下代码,可以修改APPBLB实例 +```go +getReq := &api.ModifyBecBlbRequest{ + Name: "xx_test_applb", + Desc: "xx-test1", +} +err := CLIENT.UpdateAppBlb("testUpdateAppBlb", "applb-xx", getReq) + +if err != nil { + fmt.Println("update app blb instance failed:", err) +} else { + fmt.Println("update app blb instance success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[修改APPBLB实例](https://cloud.baidu.com/doc/BEC/s/Ul4nuv8n2) +### 查询APPBLB实例列表 +通过以下代码,可以查询APPBLB实例列表 +```go +getReq := &api.MarkerRequest{} +res, err := CLIENT.GetAppBlbList(getReq) + +if err != nil { + fmt.Println("get app blb instance list failed:", err) +} else { + fmt.Println("get app blb instance list success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询APPBLB实例列表](https://cloud.baidu.com/doc/BEC/s/9l4nv22ji) + +### 查询APPBLB实例详情 +通过以下代码,可以查询APPBLB实例详情 +```go +res, err := CLIENT.GetAppBlbDetails("applb-xxxx") + +if err != nil { + fmt.Println("get app blb instance detail failed:", err) +} else { + fmt.Println("get app blb instance detail success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询APPBLB实例详情](https://cloud.baidu.com/doc/BEC/s/Ul4nvz6d8) + +### 删除APPBLB实例 +通过以下代码,可以删除APPBLB实例 +```go +err := CLIENT.DeleteAppBlbInstance("applb-xxx", "") + +if err != nil { + fmt.Println("delete app blb instance failed:", err) +} else { + fmt.Println("delete app blb instance success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除APPBLB实例](https://cloud.baidu.com/doc/BEC/s/7l4nwir90) + +### 创建TCP监听器 +通过以下代码,可以创建TCP监听器 +```go +getReq := &api.CreateBecAppBlbTcpListenerRequest{ + ListenerPort: 80, + Scheduler: "RoundRobin", + TcpSessionTimeout: 1000, +} +err := CLIENT.CreateTcpListener("testCreateTcpListener", "applb-xxx", getReq) +if err != nil { + fmt.Println("create app tcp listener failed:", err) +} else { + fmt.Println("create app tcp listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建TCP监听器](https://cloud.baidu.com/doc/BEC/s/il4nwx3ts) + +### 创建UDP监听器 +通过以下代码,可以创建UDP监听器 +```go +getReq := &api.CreateBecAppBlbUdpListenerRequest{ + ListenerPort: 80, + Scheduler: "RoundRobin", + UdpSessionTimeout: 1000, +} +err := CLIENT.CreateUdpListener("testCreateTcpListener", "applb-xxxx", getReq) +if err != nil { + fmt.Println("create app udp listener failed:", err) +} else { + fmt.Println("create app udp listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建UDP监听器](https://cloud.baidu.com/doc/BEC/s/sl4p73e1g) + +### 新建监听器策略 +通过以下代码,可以新建监听器策略 +```go +getReq := &api.CreateAppBlbPoliciesRequest{ + ListenerPort: 80, + AppPolicyVos: []api.AppPolicyVo{ + { + AppIpGroupId: "bec_ip_group-xxx", + Priority: 1, + Desc: "xxx-test", + }, + }, +} +err := CLIENT.CreateListenerPolicy("", "applb-xxx", getReq) +if err != nil { + fmt.Println("create app blb listener policy failed:", err) +} else { + fmt.Println("create app blb listener policy success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[新建监听器策略](https://cloud.baidu.com/doc/BEC/s/Hl4qgo88o) + +### 查询监听器策略 +通过以下代码,可以查询监听器策略 +```go +getReq := &api.GetBlbListenerPolicyRequest{ + Port: 80, +} +res, err := CLIENT.GetListenerPolicy("applb-xxx", getReq) +if err != nil { + fmt.Println("get app blb listener policy failed:", err) +} else { + fmt.Println("get app blb listener policy success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询监听器策略](https://cloud.baidu.com/doc/BEC/s/cl4qgvkbp) + +### 删除监听器策略 +通过以下代码,可以删除监听器策略 +```go +getReq := &api.DeleteAppBlbPoliciesRequest{ + Port: 80, + PolicyIdList: []string{ + "bec_policy-scr9cwtk", + }, +} +err := CLIENT.DeleteListenerPolicy("", "applb-xxxxx", getReq) +if err != nil { + fmt.Println("delete app blb listener policy failed:", err) +} else { + fmt.Println("delete app blb listener policy success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除监听器策略](https://cloud.baidu.com/doc/BEC/s/Bl4qhc0vy) + +### 修改TCP监听器 +通过以下代码,可以修改TCP监听器 +```go +getReq := &api.UpdateBecAppBlbTcpListenerRequest{ + Scheduler: "RoundRobin", + TcpSessionTimeout: 800, +} +err := CLIENT.UpdateTcpListener("testUpdateTcpListener", "applb-xxx", "80", getReq) +if err != nil { + fmt.Println("update app tcp listener failed:", err) +} else { + fmt.Println("update app tcp listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[修改TCP监听器](https://cloud.baidu.com/doc/BEC/s/sl4p73e1g) + +### 修改UDP监听器 +通过以下代码,可以修改UDP监听器 +```go +getReq := &api.UpdateBecAppBlbUdpListenerRequest{ + Scheduler: "RoundRobin", + UdpSessionTimeout: 800, +} +err := CLIENT.UpdateUdpListener("testUpdateUdpListener", "applb-xxx", "80", getReq) +if err != nil { + fmt.Println("update app udp listener failed:", err) +} else { + fmt.Println("update app udp listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[修改UDP监听器](https://cloud.baidu.com/doc/BEC/s/al4p7c82y) + +### 查询TCP监听器 +通过以下代码,可以查询TCP监听器 +```go +getReq := &api.GetBecAppBlbListenerRequest{ + ListenerPort: 80, +} +res, err := CLIENT.GetTcpListener("applb-xxxx", getReq) +if err != nil { + fmt.Println("get app udp listener failed:", err) +} else { + fmt.Println("get app udp listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询TCP监听器](https://cloud.baidu.com/doc/BEC/s/Ul4nxiz6l) + +### 查询TCP监听器 +通过以下代码,可以查询UDP监听器 +```go +getReq := &api.GetBecAppBlbListenerRequest{ + ListenerPort: 80, +} +res, err := CLIENT.GetUdpListener("applb-xxxx", getReq) +if err != nil { + fmt.Println("get app udp listener failed:", err) +} else { + fmt.Println("get app udp listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询UDP监听器](https://cloud.baidu.com/doc/BEC/s/4l4p7ih5s) + +### 删除监听器 +通过以下代码,可以删除监听器 +```go +getReq := &api.DeleteBlbListenerRequest{ +PortTypeList: []api.PortTypeList{ + { + Port: 80, + Type: "TCP", + }, + { + Port: 80, + Type: "UDP", + }, + }, +} +err := CLIENT.DeleteAppBlbListener("applb-xxx", "deleteApplbInstance", getReq) +if err != nil { + fmt.Println("delete app listener failed:", err) +} else { + fmt.Println("delete app listener success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除监听器](https://cloud.baidu.com/doc/BEC/s/dl4p7sfyb) + +### 创建IP组 +通过以下代码,可以创建IP组 +```go +getReq := &api.CreateBlbIpGroupRequest{ + Name: "xxx-testIpGroup", + Desc: "xxx-test", +} +res, err := CLIENT.CreateIpGroup("testIpGroup", "applb-xxx", getReq) +if err != nil { + fmt.Println("create app blb ip group failed:", err) +} else { + fmt.Println("create app blb ip group success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建IP组](https://cloud.baidu.com/doc/BEC/s/nl4p9vtw2) + +### 更新IP组 +通过以下代码,可以更新IP组 +```go +getReq := &api.UpdateBlbIpGroupRequest{ + Name: "xxx-testIpGroupupdate", + Desc: "xxx-testupdate", + IpGroupId: "bec_ip_group-xxx", +} +err := CLIENT.UpdateIpGroup("testIpGroup", "applb-xxx", getReq) +if err != nil { + fmt.Println("update app blb ip group failed:", err) +} else { + fmt.Println("update app blb ip group success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[更新IP组](https://cloud.baidu.com/doc/BEC/s/wl4pahvlw) + +### 查询IP组列表 +通过以下代码,可以查询IP组列表 +```go +getReq := &api.GetBlbIpGroupListRequest{} +res, err := CLIENT.GetIpGroup("applb-xxxx", getReq) +if err != nil { + fmt.Println("get app blb ip group list failed:", err) +} else { + fmt.Println("get app blb ip group list success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询IP组列表](https://cloud.baidu.com/doc/BEC/s/El4pan7ox) + +### 删除IP组 +通过以下代码,可以删除IP组 +```go +getReq := &api.DeleteBlbIpGroupRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", +} +err := CLIENT.DeleteIpGroup("testDeleteIpGroup", "applb-xxxx", getReq) +if err != nil { + fmt.Println("delete app blb ip group failed:", err) +} else { + fmt.Println("delete app blb ip group success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除IP组](https://cloud.baidu.com/doc/BEC/s/Ml4qem709) + +### 创建IP组协议 +通过以下代码,可以创建IP组协议 +```go +getReq := &api.CreateBlbIpGroupBackendPolicyRequest{ + IpGroupId: "bec_ip_group-xxx, + Type: "TCP", + HealthCheck: "TCP", + HealthCheckPort: 80, + HealthCheckTimeoutInSecond: 10, + HealthCheckIntervalInSecond: 3, + HealthCheckDownRetry: 4, + HealthCheckUpRetry: 5, +} +res, err := CLIENT.CreateIpGroupPolicy("", "applb-xxx", getReq) +if err != nil { + fmt.Println("create app blb ip group policy failed:", err) +} else { + fmt.Println("create app blb ip group policy success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建IP组协议](https://cloud.baidu.com/doc/BEC/s/Ml4qem709) + +### 更新IP组协议 +通过以下代码,可以更新IP组协议 +```go +getReq := &api.UpdateBlbIpGroupBackendPolicyRequest{ + IpGroupId: "bec_ip_group-xxx", + Id: "bec_ip_group_policy-xxx", + HealthCheckPort: 80, +} +err := CLIENT.UpdateIpGroupPolicy("", "applb-xxx", getReq) +if err != nil { + fmt.Println("update app blb ip group policy failed:", err) +} else { + fmt.Println("update app blb ip group policy success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[更新IP组协议](https://cloud.baidu.com/doc/BEC/s/5l4qexv01) + +### 查询IP组协议列表 +通过以下代码,可以查询IP组协议列表 +```go +getReq := &api.GetBlbIpGroupPolicyListRequest{ + IpGroupId: "bec_ip_group-xxx", +} +res, err := CLIENT.GetIpGroupPolicyList("applb-xxx", getReq) +if err != nil { + fmt.Println("get app blb ip group policy list failed:", err) +} else { + fmt.Println("get app blb ip group policy list success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询IP组协议列表](https://cloud.baidu.com/doc/BEC/s/2l4qf4jv6) + +### 删除IP组协议 +通过以下代码,可以删除IP组协议 +```go +getReq := &api.DeleteBlbIpGroupBackendPolicyRequest{ + IpGroupId: "bec_ip_group-xxx", + BackendPolicyIdList: []string{"bec_ip_group_policy-xx"}, +} +err := CLIENT.DeleteIpGroupPolicy("", "applb-xxx", getReq) +if err != nil { + fmt.Println("delete app blb ip group policy failed:", err) +} else { + fmt.Println("delete app blb ip group policy success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除IP组协议](https://cloud.baidu.com/doc/BEC/s/Ll4qg1hun) + +### 创建IP组成员 +通过以下代码,可以创建IP组成员 +```go +getReq := &api.CreateBlbIpGroupMemberRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + MemberList: []api.BlbIpGroupMember{ + { + Ip: "172.16.240.25", + Port: 90, + Weight: 100, + }, + }, +} +res, err := CLIENT.CreateIpGroupMember("", "applb-xxxx", getReq) +if err != nil { + fmt.Println("create app blb ip group member failed:", err) +} else { + fmt.Println("create app blb ip group member success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[创建IP组成员](https://cloud.baidu.com/doc/BEC/s/yl4qf9xbw) + +### 更新IP组成员 +通过以下代码,可以更新IP组成员 +```go +getReq := &api.UpdateBlbIpGroupMemberRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + MemberList: []api.UpdateBlbIpGroupMember{ + { + MemberId: "bec_ip_member-ouiinabp", + Port: 8080, + Weight: 100, + }, + }, +} +err := CLIENT.UpdateIpGroupMember("", "applb-xxxx", getReq) +if err != nil { + fmt.Println("update app blb ip group member failed:", err) +} else { + fmt.Println("update app blb ip group member success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[更新IP组成员](https://cloud.baidu.com/doc/BEC/s/Gl4qfi31t) + +### 查询IP组成员列表 +通过以下代码,可以查询IP组成员列表 +```go +getReq := &api.GetBlbIpGroupMemberListRequest{ + IpGroupId: "bec_ip_group-xxx", +} +res, err := CLIENT.GetIpGroupMemberList("applb-xxxx", getReq) +if err != nil { + fmt.Println("get app blb ip group member list failed:", err) +} else { + fmt.Println("get app blb ip group member list success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[查询IP组成员列表](https://cloud.baidu.com/doc/BEC/s/Il4qfnftj) + +### 删除IP组成员 +通过以下代码,可以删除IP组成员 +```go +getReq := &api.DeleteBlbIpGroupBackendMemberRequest{ + IpGroupId: "bec_ip_group-xxx", + MemberIdList: []string{"bec_ip_member-xxx"}, +} +err := CLIENT.DeleteIpGroupMember("", "applb-xxx", getReq) +if err != nil { + fmt.Println("delete app blb ip group member failed:", err) +} else { + fmt.Println("delete app blb ip group member success") +} +``` +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BEC API 文档[删除IP组成员](https://cloud.baidu.com/doc/BEC/s/Hl4qftd63) + + + + + + +## 客户端异常 + +客户端异常表示客户端尝试向BEC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当BEC服务端出现异常时,BEC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BEC错误返回](https://cloud.baidu.com/doc/BEC/s/5k4106ncs) + +# 版本变更记录 + +## 更新日期 [2022-08-25] + +更新内容 + +- 更新虚机相关的参数、支持创建VPC虚机、更新获取虚机监控的接口 +- 更新负载均衡相关参数、支持创建APPLB、更新获取负载均衡监控的接口 +- 更新了容器服务接口的相关参数 + +新增内容 + +- 创建、删除、列表、更新、详情虚机部署集 +- 将虚机移入、移除部署集 +- 监控接口新增stepInMin参数 +- 创建、修改、查询、删除APPBLB +- 创建、修改、查询、删除APPBLB监听器以及监听器策略 +- 创建、修改、查询、删除APPBLB IP组、IP组协议、IP组成员 +- 查询容器部署详情、查询容器部署监控、更新容器部署副本、删除容器部署 +- 查询POD列表、详情、资源监控,重启容器组 + + + +## v0.9.11 [2021-04-21] + +首次发布: + + - 创建、列表、更新、删除VM镜像 + - 创建、列表、更新、删除、详情、批量创建、批量删除blb、获取负载均衡监控信息 + - 创建、删除、列表、更新、详情、批量创建blb监听 + - 获取负载均衡已绑定资源列表、获取负载均衡可绑定的部署列表、获取部署中可绑定资源列表、创建后端服务器、删除后端服务器、修改负载均衡已绑定资源权重 + - 创建、更新、列表、详情、删除、操作、批量删除、批量操作虚机服务、获取BEC虚机服务监控 + - 创建无实例的虚机服务、创建虚机实例、添加辅助ip、删除辅助ip + - 列表、详情、删除、更新、重装、操作虚机实例、获取虚机实例配置、获取所在节点的BEC虚机列表、获取虚机监控信息 + - 创建、列表、详情、操作、更新、删除、批量操作、批量删除容器服务、获取BEC容器服务监控 + diff --git a/bce-sdk-go/doc/BLB.md b/bce-sdk-go/doc/BLB.md new file mode 100644 index 0000000..6e9e523 --- /dev/null +++ b/bce-sdk-go/doc/BLB.md @@ -0,0 +1,808 @@ +# BLB服务 + +# 概述 + +本文档主要介绍普通型BLB GO SDK的使用。在使用本文档前,您需要先了解普通型BLB的一些基本知识。若您还不了解普通型BLB,可以参考[产品描述](https://cloud.baidu.com/doc/BLB/s/Ajwvxno34)和[入门指南](https://cloud.baidu.com/doc/BLB/s/cjwvxnr91)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BLB访问域名](https://cloud.baidu.com/doc/BLB/s/cjwvxnzix)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云BLB,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BLB做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建普通型BLB Client + +普通型BLB Client是普通型BLB服务的客户端,为开发者与BLB服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建普通型BLB Client + +通过AK/SK方式访问BLB,用户可以参考如下代码新建一个BLB Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BLBClient + blbClient, err := blb.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BLB/s/ojwvynrqn)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BLB的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`blb.bj.baidubce.com`。 + +### 使用STS创建BLB Client + +**申请STS token** + +BLB可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BLB,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建BLB Client** + +申请好STS后,可将STS Token配置到BLB Client中,从而实现通过STS Token创建BLB Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BLB Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/blb" //导入BLB服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BLB服务的Client对象,Endpoint使用默认值 + blbClient, err := blb.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create blb client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + blbClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BLB Client时,无论对应BLB服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问BLB + +BLB支持HTTPS传输协议,您可以通过在创建BLB Client对象时指定的Endpoint中指明HTTPS的方式,在BLB GO SDK中使用HTTPS访问BLB服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/blb" + +ENDPOINT := "https://blb.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +blbClient, _ := blb.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BLB Client + +如果用户需要配置BLB Client的一些细节的参数,可以在创建BLB Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BLB服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/blb" + +//创建BLB Client对象 +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com +client, _ := blb.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/blb" + +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := blb.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/blb" + +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := blb.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BLB时,创建的BLB Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BLB Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +普通型blb实例针对用户复杂应用部署架构,特别是大型网站架构。使用基于策略的网络管理框架构建,实现业务驱动的流量负载均衡。 + +## 实例管理 + +### 创建实例 + +通过以下代码,可以创建一个普通型LoadBalancer,返回分配的服务地址及实例ID +```go +args := &blb.CreateLoadBalancerArgs{ + // 设置实例名称 + Name: "sdkBlb", + // 设置实例描述 + Description: "sdk create", + // 设置实例所属vpc + VpcId: vpcId, + // 设置实例所属子网 + SubnetId: subnetId, +} + +// 若要为实例设置标签,可以按照以下代码,标签设置之后,不可修改和删除 +args.Tags = []model.TagModel{ + { + TagKey: "key", + TagValue: "value", + }, +} +result, err := client.CreateLoadBalancer(args) +if err != nil { + fmt.Println("create blb failed:", err) +} else { + fmt.Println("create blb success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[CreateLoadBalancer创建实例](https://cloud.baidu.com/doc/BLB/s/njwvxnv79#createloadbalancer%E5%88%9B%E5%BB%BA%E5%AE%9E%E4%BE%8B) + +### 更新实例 + +通过以下代码,可以更新一个LoadBalancer的配置信息,如实例名称和描述 +```go +args := &blb.UpdateLoadBalancerArgs{ + Name: "testSdk", + Description: "test desc", +} +err := client.UpdateLoadBalancer(blbId, args) +if err != nil { + fmt.Println("update blb failed:", err) +} else { + fmt.Println("update blb success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[UpdateLoadBalancer更新实例](https://cloud.baidu.com/doc/BLB/s/njwvxnv79#updateloadbalancer%E6%9B%B4%E6%96%B0%E5%AE%9E%E4%BE%8B) + +### 查询已有的实例 + +通过以下代码,可以查询用户账户下所有LoadBalancer的信息 +```go +args := &blb.DescribeLoadBalancersArgs{} + +// 支持按LoadBalancer的id、name、address进行查询,匹配规则支持部分包含(不支持正则) +args.BlbId = blbId +args.Name = blbName +args.Address = blbAddress +args.ExactlyMatch = true + +// 支持查找绑定指定BLB的LoadBalancer,通过blbId参数指定 +args.BlbId = blbId + +result, err := client.DescribeLoadBalancers(args) +if err != nil { + fmt.Println("list all blb failed:", err) +} else { + fmt.Println("list all blb success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeLoadBalancers查询已有的BLB实例](https://cloud.baidu.com/doc/BLB/s/njwvxnv79#describeloadbalancers%E6%9F%A5%E8%AF%A2%E5%B7%B2%E6%9C%89%E7%9A%84blb%E5%AE%9E%E4%BE%8B) + +### 查询实例详情 + +通过以下代码,可以按id查询用户账户下特定的普通型LoadBalancer的详细信息,包含LoadBalancer所有的监听器端口信息 +```go +result, err := client.DescribeLoadBalancerDetail(blbId) +if err != nil { + fmt.Println("get blb detail failed:", err) +} else { + fmt.Println("get blb detail success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeLoadBalancerDetail查询BLB实例详情](https://cloud.baidu.com/doc/BLB/s/njwvxnv79#describeloadbalancerdetail%E6%9F%A5%E8%AF%A2blb%E5%AE%9E%E4%BE%8B%E8%AF%A6%E6%83%85) + +### 释放实例 + +通过以下代码,可以释放指定LoadBalancer,被释放的LoadBalancer无法找回 +```go +err := client.DeleteLoadBalancer(blbId) +if err != nil { + fmt.Println("delete blb failed:", err) +} else { + fmt.Println("delete blb success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DeleteLoadBalancer释放BLB实例](https://cloud.baidu.com/doc/BLB/s/njwvxnv79#deleteloadbalancer%E9%87%8A%E6%94%BEblb%E5%AE%9E%E4%BE%8B) + +### 添加普通型BLB后端服务器 + +通过以下代码,在指定普通型BLB下绑定后端服务器 +```go +args := &blb.AddBackendServersArgs{ + // 配置后端服务器的列表及权重 + BackendServerList: []blb.BackendServerModel{ + {InstanceId: instanceId, Weight: 100}, + }, +} +err := client.AddBackendServers(blbId, args) +if err != nil { + fmt.Println("add backend servers failed:", err) +} else { + fmt.Println("add backend servers success: ") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[AddBackendServers添加后端服务器](https://cloud.baidu.com/doc/BLB/s/Ujwvxnvxe#addbackendservers%E6%B7%BB%E5%8A%A0%E5%90%8E%E7%AB%AF%E6%9C%8D%E5%8A%A1%E5%99%A8) + +### 更新后端服务器权重 + +通过以下代码,更新指定blb下的信息 +```go +args := &blb.UpdateBackendServersArgs{ + // 配置后端服务器的列表及权重 + BackendServerList: []blb.BackendServerModel{ + {InstanceId: instanceId, Weight: 30}, + }, +} +err := client.UpdateBackendServers(blbId, args) +if err != nil { + fmt.Println("update backend servers failed:", err) +} else { + fmt.Println("update backend servers success: ") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[UpdateBackendServers更新后端服务器](https://cloud.baidu.com/doc/BLB/s/Ujwvxnvxe#updatebackendservers%E6%9B%B4%E6%96%B0%E5%90%8E%E7%AB%AF%E6%9C%8D%E5%8A%A1%E5%99%A8) + +### 查询后端服务器列表信息 + +通过以下代码,查询指定LoadBalancer下所有服务器的信息 +```go +args := &blb.DescribeBackendServersArgs{ + +} +result, err := client.DescribeBackendServers(blbId, args) +if err != nil { + fmt.Println("describe backend servers failed:", err) +} else { + fmt.Println("describe backend servers success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeBackendServers查询后端服务器列表](https://cloud.baidu.com/doc/BLB/s/Ujwvxnvxe#describebackendservers%E6%9F%A5%E8%AF%A2%E5%90%8E%E7%AB%AF%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%88%97%E8%A1%A8) + +### 查询后端服务器健康状态 + +通过以下代码,查询指定监听端口下后端服务器的健康状态信息 +```go +args := &blb.DescribeHealthStatusArgs{ + ListenerPort: 80, +} +result, err := client.DescribeHealthStatus(blbId, args) +if err != nil { + fmt.Println("describe health status failed:", err) +} else { + fmt.Println("describe health status success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeHealthStatus查询后端服务器健康状态](https://cloud.baidu.com/doc/BLB/s/Ujwvxnvxe#describehealthstatus%E6%9F%A5%E8%AF%A2%E5%90%8E%E7%AB%AF%E6%9C%8D%E5%8A%A1%E5%99%A8%E5%81%A5%E5%BA%B7%E7%8A%B6%E6%80%81) + +### 释放后端服务器 + +通过以下代码,释放后端服务器 +```go +args := &blb.RemoveBackendServersArgs{ + // 要从后端服务器列表中释放的实例列表 + BackendServerList: []string{instanceId}, +} +err := client.RemoveBackendServers(blbId, args) +if err != nil { + fmt.Println("remove backend servers failed:", err) +} else { + fmt.Println("remove backend servers success: ") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[RemoveBackendServers释放后端服务器](https://cloud.baidu.com/doc/BLB/s/Ujwvxnvxe#removebackendservers%E9%87%8A%E6%94%BE%E5%90%8E%E7%AB%AF%E6%9C%8D%E5%8A%A1%E5%99%A8) + +## 监听器管理 + +### 创建TCP监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于TCP协议的普通型blb监听器,监听一个前端端口,将发往该端口的所有TCP流量,根据策略进行转发 +```go +args := &blb.CreateTCPListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 80, + // 后端服务器的监听端口,需要在1-65535之间 + BackendPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection/Hash + Scheduler: "RoundRobin", + // TCP设置链接超时时间,默认900秒,需要为10-4000之间的整数 + TcpSessionTimeout: 1000, +} +err := client.CreateTCPListener(BLBID, args) +if err != nil { + fmt.Println("create TCP Listener failed:", err) +} else { + fmt.Println("create TCP Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[CreateTCPListener创建TCP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#createtcplistener%E5%88%9B%E5%BB%BAtcp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新TCP监听器 + +通过以下代码,更新指定LoadBalancer下的TCP监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &blb.UpdateTCPListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 80, + // 更新负载均衡的算法 + Scheduler: "Hash", + // 更新tcp链接超时时间 + TcpSessionTimeout: 2000, +} +err := client.UpdateTCPListener(BLBID, args) +if err != nil { + fmt.Println("update TCP Listener failed:", err) +} else { + fmt.Println("update TCP Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[UpdateTCPListener更新TCP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatetcplistener%E6%9B%B4%E6%96%B0tcp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 查询TCP监听器 + +通过以下代码,查询指定LoadBalancer下所有TCP监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &blb.DescribeListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 80, +} +result, err := client.DescribeTCPListeners(BLBID, args) +if err != nil { + fmt.Println("describe TCP Listener failed:", err) +} else { + fmt.Println("describe TCP Listener success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeTCPListeners查询TCP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describetcplisteners%E6%9F%A5%E8%AF%A2tcp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 创建UDP监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于UDP协议的监听器,监听一个前端端口,将发往该端口的所有UDP流量,根据策略进行转发 +```go +args := &blb.CreateUDPListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 53, + // 后端服务器的监听端口,需要在1-65535之间 + BackendPort: 53, + // 负载均衡算法,支持RoundRobin/LeastConnection/Hash + Scheduler: "RoundRobin", + // 健康检查字符串 健康发送的请求字符串,后端服务器收到后需要进行应答,支持16进制\00-\FF和标准ASCII字符串,最大长度1299 + HealthCheckString: "\00\01\01\00\00\01\00\00\00\00\00\00\05baidu\03com\00\00\01\00\01" +} +err := client.CreateUDPListener(BLBID, args) +if err != nil { + fmt.Println("create UDP Listener failed:", err) +} else { + fmt.Println("create UDP Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[CreateUDPListener创建UDP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#createudplistener%E5%88%9B%E5%BB%BAudp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新UDP监听器 + +通过以下代码,更新指定LoadBalancer下的UDP监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &blb.UpdateUDPListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 53, + // 更新负载均衡的算法 + Scheduler: "Hash", +} +err := client.UpdateUDPListener(BLBID, args) +if err != nil { + fmt.Println("update UDP Listener failed:", err) +} else { + fmt.Println("update UDP Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[UpdateUDPListener更新UDP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updateudplistener%E6%9B%B4%E6%96%B0udp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 查询UDP监听器 + +通过以下代码,查询指定LoadBalancer下所有UDP监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &blb.DescribeListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 53, +} +result, err := client.DescribeUDPListeners(BLBID, args) +if err != nil { + fmt.Println("describe UDP Listener failed:", err) +} else { + fmt.Println("describe UDP Listener success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeUDPListeners查询UDP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describeudplisteners%E6%9F%A5%E8%AF%A2udp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 创建HTTP监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于HTTP协议的监听器,监听一个前端端口,将发往该端口的所有HTTP请求,根据策略转发到后端服务器监听的后端端口上 +```go +args := &blb.CreateHTTPListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 80, + // 后端服务器的监听端口,需要在1-65535之间 + BackendPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection + Scheduler: "RoundRobin", +} +err := client.CreateHTTPListener(BLBID, args) +if err != nil { + fmt.Println("create HTTP Listener failed:", err) +} else { + fmt.Println("create HTTP Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[CreateHTTPListener创建HTTP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#createhttplistener%E5%88%9B%E5%BB%BAhttp%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新HTTP监听器 + +通过以下代码,更新指定LoadBalancer下的HTTP监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &blb.UpdateHTTPListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 80, + // 更新负载均衡的算法 + Scheduler: "LeastConnection", + // 开启会话保持功能 + KeepSession: true, +} +err := client.UpdateHTTPListener(BLBID, args) +if err != nil { + fmt.Println("update HTTP Listener failed:", err) +} else { + fmt.Println("update HTTP Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[更新HTTP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatehttplistener%E6%9B%B4%E6%96%B0http%E7%9B%91%E5%90%AC%E5%99%A8) + +### 查询HTTP监听器 + +通过以下代码,查询指定LoadBalancer下所有HTTP监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &blb.DescribeListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 80, +} +result, err := client.DescribeHTTPListeners(BLBID, args) +if err != nil { + fmt.Println("describe HTTP Listener failed:", err) +} else { + fmt.Println("describe HTTP Listener success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeHTTPListeners查询HTTP监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describehttplisteners%E6%9F%A5%E8%AF%A2http%E7%9B%91%E5%90%AC%E5%99%A8) + +### 创建HTTPS监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于HTTPS协议的监听器,监听一个前端端口,将发往该端口的所有HTTPS请求,先通过SSL卸载转换为HTTP请求后,再根据策略转发到后端服务器监听的后端端口上 +```go +args := &blb.CreateHTTPSListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 443, + // 后端服务器的监听端口,需要在1-65535之间 + BackendPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection + Scheduler: "RoundRobin", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.CreateHTTPSListener(BLBID, args) +if err != nil { + fmt.Println("create HTTPS Listener failed:", err) +} else { + fmt.Println("create HTTPS Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[CreateHTTPSListener创建HTTPS监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#createhttpslistener%E5%88%9B%E5%BB%BAhttps%E7%9B%91%E5%90%AC%E5%99%A8) + +### 更新HTTPS监听器 + +通过以下代码,更新指定LoadBalancer下的HTTPS监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &blb.UpdateHTTPSListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 443, + // 更新负载均衡的算法 + Scheduler: "LeastConnection", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.UpdateHTTPSListener(BLBID, args) +if err != nil { + fmt.Println("update HTTPS Listener failed:", err) +} else { + fmt.Println("update HTTPS Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[UpdateHTTPSListener更新HTTPS监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatehttpslistener%E6%9B%B4%E6%96%B0https%E7%9B%91%E5%90%AC%E5%99%A8) + + +### 查询HTTPS监听器 + +通过以下代码,查询指定LoadBalancer下所有HTTPS监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &blb.DescribeListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 443, +} +result, err := client.DescribeHTTPSListeners(BLBID, args) +if err != nil { + fmt.Println("describe HTTPS Listener failed:", err) +} else { + fmt.Println("describe HTTPS Listener success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeHTTPSListeners查询HTTPS监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describehttpslisteners%E6%9F%A5%E8%AF%A2https%E7%9B%91%E5%90%AC%E5%99%A8) + + + +### 创建SSL监听器 + +通过以下代码,在指定LoadBalancer下,创建一个基于SSL协议的blb监听器,监听一个前端端口,将发往该端口的所有SSL流量,根据策略进行转发 +```go +args := &blb.CreateSSLListenerArgs{ + // 监听器监听的端口,需要在1-65535之间 + ListenerPort: 443, + // 后端服务器的监听端口,需要在1-65535之间 + BackendPort: 80, + // 负载均衡算法,支持RoundRobin/LeastConnection/Hash + Scheduler: "RoundRobin", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.CreateSSLListener(BLBID, args) +if err != nil { + fmt.Println("create SSL Listener failed:", err) +} else { + fmt.Println("create SSL Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[CreateSSLListener创建SSL监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#createssllistener%E5%88%9B%E5%BB%BAssl%E7%9B%91%E5%90%AC%E5%99%A8) + + + +### 更新SSL监听器 + +通过以下代码,更新指定LoadBalancer下的SSL监听器参数,所有请求参数中指定的域都会被更新,未指定的域保持不变,监听器通过端口指定 +```go +args := &blb.UpdateSSLListenerArgs{ + // 要更新的监听器端口号 + ListenerPort: 443, + // 更新负载均衡的算法 + Scheduler: "LeastConnection", + // 配置证书列表 + CertIds: []string{certId}, +} +err := client.UpdateSSLListener(BLBID, args) +if err != nil { + fmt.Println("update SSL Listener failed:", err) +} else { + fmt.Println("update SSL Listener success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[UpdateSSLListener更新SSL监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#updatessllistener%E6%9B%B4%E6%96%B0ssl%E7%9B%91%E5%90%AC%E5%99%A8) + + +### 查询SSL监听器 + +通过以下代码,查询指定LoadBalancer下所有SSL监听器的信息,支持按监听器端口进行匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 +```go +args := &blb.DescribeListenerArgs{ + // 要查询的监听器端口 + ListenerPort: 443, +} +result, err := client.DescribeSSLListeners(BLBID, args) +if err != nil { + fmt.Println("describe SSL Listener failed:", err) +} else { + fmt.Println("describe SSL Listener success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DescribeSSLListeners查询SSL监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#describessllisteners%E6%9F%A5%E8%AF%A2ssl%E7%9B%91%E5%90%AC%E5%99%A8) + + +### 删除监听器 + +通过以下代码,释放指定LoadBalancer下的监听器,监听器通过监听端口来指定,支持批量释放 +```go +args := &blb.DeleteListenersArgs{ + ClientToken: "be31b98c-5e41-4838-9830-9be700de5a20", + // 要删除的监听器监听的端口 + PortList: []uint16{80, 443}, +} +err := client.DeleteListeners(BLBID, args) +if err != nil { + fmt.Println("delete Listeners failed:", err) +} else { + fmt.Println("delete Listeners success: ") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考BLB API 文档[DeleteListeners释放监听器](https://cloud.baidu.com/doc/BLB/s/yjwvxnvl6#deletelisteners%E9%87%8A%E6%94%BE%E7%9B%91%E5%90%AC%E5%99%A8) + + +# 错误处理 + +GO语言以error类型标识错误,BLB支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | BLB服务返回的错误 + +用户使用SDK调用BLB相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// blbClient 为已创建的BLB Client对象 +blbDetail, err := blbClient.DescribeLoadBalancerDetail(blbId) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get blb detail success: ", blbDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向BLB发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当BLB服务端出现异常时,BLB服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BLB错误返回](https://cloud.baidu.com/doc/BLB/s/Djwvxnzw6) + +# 版本变更记录 + +## v0.9.11 [2020-05-20] + +首次发布: + + - 创建、查看、列表、更新、删除普通型BLB实例 + - 创建、列表、更新、删除后端RS,并支持查询后端服务器健康检查状态 + - 创建、查看、更新、删除监听器端口,支持TCP/UDP/HTTP/HTTPS/SSL协议 diff --git a/bce-sdk-go/doc/BLS.md b/bce-sdk-go/doc/BLS.md new file mode 100644 index 0000000..dc853c9 --- /dev/null +++ b/bce-sdk-go/doc/BLS.md @@ -0,0 +1,872 @@ +# BLS服务 + +# 概述 + +本文档主要介绍BLS GO SDK的使用。在使用本文档前,您需要先了解BLS的一些基本知识,并已开通了BLS服务。若您还不了解BLS,可以参考[产品描述](https://cloud.baidu.com/doc/BLS/index.html)和[入门指南](https://cloud.baidu.com/doc/BLS/s/Gjwvyjbvg)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BLS访问域名](https://cloud.baidu.com/doc/BLS/s/4k8qysj2z)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx)。 + +目前支持“华北-北京”和“华南-广州”两个区域。北京区域:`bls-log.bj.baidubce.com`广州区域:`bls-log.gz.baidubce.com`。对应信息为: + +| 访问区域 | 对应Endpoint | Protocol | +| --------- | ----------------------- | ---------- | +| 华北-北京 | bls-log.bj.baidubce.com | HTTP/HTTPS | +| 华南-广州 | bls-log.gz.baidubce.com | HTTP/HTTPS | + +## 获取密钥 + +要使用百度云BLS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BLS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BLS Client + +BLS Client是BLS服务的客户端,为开发者与BLS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BLS Client + +通过AK/SK方式访问BLS,用户可以参考如下代码新建一个BLS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bls" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + AK, SK := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BLSClient + blsClient, err := bls.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`AK`对应控制台中的“Access Key ID”,`SK`对应控制台中的“Secret Access Key”,获取方式请参考《通用参考 [获取AKSK](https://cloud.baidu.com/doc/Reference/s/jjwvz2e3p)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BLS的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://bls-log.bj.baidubce.com`。 + +### 使用STS创建BLS Client + +**申请STS token** + +BLS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BLS,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建BLS Client** + +申请好STS后,可将STS Token配置到BLS Client中,从而实现通过STS Token创建BLS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BLS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/bls" //导入BLS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BLS服务的Client对象,Endpoint使用默认值 + blsClient, err := bls.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create bls client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + blsClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BLS Client时,无论对应BLS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问BLS + +BLS支持HTTPS传输协议,您可以通过在创建BLS Client对象时指定的Endpoint中指明HTTPS的方式,在BLS GO SDK中使用HTTPS访问BLS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bls" + +ENDPOINT := "https://bls-log.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +blsClient, _ := bls.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BLS Client + +如果用户需要配置BLS Client的一些细节的参数,可以在创建BLS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BLS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bls" + +//创建BLS Client对象 +AK, SK := , +ENDPOINT := "bls-log.bj.baidubce.com" +blsClient, _ := bls.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +blsClient.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bls" + +AK, SK := , +ENDPOINT := "bls-log.bj.baidubce.com" +blsClient, _ := bls.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +blsClient.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +blsClient.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bls" + +AK, SK := , +ENDPOINT := "bls-log.bj.baidubce.com" +blsClient, _ := bls.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +blsClient.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +blsClient.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BLS时,创建的BLS Client对象的`Config`字段支持的所有参数如下表所示: + +| 配置项名称 | 类型 | 含义 | +| ------------------------- | --------------------- | -------------------------------------- | +| Endpoint | string | 请求服务的域名 | +| ProxyUrl | string | 客户端请求的代理地址 | +| Region | string | 请求资源的区域 | +| UserAgent | string | 用户名称,HTTP请求的User-Agent头 | +| Credentials | \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 | +| SignOption | \*auth.SignOptions | 认证字符串签名选项 | +| Retry | RetryPolicy | 连接重试策略 | +| ConnectionTimeoutInMillis | int | 连接超时时间,单位毫秒,默认20分钟 | + +> 说明: +> +> 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BLS Client”小节。 +> 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: +> +> | 名称 | 类型 | 含义 | +> | ------------- | ------------------- | ------------------------------------------------------ | +> | HeadersToSign | map[string]struct{} | 生成签名字符串时使用的HTTP头 | +> | Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 | +> | ExpireSeconds | int | 签名字符串的有效期 | +> +> 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +> +> 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +# 主要接口 + +用户可以通过 API 的方式管理 BLS 日志集、写入、下载、查询和分析日志数据等操作。 + +## LogStore操作 + +### 创建LogStore + +创建日志集,命名日志组时,需遵循以下准则: + +- 每个账户每个区域日志集名称不能重复 +- 日志集名称长度不能超过 128 个字符 +- 日志集名称包含的字符仅限于: `a-z, A-Z, 0-9, '_', '-', '.'` + +通过以下代码,创建一个LogStore并指定其存储期限。 + +```go +err := blsClient.CreateLogStore("demo", 3) +if err != nil { + fmt.Println("Create logStore failed: ", err) +} else { + fmt.Println("Create logStore success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[CreateLogStore](https://cloud.baidu.com/doc/BLS/s/pk8to0k59) + +### 更新指定LogStore + +通过以下代码,更新指定的日志集,目前仅支持更改与日志集关联的存储期限。 + +```go +err := blsClient.UpdateLogStore("demo", 5) +if err != nil { + fmt.Println("Update logStore failed: ", err) +} else { + fmt.Println("Update logStore success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[UpdateLogStore](https://cloud.baidu.com/doc/BLS/s/ok8to0kla) + +### 查询指定LogStore + +通过以下代码,获取指定日志集的详情信息。 + +```go +res, err := blsClient.DescribeLogStore("demo") +if err != nil { + fmt.Println("Get logStore failed: ", err) +} else { + fmt.Println("LogStore info: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DescribeLogStore](https://cloud.baidu.com/doc/BLS/s/Bk8to0jp3) + +### 获取LogStore列表 + +通过以下代码,获取当前用户的日志集列表。 + +```go +// 可选参数列表 +args := &api.QueryConditions{ + NamePattern: "bls-log", + Order: "asc", + OrderBy: "creationDateTime", + PageNo: 1, + PageSize: 10} +res, err := blsClient.ListLogStore(args) +if err != nil { + fmt.Println("Get logStore list failed: ", err) +} else { + fmt.Println("List logStore success: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[ListLogStore](https://cloud.baidu.com/doc/BLS/s/Hk8to0kda) + +### 删除LogStore + +通过以下代码,删除指定的日志集,并且会永久删除与其关联的所有已存储日志记录。 + +```go +err := blsClient.DeleteLogStore("demo") +if err != nil { + fmt.Println("Delete logStore failed: ", err) +} else { + fmt.Println("Delete logStore success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DeleteLogStore](https://cloud.baidu.com/doc/BLS/s/ak8to0jx8) + +## LogStream操作 + +LogStream会随着LogStore的创建自动创建,目前暂不支持对LogStream的删除操作。 + +### 获取LogStream列表 + +通过以下代码,获取指定日志集的日志流列表。 + +```go +// 可选参数列表 +args := &api.QueryConditions{ + NamePattern: "bls-log", + Order: "desc", + OrderBy: "creationDateTime", + PageNo: 1, + PageSize: 20, +} +res, err := blsClient.ListLogStore(args) +if err != nil { + fmt.Println("Get logStream list failed: ", err) +} else { + fmt.Println("List logStore success: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[ListLogStream](https://cloud.baidu.com/doc/BLS/s/dk8to0lhy) + +## LogRecord操作 + +### 推送LogRecord + +支持批量推送日志记录到 BLS 平台,日志记录的格式可以是 TEXT,也可以是 JSON 格式。如果是 TEXT,则不对日志进行解析;如果是 JSON 格式,可以自动发现 JSON 字段(仅支持首层字段发现,暂不支持嵌套类型字段的自动发现)。 + +如果既想上传日志原文,又想上传解析出的具体字段,可以使用 JSON 格式进行上传,并在 JSON 中包含日志原文(使用 @raw 作为key,日志原文作为 value)。 BLS 解析到 @raw 的时候,会将其内容作为日志原文处理。 + +通过以下代码,可以批量推送JSON日志记录到指定日志集的指定日志流中。 + +```go +// 推送JSON格式日志记录 +jsonRecords := []api.LogRecord{ + { + Message: "{\"body_bytes_sent\":184,\"bytes_sent\":398,\"client_ip\":\"120.193.204.39\"}", + Timestamp: time.Now().UnixNano() / 1e6, + Sequence: 1, + }, + { + Message: "{\"body_bytes_sent\":14,\"bytes_sent\":408,\"client_ip\":\"120.193.222.39\"}", + Timestamp: time.Now().UnixNano() / 1e6, + Sequence: 2, + }, +} +// 指定logRecord类型为JSON,并将日志记录推送到日志集demo中的日志流json-logStream中 +// 若没有该日志流,则自动创建 +err := blsClient.PushLogRecord("demo", "json-logStream", "JSON", jsonRecords) +if err != nil { + fmt.Println("Push logRecords failed: ", err) +} else { + fmt.Println("Push logRecords success") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[PushLogRecord](https://cloud.baidu.com/doc/BLS/s/dk8to0ktn) + +### 查看指定LogRecord + +通过以下代码,查看指定日志流中的日志记录,您可以获取最近的日志记录或使用时间范围进行过滤。 + +```go +args := &api.PullLogRecordArgs{ + // 必须指定日志流名称 + LogStreamName: "json-logStream", + // 可选参数 + StartDateTime: "2021-01-01T10:11:44Z", + EndDateTime: "2021-12-10T16:11:44Z", + Limit: 500, // 返回最大条目数 + Marker: "", // 指定查看的位置标记 +} +res, err := blsClient.PullLogRecord("demo", args) +if err != nil { + fmt.Println("Pull logRecord failed: ", err) +} else { + fmt.Println("LogRecords result: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[PullLogRecord](https://cloud.baidu.com/doc/BLS/s/Ek8to0l1o) + +### 查询指定LogRecord + +用户通过提交 Query 检索或分析指定日志集中的数据,每次只能查询一个日志集的内容。 + +Query 语句格式支持 检索 + SQL分析,通过竖线分隔,即在检索的结果集上执行 SQL,形如:`Search | SQL`。 + +例如 `method:GET and status >= 400 | select host, count(*) group by host` + +注: + +- 如果只需要检索原日志,不需要执行 SQL 分析,可以省略竖线和 SQL 语句。 +- 如果不需要检索,只需要 SQL 分析,那么检索语句可以写为 `*`,表示匹配所有记录。即 `* | SQL`。如果查询的日志集没有开启索引,也可以省略检索语句和竖线,只写 SQL 语句。 + +查询相关限制如下: + +- 每个账户支持最多的查询并发数是 15 个 +- 限制返回的结果集大小不超过 1MB 或 1000 条记录。 + +检索语法请参考 [检索语法](https://cloud.baidu.com/doc/BLS/s/Okbta3asp) + +SQL 语句中可以不包括 from 子句,语法详情可以参考 [SQL 语法](https://cloud.baidu.com/doc/BLS/s/xk5cc9piu) + +通过以下代码,您可以在指定日志集中查询满足条件的日志记录。 + +```go +args := &api.QueryLogRecordArgs{ + // 必选参数 + Query: "select count(*)", // 查询SQL + StartDateTime: "2021-01-01T10:11:44Z", + EndDateTime: "2021-12-10T16:11:44Z", + // 可选参数 + LogStreamName: "json-logStream", // 不指定则在日志集所有日志流中查询 + Limit: 100, +} +res, err := blsClient.QueryLogRecord("demo", args) +if err != nil { + fmt.Println("Query logRecord failed: ", err) +} else { + fmt.Println("LogRecords result: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[QueryLogRecord](https://cloud.baidu.com/doc/BLS/s/hk8to0l9o) + +## FastQuery操作 + +### 创建FastQuery + +创建快速查询的实例名称必须遵循以下准则: + +- 每个账户每个区域快速查询名称不能相同 +- 快速查询名称长度不能超过128个字符 +- 快速查询名称包含的字符仅限于:`a-z, A-Z, 0-9, '_', '-', '.'` + +通过以下代码,可以创建一个快速查询。 + +```go +args := &api.CreateFastQueryBody{ + FastQueryName: "macro", + Query: "select count(*)", + LogStoreName: "demo", + // 可选参数 + Description: "calculate record number", + LogStreamName: "json-logStream", +} +err := blsClient.CreateFastQuery(args) +if err != nil { + fmt.Println("Create fastQuery failed: ", err) +} else { + fmt.Println('Create fastQuery success.') +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[CreateFastQuery](https://cloud.baidu.com/doc/BLS/s/kk8to0m6g) + +### 获取指定FastQuery + +通过以下代码,获取指定名称的快速查询的详细信息。 + +```go +res, err := blsClient.DescribeFastQuery("macro") +if err != nil { + fmt.Println("Get fastQuery failed: ", err) +} else { + fmt.Println("Fastquery info: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DescribeFastQuery](https://cloud.baidu.com/doc/BLS/s/Zk8to0mmn) + +### 更新指定FastQuery + +通过以下代码,更新指定名称的快速查询实例信息。 + +```go +args := &api.UpdateFastQueryBody{ + LogStoreName: "demo", + // 可选参数 + Query: "select * limit 3", + Description: "Top 3", + LogStreamName: "", +} +err := blsClient.UpdateFastQuery("macro", args) +if err != nil { + fmt.Println("Update fastQuery failed: ", err) +} else { + fmt.Println("Update fastQuery success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[UpdateFastQuery](https://cloud.baidu.com/doc/BLS/s/Ik8to0mei) + +### 获取FastQuery列表 + +通过以下代码,获取当前用户保存的快速查询列表。 + +```go +// 可选参数列表 +args := &api.QueryConditions{ + NamePattern: "m", + Order: "desc", + OrderBy: "", + PageNo: 1, + PageSize: 20, +} +res, err := blsClient.ListFastQuery(args) +if err != nil { + fmt.Println("List fastQuery failed: ", err) +} else { + fmt.Println("FastQuery list: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[ListFastQuery](https://cloud.baidu.com/doc/BLS/s/0k8to0lyf) + +### 删除指定FastQuery + +通过以下代码,删除指定名称的快速查询示例。 + +```go +err := blsClient.DeleteFastQuery("macro") +if err != nil { + fmt.Println("Delete fastQuery failed: ", err) +} else { + fmt.Println("Delete fastQuery success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DeleteFastQuery](https://cloud.baidu.com/doc/BLS/s/Uk8to0lqd) + +## Index操作 + +### 创建Index + +通过以下代码,为指定的日志集创建索引。 + +```go +indexMappings := map[string]api.LogField{ + "age": { + Type: "long", + }, + "salary": { + Type: "text", + }, + "name": { + Type: "text", + }, +} +err := blsClient.CreateIndex("demo", true, indexMappings) // true表示索引开启状态 +if err != nil { + fmt.Println("Create index failed: ", err) +} else { + fmt.Println("Create index success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[CreateIndex](https://cloud.baidu.com/doc/BLS/s/dkbt4q6ps) + +### 更新指定Index + +通过以下代码,更新指定日志集的索引结构。 + +```go +indexMappings := map[string]api.LogField{ + "age": { + Type: "long", + }, + "wage": { + Type: "float", + }, + "name": { + Type: "text", + }, +} +err := blsClient.UdpateIndex("demo", true, indexMappings) +if err != nil { + fmt.Println("Update index failed: ", err) +} else { + fmt.Println("Update index success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[UpdateIndex](https://cloud.baidu.com/doc/BLS/s/bkbt4w0fe) + +### 获取指定Index + +通过以下代码,获取指定日志集的索引结构。 + +```go +res, err := blsClient.DescribeIndex("demo") +if err != nil { + fmt.Println("Get index failed: ", err) +} else { + fmt.Println("Index info: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DescribeIndex](https://cloud.baidu.com/doc/BLS/s/1kbt4yem2) + +### 删除指定Index + +通过以下代码,删除指定日志集的索引,该操作会将索引数据清空。 + +```go +res, err := blsClient.DeleteIndex("demo") +if err != nil { + fmt.Println("Delete index failed: ", err) +} else { + fmt.Println("Delete index success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DeleteIndex](https://cloud.baidu.com/doc/BLS/s/bkbt56uvu) + +## LogShipper操作 + +### 创建LogShipper + +创建投递任务,需要遵循以下准则: + +- 每个日志集可以创建多个投递任务 +- 总投递任务上限为300 +- 投递任务名称,最长63个字符,包含字母、数字、-和_ +- 投递开始时间,最早为前180天,最迟为后24小时,默认为任务创建时间为开始时间,格式为ISO8601 + +```go +args := &api.CreateLogShipperBody{ + LogShipperName: "demo", + LogStoreName: "store", + StartTime: "2021-07-06T19:01:00Z", + DestConfig: &api.ShipperDestConfig{ + BOSPath: "bucket_1/demo/", + }, +} +id, err := blsClient.CreateLogShipper(args) +if err != nil { + fmt.Println("Create LogShipper failed: ", err) +} else { + fmt.Printf("Create LogShipper %s success.", id) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[CreateLogShipper](https://cloud.baidu.com/doc/BLS/s/Skref348s) + +### 更新指定LogShipper + +通过以下代码,更新指定的投递任务,目前不支持更改投递任务的日志集、起始时间和目的类型。 + +```go +args := &api.UpdateLogShipperBody{ + LogShipperName: "shipper-sdk", + DestConfig: &api.ShipperDestConfig{ + PartitionFormatLogStream: true, + MaxObjectSize: 50, + CompressType: "snappy", + DeliverInterval: 30, + StorageFormat: "json", + }, +} +err := blsClient.UpdateLogShipper("logShipperID", args) +if err != nil { + fmt.Println("Update LogShipper failed: ", err) +} else { + fmt.Println("Update LogShipper success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[UpdateLogShipper](https://cloud.baidu.com/doc/BLS/s/ukrektd01) + +### 查询指定LogShipper + +通过以下代码,获取指定投递任务的详情信息。 + +```go +res, err := blsClient.GetLogShipper("logShipperID") +if err != nil { + fmt.Println("Get LogShipper failed: ", err) +} else { + fmt.Println("LogShipper info: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[GetLogShipper](https://cloud.baidu.com/doc/BLS/s/xkrekxc8z) + +### 获取LogShipper列表 + +通过以下代码,查看符合查询条件的投递任务。 + +```go +args := &api.ListLogShipperCondition{ + LogShipperID: "logShipperID", + LogStoreName: "demo*", + Status: "Running", +} +res, err := blsClient.ListLogShipper(args) +if err != nil { + fmt.Println("Get LogShipper list failed: ", err) +} else { + fmt.Println("List LogShipper success: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[ListLogShipper](https://cloud.baidu.com/doc/BLS/s/bkrekyq51) + +### 查看LogShipper执行记录 + +通过以下代码,查看投递任务的执行记录。 + +```go +args := &api.ListShipperRecordCondition{ + SinceHours: 20 * 24, +} +res, err := blsClient.ListLogShipperRecord("logShipperID", args) +if err != nil { + fmt.Println("Get LogShipper record failed: ", err) +} else { + fmt.Println("Get LogShipper record success: ", res) +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[ListLogShipperRecord](https://cloud.baidu.com/doc/BLS/s/dkrel0hiy) + +### 启停LogShipper + +#### 单个启停 + +通过以下代码,启停指定的投递任务。 + +```go +args := &api.SetSingleShipperStatusCondition{DesiredStatus: "Paused"} +err := blsClient.SetSingleLogShipperStatus("logShipperID", args) +if err != nil { + fmt.Println("Set LogShipper status failed: ", err) +} else { + fmt.Println("Set LogShipper status success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[SetSingleLogShipperStatus](https://cloud.baidu.com/doc/BLS/s/dkrel1tsv) + +#### 批量启停 + +通过以下代码,批量启停投递任务。 + +```go +args := &api.BulkSetShipperStatusCondition{ + LogShipperIDs: []string{"id1_to_set", "id2_to_set"}, + DesiredStatus: "Paused", +} +err := blsClient.BulkSetLogShipperStatus(args) +if err != nil { + fmt.Println("Bulk set LogShipper status failed: ", err) +} else { + fmt.Println("Bulk set LogShipper status success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[BulkSetLogShipperStatus](https://cloud.baidu.com/doc/BLS/s/6krel2nl8) + +### 删除LogShipper + +#### 单个删除 + +通过以下代码,删除指定的投递任务。 + +```go +err := blsClient.DeleteSingleLogShipper("logShipperID") +if err != nil { + fmt.Println("Delete LogShipper failed: ", err) +} else { + fmt.Println("Delete LogShipper success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[DeleteSingleLogShipper](https://cloud.baidu.com/doc/BLS/s/1krel3v47) + +#### 批量删除 + +通过一下代码,批量删除投递任务。 + +```go +ids := []string{"id1_to_del", "id2_to_del"} +args := &api.BulkDeleteShipperCondition{LogShipperIDs:ids} +err := blsClient.BulkDeleteLogShipper("logShipperID") +if err != nil { + fmt.Println("Bulk delete LogShipper failed: ", err) +} else { + fmt.Println("Bulk delete LogShipper success.") +} +``` + +> **提示:** +> +> - 详细的参数配置及限制条件,可以参考BLS API 文档[BulkDeleteLogShipper](https://cloud.baidu.com/doc/BLS/s/Ykrel4g5f) + diff --git a/bce-sdk-go/doc/BOS.md b/bce-sdk-go/doc/BOS.md new file mode 100644 index 0000000..592054d --- /dev/null +++ b/bce-sdk-go/doc/BOS.md @@ -0,0 +1,1986 @@ +# BOS服务 + +# 概述 + +本文档主要介绍BOS GO SDK的使用。在使用本文档前,您需要先了解BOS的一些基本知识,并已开通了BOS服务。若您还不了解BOS,可以参考[产品描述](https://cloud.baidu.com/doc/BOS/ProductDescription.html)和[入门指南](https://cloud.baidu.com/doc/BOS/GettingStarted-new.html)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BOS访问域名](https://cloud.baidu.com/doc/BOS/DevRef.html#BOS.E8.AE.BF.E9.97.AE.E5.9F.9F.E5.90.8D)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/Regions.html)。 + +目前支持“华北-北京”、“华南-广州”和“华东-苏州”三个区域。北京区域:`http://bj.bcebos.com`,广州区域:`http://gz.bcebos.com`,苏州区域:`http://su.bcebos.com`。对应信息为: + +访问区域 | 对应Endpoint +---|--- +BJ | bj.bcebos.com +GZ | gz.bcebos.com +SU | su.bcebos.com + +## 获取密钥 + +要使用百度云BOS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BOS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BOS Client + +BOS Client是BOS服务的客户端,为开发者与BOS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BOS Client + +通过AK/SK方式访问BOS,用户可以参考如下代码新建一个BOS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bos" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BosClient + bosClient, err := bos.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BOS/GettingStarted.html#.E7.AE.A1.E7.90.86ACCESSKEY)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BOS的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://bj.bcebos.com`。 + +### 使用STS创建BOS Client + +**申请STS token** + +BOS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问BOS,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/BOS/API.html#STS.E7.AE.80.E4.BB.8B)。 + +**用STS token新建BOS Client** + +申请好STS后,可将STS Token配置到BOS Client中,从而实现通过STS Token创建BOS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建BOS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/bos" //导入BOS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建BOS服务的Client对象,Endpoint使用默认值 + bosClient, err := bos.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create bos client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + bosClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置BOS Client时,无论对应BOS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问BOS + +BOS支持HTTPS传输协议,您可以通过在创建BOS Client对象时指定的Endpoint中指明HTTPS的方式,在BOS GO SDK中使用HTTPS访问BOS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos" + +ENDPOINT := "https://bj.bcebos.com" //指明使用HTTPS协议 +AK, SK := , +bosClient, _ := bos.NewClient(AK, SK, ENDPOINT) +``` + +## 配置BOS Client + +如果用户需要配置BOS Client的一些细节的参数,可以在创建BOS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问BOS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos" + +//创建BOS Client对象 +AK, SK := , +ENDPOINT := "bj.bcebos.com" +client, _ := bos.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos" + +AK, SK := , +ENDPOINT := "bj.bcebos.com" +client, _ := bos.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos" + +AK, SK := , +ENDPOINT := "bj.bcebos.com" +client, _ := bos.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问BOS时,创建的BOS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建BOS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# Bucket管理 + +Bucket既是BOS上的命名空间,也是计费、权限控制、日志记录等高级功能的管理实体。 + +- Bucket名称在所有区域中具有全局唯一性,且不能修改。 + +> **说明:** +> +> 百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/Regions.html)。 +> 目前支持“华北-北京”、“华南-广州”和“华东-苏州”三个区域。北京区域:`http://bj.bcebos.com`,广州区域:`http://gz.bcebos.com`,苏州区域:`http://su.bcebos.com`。 + +- 存储在BOS上的每个Object都必须包含在一个Bucket中。 +- 一个用户最多可创建100个Bucket,但每个Bucket中存放的Object的数量和大小总和没有限制,用户不需要考虑数据的可扩展性。 + +## Bucket权限管理 + +### 设置Bucket的访问权限 + +如下代码将Bucket的权限设置为了private。 + +```go +err := bosClient.PutBucketAclFromCanned(bucketName, "private") +``` + +用户可设置的CannedACL包含三个值:`private` 、`public-read` 、`public-read-write`,它们分别对应相关权限。具体内容可以参考BOS API文档 [使用CannedAcl方式的权限控制](https://cloud.baidu.com/doc/BOS/API.html#.4F.FA.21.55.58.27.F8.31.85.2D.01.55.89.10.A7.16)。 + +### 设置指定用户对Bucket的访问权限 + +BOS还可以实现设置指定用户对Bucket的访问权限,参考如下代码实现: + +```go +// import "github.com/baidubce/bce-sdk-go/bce" +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +// 1. 直接上传ACL文件流 +aclBodyStream := bce.NewBodyFromFile("") +err := bosClient.PutBucketAcl(bucket, aclBodyStream) + +// 2. 直接使用ACL json字符串 +aclString := `{ + "accessControlList":[ + { + "grantee":[{ + "id":"e13b12d0131b4c8bae959df4969387b8" //指定用户ID + }], + "permission":["FULL_CONTROL"] //指定用户权限 + } + ] +}` +err := bosClient.PutBucketAclFromString(bucket, aclString) + +// 3. 使用ACL文件 +err := bosClient.PutBucketAclFromFile(bucket, "") + +// 4. 使用ACL struct对象设置 +grantUser1 := api.GranteeType{""} +grantUser2 := api.GranteeType{""} +grant1 := api.GrantType{ + Grantee: []api.GranteeType{grantUser1}, + Permission: []string{"FULL_CONTROL"} +} +grant2 := api.GrantType{ + Grantee: []api.GranteeType{granteUser2}, + Permission: []string{"READ"} +} +grantArr := make([]api.GranteType) +grantArr = append(grantArr, grant1) +grantArr = append(grantArr, grant2) +args := &api.PutBucketAclArgs{grantArr} +err := bosClient.PutBucketAclFromStruct(bucketName, args) +``` + +> **注意:** +> Permission中的权限设置包含三个值:`READ`、`WRITE`、`FULL_CONTROL`,它们分别对应相关权限。具体内容可以参考BOS API文档 [上传ACL文件方式的权限控制](https://cloud.baidu.com/doc/BOS/API.html#.D4.56.61.2C.A5.B1.68.B6.42.32.3E.18.15.BD.CE.43)。 +> ACL规则比较复杂,直接编辑ACL的文件或JSON字符串比较困难,因此提供了第四种方式方便使用代码创建ACL规则。 + +### 设置更多Bucket访问权限 + +1. 通过设置referer白名单方式设置防盗链 + +```go +aclString := `{ + "accessControlList":[ + { + "grantee":[{"id":"*"]}, //指定用户ID为全部用户 + "permission":["FULL_CONTROL"], //指定用户权限 + "condition":[{"referer": {"stringEquals": "http://allowed-domain/"}}] + } + ] +}` +err := bosClient.PutBucketAclFromString(bucket, aclString) +``` + +2. 限制客户端IP访问,只允许部分客户端IP访问 + +```go +aclString := `{ + "accessControlList":[ + { + "grantee":[{"id":"*"]}, //指定用户ID为全部用户 + "permission":["READ"], //指定用户权限 + "condition":[{"ipAddress": ["ip-1", "ip-2"]}] + } + ] +}` +err := bosClient.PutBucketAclFromString(bucket, aclString) +``` + +### 设置STS临时token权限 + +对于通过STS方式创建的临时访问身份,管理员也可进行专门的权限设定。 + +STS的简介及设置临时权限的方式可参见[临时授权访问](https://cloud.baidu.com/doc/BOS/API.html#.E4.B8.B4.E6.97.B6.E6.8E.88.E6.9D.83.E8.AE.BF.E9.97.AE)。 + +使用BOS GO SDK设置STS临时token权限可参考如下示例: + +```go +// import "github.com/baidubce/bce-sdk-go/services/sts" + +AK, SK := , +stsClient, err := sts.NewClient(AK, SK) +aclString := `{ + "accessControlList":[ + { + "grantee":[{"id":"*"]}, //指定用户ID为全部用户 + "permission":["FULL_CONTROL"], //指定用户权限 + "condition":[{"referer": {"stringEquals": "http://allowed-domain/"}}] + } + ] +}` +//使用有效期为300秒且指定ACL的方式获取临时STS token +sts, err := stsClient.GetSessionToken(300, aclString) +``` + +### 查看Bucket的访问权限 + +用户可以通过如下接口查看Bucket的访问权限,注意:Bucket的访问权限不能删除,默认为私有。 + +```go +result, err := bosClient.GetBucketAcl(bucketName) +``` + +返回的结果对象的字段包含了访问权限的详细内容,具体定义如下: + +```go +type GetBucketAclResult struct { + AccessControlList []struct{ + Grantee []struct { + Id string + } + Permission []string + } + Owner struct { + Id string + } +} +``` + +## 查看Bucket所属的区域 + +Bucket Location即Bucket Region,百度云支持的各region详细信息可参见[区域选择说明](https://cloud.baidu.com/doc/Reference/Regions.html)。 + +如下代码可以获取该Bucket的Location信息: + +```go +location, err := bosClient.GetBucketLocation(bucketName) +``` + +## 新建Bucket + +如下代码可以新建一个Bucket: + +```go +// 新建Bucket的接口为PutBucket,需指定Bucket名称 +if loc, err := bosClient.PutBucket(); err != nil { + fmt.Println("create bucket failed:", err) +} else { + fmt.Println("create bucket success at location:", loc) +} +``` + +> **注意:** 由于Bucket的名称在所有区域中是唯一的,所以需要保证bucketName不与其他所有区域上的Bucket名称相同。 +> +> Bucket的命名有以下规范: +> - 只能包括小写字母,数字,短横线(-)。 +> - 必须以小写字母或者数字开头。 +> - 长度必须在3-63字节之间。 + +## 列举Bucket + +如下代码可以列出用户所有的Bucket: + +```go +if res, err := bosClient.ListBuckets(); err != nil { + fmt.Println("list buckets failed:", err) +} else { + fmt.Println("owner:", res.Owner) + for i, b := range res.Buckets { + fmt.Println("bucket", i) + fmt.Println(" Name:", b.Name) + fmt.Println(" Location:", b.Location) + fmt.Println(" CreationDate:", b.CreationDate) + } +} +``` + +## 删除Bucket + +如下代码可以删除一个Bucket: + +```go +err := bosClient.DeleteBucket(bucketName) +``` + +> **注意:** +> - 在删除前需要保证此Bucket下的所有Object已经已被删除,否则会删除失败。 +> - 在删除前确认该Bucket没有开通跨区域复制,不是跨区域复制规则中的源Bucket或目标Bucket,否则不能删除。 + +## 判断Bucket是否存在 + +若用户需要判断某个Bucket是否存在,则如下代码可以做到: + +```go +exists, err := bosClient.DoesBucketExist(bucketName) +if err == nil && exists { + fmt.Println("Bucket exists") +} else { + fmt.Println("Bucket not exists") +} +``` + + +> **注意:** +> 如果Bucket不为空(即Bucket中有Object存在),则Bucket无法被删除,必须清空Bucket后才能成功删除。 + + +# 文件管理 + +## 上传文件 + +在BOS中,用户操作的基本数据单元是Object。Object包含Key、Meta和Data。其中,Key是Object的名字;Meta是用户对该Object的描述,由一系列Name-Value对组成;Data是Object的数据。 + +BOS GO SDK提供了丰富的文件上传接口,可以通过以下方式上传文件: + +- 简单上传 +- 追加上传 +- 抓取上传 +- 分块上传 + +### 简单上传 + +BOS在简单上传的场景中,支持以指定文件形式、以数据流方式、以二进制串方式、以字符串方式执行Object上传,请参考如下代码: + +```go +// import "github.com/baidubce/bce-sdk-go/bce" + +// 从本地文件上传 +etag, err := bosClient.PutObjectFromFile(bucketName, objectName, fileName, nil) + +// 从字符串上传 +str := "test put object" +etag, err := bosClient.PutObjectFromString(bucketName, objectName, str, nil) + +// 从字节数组上传 +byteArr := []byte("test put object") +etag, err := bosClient.PutObjectFromBytes(bucketName, objectName, byteArr, nil) + +// 从文件上传 +body, err := bce.NewBodyFromFile(fileName) +etag, err := bosClient.PutObject(bucketName, objectName, body, nil) + +// 从数据流上传(分块编码上传) +reader, err := os.Open(fileName) +etag, err := bosClient.PutObjectFromStream(bucketName, objectName, reader, nil) + +// 使用基本接口,提供必需参数从数据流上传 +reader, err := os.Open(fileName) +body, err := bce.NewBodyFromSizedReader(reader, -1) +etag, err := bosClient.BasicPutObject(bucketName, objectName, body) +``` + +Object以文件的形式上传到BOS中,上述简单上传的接口支持不超过5GB的Object上传。在请求处理成功后,BOS会在Header中返回Object的ETag作为文件标识。 + +**设置文件元信息** + +文件元信息(Object Meta),是对用户在向BOS上传文件时,同时对文件进行的属性描述,主要分为分为两种:设置HTTP标准属性(HTTP Headers)和用户自定义的元信息。 + +***设定Object的Http Header*** + +BOS GO SDK本质上是调用后台的HTTP接口,因此用户可以在上传文件时自定义Object的Http Header。常用的http header说明如下: + +名称 | 描述 |默认值 +---|---|--- +Content-MD5 | 文件数据校验,设置后BOS会启用文件内容MD5校验,把您提供的MD5与文件的MD5比较,不一致会抛出错误 | 有 +Content-Type | 文件的MIME,定义文件的类型及网页编码,决定浏览器将以什么形式、什么编码读取文件。如没有指定,BOS则根据文件的扩展名自动生成,如文件没有扩展名则填默认值 | application/octet-stream +Content-Disposition | 指示MIME用户代理如何显示附加的文件,打开或下载,及文件名称 | 无 +Content-Length | 上传的文件的长度,超过流/文件的长度会截断,不足为实际值 | 流/文件的长度 +Expires| 缓存过期时间 | 无 +Cache-Control | 指定该Object被下载时的网页的缓存行为 | 无 + +参考代码如下: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.PutObjectArgs) + +// 设置上传内容的MIME类型 +args.ContentType = "text/javascript" + +// 设置上传内容的长度 +args.ContentLength = 1024 + +// 设置缓存过期时间 +args.Expires = "Mon, 19 Mar 2018 11:55:32 GMT" + +// 设置缓存行为 +args.CacheControl = "max-age=3600" + +etag, err := bosClient.PutObject(bucketName, objectName, bodyStream, args) +``` + +> 注意:用户上传对象时SDK会自动设置ContentLength和ContentMD5,用来保证数据的正确性。如果用户自行设定ContentLength,必须为大于等于0且小于等于实际对象大小的数值,从而上传截断部分的内容,为负数或大于实际大小均报错。 + +***用户自定义元信息*** + +BOS支持用户自定义元数据来对Object进行描述。如下代码所示: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.PutObjectArgs) + +// 设置用户自定义元数据 +args.UserMeta = map[string]string{ + "name1": "my-metadata1", + "name2": "my-metadata2", +} + +etag, err := bosClient.PutObject(bucketName, objectName, bodyStream, args) +``` + +> **提示:** +> - 在上面代码中,用户自定义了一个名字为“name1”和“name2”,值分别为“my-metadata1”和“my-metadata2”的元数据 +> - 当用户下载此Object的时候,此元数据也可以一并得到 +> - 一个Object可以有多个类似的参数,但所有的User Meta总大小不能超过2KB + +**上传Object时设置存储类型** + +BOS支持标准存储、低频存储和冷存储,上传Object并存储为低频存储类型通过指定StorageClass实现,三种存储类型对应的参数如下: + +存储类型 | 参数 +---|--- +标准存储 | STANDRAD +低频存储 | STANDARD_IA +冷存储 | COLD + +以低频存储为例,代码如下: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.PutObjectArgs) +args.StorageClass = api.STORAGE_CLASS_STANDARD_IA +etag, err := bosClient.PutObject(bucketName, objectName, bodyStream, args) +``` + +### 追加上传 + +上文介绍的简单上传方式,创建的Object都是Normal类型,用户不可再进行追加写,这在日志、视频监控、视频直播等数据复写较频繁的场景中使用不方便。 + +正因如此,百度云BOS特别支持了AppendObject,即以追加写的方式上传文件。通过AppendObject操作创建的Object类型为Appendable Object,可以对该Object追加数据。AppendObject大小限制为0~5G。当您的网络情况较差时,推荐使用AppendObject的方式进行上传,每次追加较小数据(如256kb)。 + +通过AppendObject方式上传示例代码如下: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.AppendObjectArgs) + +// 1. 原始接口上传,设置为低频存储,设置追加的偏移位置 +args.StorageClass = api.STORAGE_CLASS_STANDARD_IA +args.Offset = 1024 +res, err := bosClient.AppendObject(bucketName, objectName, bodyStream, args) + +// 2. 封装的简单接口,仅支持设置offset +res, err := bosClient.SimpleAppendObject(bucketName, objectName, bodyStream, offset) + +// 3. 封装的从字符串上传接口,仅支持设置offset +res, err := bosClient.SimpleAppendObjectFromString(bucketName, objectName, "abc", offset) + +// 4. 封装的从给出的文件名上传文件的接口,仅支持设置offset +res, err := bosClient.SimpleAppendObjectFromFile(bucketName, objectName, "", offset) + +fmt.Println(res.ETag) // 打印ETag +fmt.Println(res.ContentMD5) // 打印ContentMD5 +fmt.Println(res.NextAppendOffset) // 打印NextAppendOffset +``` + +### 抓取上传 + +BOS支持用户提供的url自动抓取相关内容并保存为指定Bucket的指定名称的Object。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.FetchObjectArgs) + +// 1. 原始接口抓取,设置为异步抓取模式 +args.FetchMode = api.FETCH_MODE_ASYNC +res, err := bosClient.FetchObject(bucket, object, url, args) + +// 2. 基本抓取接口,默认为同步抓取模式 +res, err := bosClient.BasicFetchObject(bucket, object, url) + +// 3. 易用接口,直接指定可选参数 +res, err := bosClient.SimpleFetchObject(bucket, object, url, + api.FETCH_MODE_ASYNC, api.STORAGE_CLASS_STANDARD_IA) + +fmt.Println(res.ETag) // 打印ETag +``` + +### 分块上传 + +除了通过简单上传几追加上传方式将文上传件到BOS以外,BOS还提供了另外一种上传模式 —— Multipart Upload。用户可以在如下的应用场景内(但不仅限于此),使用Multipart Upload上传模式,如: + +- 需要支持断点上传。 +- 上传超过5GB大小的文件。 +- 网络条件较差,和BOS的服务器之间的连接经常断开。 +- 需要流式地上传文件。 +- 上传文件之前,无法确定上传文件的大小。 + +BOS GO SDK提供了分块操作的控制参数: + +- MultipartSize:每个分块的大小,默认为10MB,最小不得低于5MB +- MaxParallel:分块操作的并发数,默认为10 + +下面的示例代码设置了分块的大小为20MB,并发数为100: + +``` +// import "github.com/baidubce/bce-sdk-go/services/bos" + +client := bos.NewClient(, , ) +client.MultipartSize = 20 * (1 << 10) +client.MaxParallel = 100 +``` + +除了上述参数外,还会对设置的每个分块数进行1MB对齐,同时限制是最大分块数目不得超过10000,如果分块较小导致分块数超过这个上限会自动调整分块大小。 + +下面将一步步介绍Multipart Upload的实现。假设有一个文件,本地路径为 `/path/to/file.zip`,由于文件比较大,将其分块传输到BOS中。 + +**初始化Multipart Upload** + +使用`BasicInitiateMultipartUpload`方法来初始化一个基本的分块上传事件: + +```go +res, err := bosClient.BasicInitiateMultipartUpload(bucketName, objectKey) +fmt.Println(res.UploadId) // 打印初始化分块上传后获取的UploadId +``` + +返回结果中含有 `UploadId` ,它是区分分块上传事件的唯一标识,在后面的操作中,我们将用到它。 + +***上传低频存储类型Object的初始化*** + +BOS GO SDK提供的`InitiateMultipartUpload`接口可以设置其他分块上传的相关参数,下面的代码初始化了低频存储的一个分块上传事件: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.InitiateMultipartUploadArgs) +args.StorageClass = api.STORAGE_CLASS_STANDARD_IA +res, err := bosClient.InitiateMultipartUpload(bucketName, objectKey, contentType, args) +fmt.Println(res.UploadId) // 打印初始化分块上传后获取的UploadId +``` + +***上传冷存储类型Object的初始化*** + +初始化低频存储的一个分块上传事件: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.InitiateMultipartUploadArgs) +args.StorageClass = api.STORAGE_CLASS_COLD +res, err := bosClient.InitiateMultipartUpload(bucketName, objectKey, contentType, args) +fmt.Println(res.UploadId) // 打印初始化分块上传后获取的UploadId +``` + +**上传分块** + +接着,把文件分块上传。 + +```go +// import "github.com/baidubce/bce-sdk-go/bce" +// import "github.com/baidubce/bce-sdk-go/services/bos" +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +file, _ := os.Open("/path/to/file.zip") + +// 分块大小按MULTIPART_ALIGN=1MB对齐 +partSize := (bosClient.MultipartSize + + bos.MULTIPART_ALIGN - 1) / bos.MULTIPART_ALIGN * bos.MULTIPART_ALIGN + +// 获取文件大小,并计算分块数目,最大分块数MAX_PART_NUMBER=10000 +fileInfo, _ := file.Stat() +fileSize := fileInfo.Size() +partNum := (fileSize + partSize - 1) / partSize +if partNum > bos.MAX_PART_NUMBER { // 超过最大分块数,需调整分块大小 + partSize = (fileSize + bos.MAX_PART_NUMBER + 1) / bos.MAX_PART_NUMBER + partSize = (partSize + bos.MULTIPART_ALIGN - 1) / bos.MULTIPART_ALIGN * bos.MULTIPART_ALIGN + partNum = (fileSize + partSize - 1) / partSize +} + +// 创建保存每个分块上传后的ETag和PartNumber信息的列表 +partEtags := make([]api.UploadInfoType) + +// 逐个分块上传 +for i := int64(1); i <= partNum; i++ { + // 计算偏移offset和本次上传的大小uploadSize + uploadSize := partSize + offset := partSize * (i - 1) + left := fileSize - offset + if left < partSize { + uploadSize = left + } + + // 创建指定偏移、指定大小的文件流 + partBody, _ := bce.NewBodyFromSectionFile(file, offset, uploadSize) + + // 上传当前分块 + etag, err := bosClient.BasicUploadPart(bucketName, objectKey, uploadId, int(i), partBody) + + // 保存当前分块上传成功后返回的序号和ETag + partEtags = append(partEtags, api.UploadInfoType{int(partNum), etag}) +} +``` + +上面代码的核心是调用 `BasicUploadPart` 方法来上传每一个分块,但是要注意以下几点: + +- BasicUploadPart 方法要求除最后一个Part以外,其他的Part大小都要大于等于5MB。但是该接口并不会立即校验上传Part的大小;只有当Complete Multipart Upload的时候才会校验。 +- 为了保证数据在网络传输过程中不出现错误,建议您在`BasicUploadPart`后,使用每个分块BOS返回的Content-MD5值分别验证已上传分块数据的正确性。当所有分块数据合成一个Object后,不再含MD5值。 +- Part号码的范围是1~10000。如果超出这个范围,BOS将返回InvalidArgument的错误码。 +- 每次上传Part之后,BOS的返回结果会包含一个 `PartETag`对象,它是上传块的ETag与块编号(PartNumber)的组合,在后续完成分块上传的步骤中会用到它,因此需要将其保存起来。一般来讲这些`PartETag` 对象将被保存到List中。 + +**完成分块上传** + +如下代码所示,完成分块上传: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +completeArgs := &api.CompleteMultipartUploadArgs{Parts: partEtags} +res, _ := bosClient.CompleteMultipartUploadFromStruct( + bucketName, objectKey, uploadId, completeArgs) + +// 输出结果对象的内容 +fmt.Println(res.Location) +fmt.Println(res.Bucket) +fmt.Println(res.Key) +fmt.Println(res.ETag) +``` + +上面代码中的 `partETags`是第二部中保存的partETag的列表,BOS收到用户提交的Part列表后,会逐一验证每个数据Part的有效性。当所有的数据Part验证通过后,BOS将把这些数据part组合成一个完整的Object。 + +**取消分块上传** + +用户可以使用abortMultipartUpload方法取消分块上传。 + +```go +bosClient.AbortMultipartUpload(bucketName, objectKey, uploadId) +``` + +**获取未完成的分块上传** + +用户可以使用 `ListMultipartUploads` 方法获取Bucket内未完成的分块上传事件。 + +```go +// 列出给定bucket下所有未完成的分块信息 +res, err := BasicListMultipartUploads(bucketName) + +// 输出返回结果状态信息 +fmt.Println(res.Bucket) +fmt.Println(res.Delimiter) +fmt.Println(res.Prefix) +fmt.Println(res.IsTruncated) +fmt.Println(res.KeyMarker) +fmt.Println(res.NextKeyMarker) +fmt.Println(res.MaxUploads) + +// 遍历所有未完成分块信息列表 +for _, multipartUpload := range res.Uploads { + fmt.Println("Key:", multipartUpload.Key, ", UploadId:", multipartUpload.UploadId) +} +``` + +> **注意:** +> 1. 默认情况下,如果Bucket中的分块上传事件的数目大于1000,则只会返回1000个Object,并且返回结果中IsTruncated的值为True,同时返回NextKeyMarker作为下次读取的起点。 +> 2. 若想返回更多分块上传事件的数目,可以使用KeyMarker参数分次读取。 + +**获取所有已上传的块信息** + +用户可以使用 `ListParts` 方法获取某个上传事件中所有已上传的块。 + +```go +// 使用基本接口列出当前上传成功的分块 +res, err := bosClient.BasicListParts(bucketName, objectKey, uploadId) + +// 使用原始接口提供参数,列出当前上传成功的最多100个分块 +args := new(api.ListPartsArgs) +args.MaxParts = 100 +res, err := bosClient.ListParts(bucketName, objectKey, uploadId, args) + +// 打印返回的状态结果 +fmt.Println(res.Bucket) +fmt.Println(res.Key) +fmt.Println(res.UploadId) +fmt.Println(res.Initiated) +fmt.Println(res.StorageClass) +fmt.Println(res.PartNumberMarker) +fmt.Println(res.NextPartNumberMarker) +fmt.Println(res.MaxParts) +fmt.Println(res.IsTruncated) + +// 打印分块信息 +for _, part := range res.Parts { + fmt.Println("PartNumber:", part.PartNumber, ", Size:", part.Size, + ", ETag:", part.ETag, ", LastModified:", part.LastModified) +} +``` + +> **注意:** +> 1. 默认情况下,如果Bucket中的分块上传事件的数目大于1000,则只会返回1000个Object,并且返回结果中IsTruncated的值为True,同时返回NextPartNumberMarker作为下次读取的起点。 +> 2. 若想返回更多分块上传事件的数目,可以使用PartNumberMarker参数分次读取。 + +上述示例是使用API依次实现,没有并发执行,如果需要加快速度需要用户实现并发上传的部分。为了方便用户使用,BOS Client特封装了分块上传的并发接口`UploadSuperFile`: + +- 接口:`UploadSuperFile(bucket, object, fileName, storageClass string) error` +- 参数: + - bucket: 上传对象的bucket的名称 + - object: 上传对象的名称 + - fileName: 本地文件名称 + - storageClass: 上传对象的存储类型,默认标准存储 +- 返回值: + - error: 上传过程中的错误,成功则为空 + +用户只需给出`bucket`、`object`、`filename`即可并发的进行分块上传,同时也可指定上传对象的`storageClass`。 + +## 下载文件 + +BOS GO SDK提供了丰富的文件下载接口,用户可以通过以下方式从BOS中下载文件: + +- 简单流式下载 +- 下载到本地文件 +- 范围下载 + +### 简单流式下载 + +用户可以通过如下代码将Object读取到一个流中: + +```go +// 提供Bucket和Object,直接获取一个对象 +res, err := bosClient.BasicGetObject(bucketName, objectName) + +// 获取ObjectMeta +meta := res.ObjectMeta + +// 获取Object的读取流(io.ReadCloser) +stream := res.Body + +// 确保关闭Object读取流 +defer stream.Close() + +// 调用stream对象的Read方法处理Object +... +``` + +> **注意:** +> 1. 上述接口的返回结果对象中包含了Object的各种信息,包含Object所在的Bucket、Object的名称、MetaData以及一个读取流。 +> 2. 可通过结果对象的ObjectMeta字段获取对象的元数据,它包含了Object上传时定义的ETag,Http Header以及自定义的元数据。 +> 3. 可通过结果对象的Body字段获取返回Object的读取流,通过操作读取流将Object的内容读取到文件或者内存中或进行其他操作。 + +### 下载到本地文件 + +用户可以通过如下代码直接将Object下载到指定文件: + +```go +err := bosClient.BasicGetObjectToFile(bucketName, objectName, "path-to-local-file") +``` + +### 范围下载 + +为了实现更多的功能,可以指定下载范围、返回header来实现更精细化地获取Object。如果指定的下载范围是0 - 100,则返回第0到第100个字节的数据,包括第100个,共101字节的数据,即[0, 100]。 + +```go +// 指定范围起始位置和返回header +responseHeaders := map[string]string{"ContentType": "image/gif"} +rangeStart = 1024 +rangeEnd = 2048 +res, err := bosClient.GetObject(bucketName, objectName, responseHeaders, rangeStart, rangeEnd) + +// 只指定起始位置start +res, err := bosClient.GetObject(bucketName, objectName, responseHeaders, rangeStart) + +// 不指定range +res, err := bosClient.GetObject(bucketName, objectName, responseHeaders) + +// 不指定返回可选头部 +res, err := bosClient.GetObject(bucketName, objectName, nil) +``` + +基于范围下载接口,用户可以据此实现文件的分段下载和断点续传。为了方便用户使用,BOS GO SDK封装了并发下载的接口`DownloadSuperFile`: + +- 接口:`DownloadSuperFile(bucket, object, fileName string) error` +- 参数: + - bucket: 下载对象所在bucket的名称 + - object: 下载对象的名称 + - fileName: 该对象保存到本地的文件名称 +- 返回值: + - error: 下载过程中的错误,成功则为空 + +该接口利用并发控制参数执行并发范围下载,直接下载到用户指定的文件中。 + +### 其他使用方法 + +**获取Object的存储类型** + +Object的storage class属性分为`STANDARD`(标准存储)、`STANDARD_IA`(低频存储)和`COLD`(冷存储),通过如下代码可以实现: + +```go +res, err := bosClient.GetObjectMeta(bucketName, objectName) +fmt.Println(res.StorageClass) +``` + +**只获取Object Metadata** + +通过GetObjectMeta方法可以只获取Object Metadata而不获取Object的实体。如下代码所示: + +```go +res, err := bosClient.GetObjectMeta(bucketName, objectName) +fmt.Printf("Metadata: %+v\n", res) +``` + +## 获取文件下载URL + +用户可以通过如下代码获取指定Object的URL: + +```go +// 1. 原始接口,可设置bucket、object名称,过期时间、请求方法、请求头和请求参数 +url := bosClient.GeneratePresignedUrl(bucketName, objectName, + expirationInSeconds, method, headers, params) + +// 2. 基本接口,默认为`GET`方法,仅需设置过期时间 +url := bosClient.BasicGeneratePresignedUrl(bucketName, objectName, expirationInSeconds) +``` + +> **说明:** +> +> * 用户在调用该函数前,需要手动设置endpoint为所属区域域名。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/Regions.html)。目前支持“华北-北京”、“华南-广州”和“华东-苏州”三个区域。北京区域:`http://bj.bcebos.com`,广州区域:`http://gz.bcebos.com`,苏州区域:`http://su.bcebos.com`。 +> * `expirationInSeconds`为指定的URL有效时长,时间从当前时间算起,为可选参数,不配置时系统默认值为1800秒。如果要设置为永久不失效的时间,可以将`expirationInSeconds`参数设置为-1,不可设置为其他负数。 +> * 如果预期获取的文件时公共可读的,则对应URL链接可通过简单规则快速拼接获取: http://{$bucketName}.{$region}.bcebos.com/{$objectName}。 + +## 列举存储空间中的文件 + +BOS GO SDK支持用户通过以下两种方式列举出object: + +- 简单列举 +- 通过参数复杂列举 + +除此之外,用户还可在列出文件的同时模拟文件夹。 + +### 简单列举 + +当用户希望简单快速列举出所需的文件时,可通过ListObjects方法返回ListObjectsResult对象,ListObjectsResult对象包含了此次请求的返回结果。用户可以从ListObjectsResult对象的Contents字段获取Object的所有描述信息。 + +```go +listObjectResult, err := bosClient.ListObjects(bucketName, nil) + +// 打印当前ListObjects请求的状态结果 +fmt.Println("Name:", listObjectResult.Name) +fmt.Println("Prefix:", listObjectResult.Prefix) +fmt.Println("Delimiter:", listObjectResult.Delimiter) +fmt.Println("Marker:", listObjectResult.Marker) +fmt.Println("NextMarker:", listObjectResult.NextMarker) +fmt.Println("MaxKeys:", listObjectResult.MaxKeys) +fmt.Println("IsTruncated:", listObjectResult.IsTruncated) + +// 打印Contents字段的具体结果 +for _, obj := range listObjectResult.Contents { + fmt.Println("Key:", obj.Key, ", ETag:", obj.ETag, ", Size:", obj.Size, + ", LastModified:", obj.LastModified, ", StorageClass:", obj.StorageClass) +} +``` + +> **注意:** +> 1. 默认情况下,如果Bucket中的Object数量大于1000,则只会返回1000个Object,并且返回结果中IsTruncated值为True,并返回NextMarker做为下次读取的起点。 +> 2. 若想增大返回Object的数目,可以使用Marker参数分次读取。 + +### 通过参数复杂列举 + +除上述简单列举外,用户还可通过设置ListObjectsArgs参数实现各种灵活的查询功能。ListObjectsArgs可设置的参数如下: + +参数 | 功能 +-----|----- +Prefix | 限定返回的object key必须以prefix作为前缀 +Delimiter | 分隔符,是一个用于对Object名字进行分组的字符所有名字包含指定的前缀且第一次出现。Delimiter字符之间的Object作为一组元素 +Marker | 设定结果从marker之后按字母排序的第一个开始返回 +MaxKeys | 限定此次返回object的最大数,如果不设定,默认为1000,max-keys取值不能大于1000 + +> **注意:** +> 1. 如果有Object以Prefix命名,当仅使用Prefix查询时,返回的所有Key中仍会包含以Prefix命名的Object,详见[递归列出目录下所有文件](#递归列出目录下所有文件)。 +> 2. 如果有Object以Prefix命名,当使用Prefix和Delimiter组合查询时,返回的所有Key中会有Null,Key的名字不包含Prefix前缀,详见[查看目录下的文件和子目录](#查看目录下的文件和子目录)。 + +下面我们分别以几个案例说明通过参数列举的方法: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.ListObjectsArgs) + +// 指定最大返回参数为500 +args.MaxKeys = 500 + +// 指定满足特定前缀 +args.Prefix = "my-prefix/" + +// 指定分隔符,实现类似文件夹的功能 +args.Delimiter = "/" + +// 设置特定Object之后的排序结果 +args.Marker = "bucket/object-0" + +listObjectResult, err := bosClient.ListObjects(bucketName, args) +``` + +### 模拟文件夹功能 + +在BOS的存储结果中是没有文件夹这个概念的,所有元素都是以Object来存储,但BOS的用户在使用数据时往往需要以文件夹来管理文件。因此,BOS提供了创建模拟文件夹的能力,其本质上来说是创建了一个size为0的Object。对于这个Object可以上传下载,只是控制台会对以“/”结尾的Object以文件夹的方式展示。 + +用户可以通过Delimiter和Prefix参数的配合模拟出文件夹功能。Delimiter和Prefix的组合效果是这样的: + +如果把Prefix设为某个文件夹名,就可以罗列以此Prefix开头的文件,即该文件夹下递归的所有的文件和子文件夹(目录)。文件名在Contents中显示。 +如果再把 Delimiter 设置为“/”时,返回值就只罗列该文件夹下的文件和子文件夹(目录),该文件夹下的子文件名(目录)返回在CommonPrefixes 部分,子文件夹下递归的文件和文件夹不被显示。 + +如下是几个应用方式: + +**列出Bucket内所有文件** + +当用户需要获取Bucket下的所有文件时,可以参考如下代码: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.ListObjectsArgs) +args.Delimiter = "/" +listObjectResult, err := bosClient.ListObjects(bucketName, args) +``` + +**递归列出目录下所有文件** + +可以通过设置 `Prefix` 参数来获取某个目录下所有的文件: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.ListObjectsArgs) +args.Prefix = "fun/" +listObjectResult, err := bosClient.ListObjects(bucketName, args) +fmt.Println("Objects:") +for _, obj := range listObjectResult.Contents { + fmt.Println(obj.Key) +} +``` + +输出: + + Objects: + fun/ + fun/movie/001.avi + fun/movie/007.avi + fun/test.jpg + +**查看目录下的文件和子目录** + +在 `Prefix` 和 `Delimiter` 结合的情况下,可以列出目录下的文件和子目录: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.ListObjectsArgs) +args.Delimiter = "/" +args.Prefix = "fun/" +listObjectResult, err := bosClient.ListObjects(bucketName, args) + +// 遍历所有的Objects(当前目录和直接子文件) +fmt.Println("Objects:") +for _, obj := range listObjectResult.Contents { + fmt.Println(obj.Key) +} + +// 遍历所有的CommonPrefix(子目录) +fmt.Println("CommonPrefixs:") +for _, obj := range listObjectResult.CommonPrefixes { + fmt.Println(obj.Prefix) +} +``` + +输出: + Objects: + fun/ + fun/test.jpg + + CommonPrefixs: + fun/movie/ + + +返回的结果中,`ObjectSummaries` 的列表中给出的是fun目录下的文件。而`CommonPrefixs`的列表中给出的是fun目录下的所有子文件夹。可以看出`fun/movie/001.avi` ,`fun/movie/007.avi`两个文件并没有被列出来,因为它们属于 `fun` 文件夹下的 `movie` 目录。 + +### 列举Bucket中object的存储属性 + +当用户完成上传后,如果需要查看指定Bucket中的全部Object的storage class属性,可以通过如下代码实现: + +```go +listObjectResult, err := bosClient.ListObjects(bucketName, args) +for _, obj := range listObjectResult.Contents { + fmt.Println("Key:", obj.Key) + fmt.Println("LastModified:", obj.LastModified) + fmt.Println("ETag:", obj.ETag) + fmt.Println("Size:", obj.Size) + fmt.Println("StorageClass:", obj.StorageClass) + fmt.Println("Owner:", obj.Owner.Id, obj.Owner.DisplayName) +} +``` + +## 权限控制 + +### 设置对象的访问权限 + +目前BOS支持两种方式设置ACL。第一种是使用Canned Acl,在PutObjectAcl的时候,通过头域的"x-bce-acl"或者"x-bce-grant-permission"来设置对象的访问权限,当前可设置的权限包括private和public-read,两种类型的header不可以同时在一个请求中出现。第二种方式是上传一个ACL文件。详细信息请参考[设置Object权限控制](https://cloud.baidu.com/doc/BOS/API.html#PutObjectAcl.E6.8E.A5.E5.8F.A3) + +#### 设置Canned ACL + +Canned ACL是预定义的访问权限,用户可选择对某个对象进行设置,支持三种接口: + +```go +// 1. 使用x-bce-acl Header设置 +err := bosClient.PutObjectAclFromCanned(bucket, object, cannedAcl) //cannedAcl可取值为:private、public-read + +// 2. 使用x-bce-grant-{permission} Header设置 +err1 := bosClient.PutObjectAclGrantRead(bucket, object, userId) +err2 := bosClient.PutObjectAclGrantFullControl(bucket, object, userId) +// userId为授权的用户,支持可变参数,传入多个用户ID +``` + +#### 设置自定义ACL + +用户可参考如下代码设置Bucket内的对象的自定义访问权限,支持四种不同参数: + +```go +// import "github.com/baidubce/bce-sdk-go/bce" +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +// 1. 直接上传ACL文件流 +aclBodyStream := bce.NewBodyFromFile("") +err := bosClient.PutObjectAcl(bucket, object, aclBodyStream) + +// 2. 直接使用ACL json字符串 +aclString := `{ + "accessControlList":[ + { + "grantee":[{ + "id":"e13b12d0131b4c8bae959df4969387b8" //指定用户ID + }], + "permission":["FULL_CONTROL"] //指定用户权限 + } + ] +}` +err := bosClient.PutObjectAclFromString(bucket, object, aclString) + +// 3. 使用ACL文件 +err := bosClient.PutObjectAclFromFile(bucket, object, "") + +// 4. 使用ACL struct对象设置 +grantUser1 := api.GranteeType{""} +grantUser2 := api.GranteeType{""} +grant1 := api.GrantType{ + Grantee: []api.GranteeType{grantUser1}, + Permission: []string{"FULL_CONTROL"} +} +grant2 := api.GrantType{ + Grantee: []api.GranteeType{granteUser2}, + Permission: []string{"READ"} +} +grantArr := make([]api.GranteType) +grantArr = append(grantArr, grant1) +grantArr = append(grantArr, grant2) +args := &api.PutObjectAclArgs{grantArr} +err := bosClient.PutObjectAclFromStruct(bucketName, object, args) +``` + +### 获取对象的访问权限 + +如下代码可获取一个对象的访问权限: + +```go +result, err := bosClient.GetObjectAcl(bucketName, object) +``` + +返回结果对象的字段包含了访问权限的详细内容,具体定义如下: + +```go +type GetObjectAclResult struct { + AccessControlList []struct{ + Grantee []struct{ + Id string + } + Permission []string + } +} +``` + +### 删除对象的访问权限 + +对设置过访问权限的对象,可以调用此接口进行删除: + +```go +err := bosClient.DeleteObjectAcl(bucketName, object) +``` + +## 删除文件 + +**删除单个文件** + +可参考如下代码删除了一个Object: + +```go +// 指定要删除Object名称和所在的Bucket名称 +err := bosClient.DeleteObject(bucketName, objectName) +``` + +**删除多个文件** + +用户也可通过一次调用删除同一个Bucket下的多个文件,有如下参数: + +参数名称 | 描述 | 父节点 +---------|---------|-------- +objects | 保存要删除的Object信息的容器,包含一个或多个Object元素 | - ++key | 要删除的Object的名称 | objects + +具体示例如下: + +``` +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +// 1. 原始接口,提供多个Object的List Stream +res, err := bosClient.DeleteMultipleObjects(bucket, objectListStream) + +// 2. 提供json字符串删除 +objectList := `{ + "objects":[ + {"key": "aaa"}, + {"key": "bbb"} + ] +}` +res, err := bosClient.DeleteMultipleObjectsFromString(bucket, objectList) + +// 3. 提供删除Object的List对象 +deleteObjectList := make([]api.DeleteObjectArgs, 0) +deleteObjectList = append(deleteObjectList, api.DeleteObjectArgs{"aaa"}) +deleteObjectList = append(deleteObjectList, api.DeleteObjectArgs{"bbb"}) +multiDeleteObj := &api.DeleteMultipleObjectsArgs{deleteObjectList} +res, err := bosClient.DeleteMultipleObjectsFromStruct(bucket, multiDeleteObj) + +// 4. 直接提供待删除Object的名称列表 +deleteObjects := []string{"aaa", "bbb"} +res, err := bosClient.DeleteMultipleObjectsFromKeyList(bucket, deleteObjects) +``` + +> **说明:** +> +> 一次删除多个Object的时候,返回的结果里包含了未删除成功的Object名称列表。删除部分对象成功时`res`里包含了未删除成功的名称列表。 +> 删除部分对象成功时`err`为`nil`且`res`不为`nil`,判断全部删除成功:`err`为`io.EOF`且`res`为`nil`。 + +## 查看文件是否存在 + +用户可通过如下操作查看某文件是否存在: + +```go +// import "github.com/baidubce/bce-sdk-go/bce" + +_, err := bosClient.GetObjectMeta(bucketName, objectName) +if realErr, ok := err.(*bce.BceServiceError); ok { + if realErr.StatusCode == 404 { + fmt.Println("object not exists") + } +} +fmt.Println("object exists") +``` + +## 获取及更新文件元信息 + +文件元信息(Object Metadata),是对用户上传BOS的文件的属性描述,分为两种:HTTP标准属性(HTTP Headers)和User Meta(用户自定义元信息)。 + +### 获取文件元信息 + +用户通过GetObjectMeta方法可以只获取Object Metadata而不获取Object的实体。如下代码所示: + +```go +res, err := bosClient.GetObjectMeta(bucketName, objectName) +fmt.Printf("Metadata: %+v\n", res) +``` + +### 修改文件元信息 + +BOS修改Object的Metadata通过拷贝Object实现。即拷贝Object的时候,把目的Bucket设置为源Bucket,目的Object设置为源Object,并设置新的Metadata,通过拷贝自身实现修改Metadata的目的。如果不设置新的Metadata,则报错。这种方式下必须使用拷贝模式为“replace”(默认情况为“copy”)。示例如下: + +```go +// import "github.com/baidubce/bce-sdk-go/bce" + +args := new(api.CopyObjectArgs) + +// 必须设置拷贝模式为"replace",默认为"copy"是不能执行Metadata修改的 +args.MetadataDirective="replace" + +// 设置Metadata参数值,具体字段请参考官网说明 +args.LastModified = "Wed, 29 Nov 2017 13:18:08 GMT" +args.ContentType = "text/json" + +// 使用CopyObject接口修改Metadata,源对象和目的对象相同 +res, err := bosClient.CopyObject(bucket, object, bucket, object, args) +``` + +## 拷贝文件 + +### 拷贝一个文件 + +用户可以通过CopyObject方法拷贝一个Object,如下代码所示: + +```go +// 1. 原始接口,可设置拷贝参数 +res, err := bosClient.CopyObject(bucketName, objectName, srcBucket, srcObject, nil) + +// 2. 忽略拷贝参数,使用默认 +res, err := bosClient.BasicCopyObject(bucketName, objectName, srcBucket, srcObject) + +fmt.Println("ETag:", res.ETag, "LastModified:", res.LastModified) +``` + +上述接口返回的结果对象中包含了新Object的ETag和修改时间LastModified。 + +### 设置拷贝参数拷贝Object + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.CopyObjectArgs) + +// 设置用户自定义Metadata +args.UserMeta = map[string]string{"": ""} + +res, err := bosClient.CopyObject(bucketName, objectName, srcBucket, srcObject, args) +fmt.Println("ETag:", res.ETag, "LastModified:", res.LastModified) +``` + +**设置Object的Copy属性** + +用户在执行拷贝的过程中,可以对源Object的Etag或修改状态进行判断,根据判断结果决定是否执行拷贝。详细的参数解释如下: + +| 名称 | 类型 | 描述 | 是否必需 | +| --- | --- | --- | ---- | +| x-bce-copy-source-if-match | String | 如果源Object的ETag值和用户提供的ETag相等,则执行拷贝操作,否则拷贝失败。 | 否 | +| x-bce-copy-source-if-none-match | String | 如果源Object的ETag和用户提供的ETag不相等,则执行拷贝操作,否则拷贝失败。 | 否 | +| x-bce-copy-source-if-unmodified-since | String | 如果源object在x-bce-copy-source-if-unmodified-since之后没被修改,则执行拷贝操作,否则拷贝失败。 | 否 | +| x-bce-copy-source-if-modified-since | String | 如果源object在x-bce-copy-source-if-modified-since之后被修改了,则执行拷贝操作,否则拷贝失败。 | 否 | + +对应的示例代码: + +```go +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +args := new(api.CopyObjectArgs) + +// 设置用户自定义Metadata +args.UserMeta = map[string]string{"": ""} + +// 设置copy-source-if-match +args.IfMatch = "111111111183bf192b57a4afc76fa632" + +// 设置copy-source-if-none-match +args.IfNoneMatch = "111111111183bf192b57a4afc76fa632" + +// 设置copy-source-if-modified-since +args.IfModifiedSince = "Fri, 16 Mar 2018 17:07:21 GMT" + +// 设置copy-source-if-unmodified-since +args.IfUnmodifiedSince = "Fri, 16 Mar 2018 17:07:21 GMT" + +res, err := bosClient.CopyObject(bucketName, objectName, srcBucket, srcObject, args) +fmt.Println("ETag:", res.ETag, "LastModified:", res.LastModified) +``` + +**同步Copy功能** + +当前BOS的CopyObject接口是通过同步方式实现的。同步方式下,BOS端会等待Copy实际完成才返回成功。同步Copy能帮助用户更准确的判断Copy状态,但用户感知的复制时间会变长,且复制时间和文件大小成正比。 + +### 分块拷贝 + +除了通过CopyObject接⼝拷贝文件以外,BOS还提供了另外一种拷贝模式——Multipart Upload Copy。用户可以在如下的应用场景内(但不仅限于此),使用Multipart Upload Copy,如: + +- 需要支持断点拷贝。 +- 拷贝超过5GB大小的文件。 +- 网络条件较差,和BOS的服务器之间的连接经常断开。 + +分块拷贝与上传对象中的分块上传类似,也是通过三个步骤来实现:初始化、执行分块拷贝和汇总完成,其中初始化和汇总完成的操作同分块上传的接口一致。 + +下面提供分块拷贝的详细示例代码,用户可与分块上传的详细说明进行对比,以便于理解: + +``` +// import "github.com/baidubce/bce-sdk-go/services/bos/api" + +// 1. 初始化分块上传, +initResult, err := bosClient.BasicInitiateMultipartUpload(bucketName, objectKey) +if err != nil { + fmt.Println("initiate multipart upload copy failed:", err) + return +} + +// 2. 执行分块上传 +meta, err := bosClient.GetObjectMeta(bucketName, objectKey) // 获取对象大小以便进行切块 +if err != nil { + fmt.Println("get object length failed:", err) + return +} +const ( + MB = 1 << 20 + MAX_PARTS = 10000 // 分块拷贝的part总数不能超过10000 +) +var ( + leftSize int64 = meta.ContentLength + offset int64 = 0 + + // 单个part须为1MB的整数倍,且不超过5GB,除最后一个外其余part必须大于等于5MB + partSize int64 = 8 * MB +) +totalParts := (meta.ContentLength + partSize - 1) / partSize +if totalParts > MAX_PARTS { + partSize = (meta.ContentLength + MAX_PART - 1) / 10000 + partSize = (partSize + MB - 1) / MB * MB // 按1MB对齐 + totalParts = (meta.ContentLength + partSize - 1) / partSize +} +copyInfo := make([]UploadInfoType, partNumber) +for partNumber := int64(1); partNumber <= totalParts; partNumber++ { + start := (partNumber - 1) * partSize + end := partNumber * partSize + if end > meta.ContentLength { + end = meta.ContentLength + } + + // 设置拷贝的参数,分块拷贝的SourceRange制定当前拷贝的区间,若不指定则拷贝全部对象 + // 还有另外四个参数用户可自行设定:IfMatch、IfNoneMatch、IfModifiedSince、IfUnmodifiedSince + args := &api.UploadPartCopyArgs{ + // 指定拷贝区间时必须使用“bytes=first-last”格式,last是最后一个字节的索引(从0开始算起) + SourceRange: fmt.Sprintf("bytes=%d-%d", start, end-1) + } + res, err := bosClient.UploadPartCopy(destBucket, destObject, + initResult.Bucket, initResult.Key, initResult.UploadId, partNumber, args) + if err != nil { + bosClient.AbortMultipartUpload(initResult.Bucket, initResult.Key, initResult.UploadId) + fmt.Println("abort multipart upload copy with error:", err) + return + } + copyInfo[partNumber-1] = api.UploadInfoType{partNumber, res.ETag} +} + +// 3. 完成汇总 +completeArgs := &api.CompleteMultipartUploadArgs{Parts: copyInfo} +completeRes, err := bosClient.CompleteMultipartUploadFromStruct( + initResult.Bucket, initResult.Key, initResult.UploadId, completeArgs) +if err != nil { + bosClient.AbortMultipartUpload(initResult.Bucket, initResult.Key, initResult.UploadId) + fmt.Println("abort multipart upload copy with error:", err) + return +} +fmt.Println(completeRes.Location) +fmt.Println(completeRes.Bucket) +fmt.Println(completeRes.Key) +fmt.Println(completeRes.ETag) +``` + +# 数据处理及使用 + +## 生命周期管理 + +BOS支持用户对Bucket设置生命周期规则,以自动将过期的文件清除,节省存储空间。针对不同前缀的文件,用户可以同时设置多条规则。 +在为Bucket设置一条生命周期规则时,需注意如下参数的使用方式: + +规则项 | 描述 | 是否必填 | 备注 +-------|--------|------------|-------- +id | 规则的标识符 | 必填 | 同一个bucket内规则id必须唯一,不能重复。如果用户不填系统会自动帮用户生成一个 +status | 规则的状态 | 必填 | 取值为enabled或disabled,当规则处于disabled时规则不生效 +resource | 规则对哪些资源生效 | 必填 | 举例:对samplebucket里以prefix/为前缀的Object生效:`samplebucket/prefix/*` +condition | 规则依赖的条件 | 必填 | 目前只支持time形式 ++time | 时间限制条件 | 必填 | 通过定义的dateGreaterThan实现 +++dateGreaterThan | 描述时间关系 | 必填 | 支持绝对时间date和相对时间days。绝对时间date格式为yyyy-mm-ddThh:mm:ssZ,eg. 2016-09-07T00:00:00Z。绝对时间为UTC时间,必须以00:00:00(UTC 0点)结尾;相对时间days的描述遵循ISO8601,支持的最小时间粒度为天,如:$(lastModified)+P7D表示的时间为object的last-modified之后7天。 +action | 对resource执行的操作动作 | 必填 | - ++name | 执行的操作名称 | 必填 | 取值为Transition、DeleteObject、AbortMultipartUpload ++storageClass | Object的存储类型 | 可选 | action为Transition时可以设定,取值为STANDARD_IA或COLD,表示从原存储类型转为低频存储或冷存储 + +### 设置生命周期规则 + +可通过如下代码设置一条生命周期规则: + +```go +// import "github.com/baidubce/bce-sdk-go/bce" + +ruleStr := `{ + "rule": [ + { + "id": "delete-rule-1", + "status": "enabled", + "resource": ["my-bucket/abc*"], + "condition": { + "time": { + "dateGreaterThan": "2018-01-01T00:00:00Z" + } + }, + "action": { + "name": "DeleteObject" + } + } + ] +}` + +// 1. 通过stream调用接口进行设置 +body, _ := bce.NewBodyFromString(ruleStr) +err := bosClient.PutBucketLifecycle(bucketName, body) + +// 2. 直接传入字符串 +err := bosClient.PutBucketLifecycleFromString(bucketName, ruleStr) +``` + +### 查看生命周期规则 + +可通过如下代码查看Bucket内的生命周期规则: + +```go +res, err := bosClient.GetBucketLifecycle(bucketName) +fmt.Printf("%+v\n", res.Rule) +``` + +### 删除生命周期规则 + +可通过如下代码清空生命周期规则: + +```go +err := bosClient.DeleteBucketLifecycle(bucketName) +``` + +## 跨域资源共享 + +跨域资源共享(Cross-Origin Resource Sharing),简称CORS,是HTML5提供的标准跨域解决方案,BOS目前已经支持CORS标准来实现跨域访问。关于跨域访问的介绍请参考[跨域访问](https://cloud.baidu.com/doc/BOS/DevRef.html#.E8.B7.A8.E5.9F.9F.E8.AE.BF.E9.97.AE)。 + +### 设置CORS规则 + +用户可针对Bucket设置CORS规则,支持通过json字符串、文件、流、对象方式设置: + +```go +// import "github.com/baidubce/bce-sdk-go/service/bos/api" + +// 1. 通过流式调用接口进行设置 +err := bosClient.PutBucketCors(bucketName, body) + +// 2. 直接传入字符串 +err := bosClient.PutBucketCorsFromString(bucketName, corsString) + +// 3. 传入CORS文件名 +err := bosClient.PutBucketCorsFromFile(bucketName, corsFile) + +// 4. 传入对象 +corsObj := &api.BucketCORSType{ + AllowedOrigins: []string{"example.com"}, + AllowedMethods: []string{"HEAD", "GET"}, + AllowedHeaders: []string{"*"}, + AllowedExposeHeaders: []string{"*"}, + MaxAgeSeconds: 3600, +} +err := bosClient.PutBucketCorsFromStruct(bucketName, &api.PutBucketCorsArgs{corsObj}) +``` + +### 获取CORS规则 + +用户可获取指定Bucket的CORS规则: + +```go +result, err := bosClient.GetBucketCors(bucketName) +``` + +结果对象的定义与`PutBucketCorsFromStruct`接口的请求参数相同。 + +### 删除CORS规则 + +可参考如下代码删除Bucket的CORS规则,删除后的Bucket将无法进行跨域访问。 + +```go +err := bosClient.DeleteBucketCors(bucketName) +``` + +## 管理存储类型 + +每个Bucket会有自身的存储类型,如果该Bucket下的Object上传时未指定存储类型则会默认继承该Bucket的存储类型。 + +### 设置Bucket存储类型 + +Bucket默认的存储类型为标准模式,用户可以通过下面的代码进行设置: + +``` +storageClass := "STANDARD_IA" +err := bosClient.PutBucketStorageclass(bucketName, storageClass) +``` + +### 获取Bucket存储类型 + +下面的代码可以查看一个Bucket的默认存储类型: + +``` +storageClass, err := bosClient.GetBucketStorageclass(bucketName) +``` + +## 设置访问日志 + +BOS GO SDK支持将用户访问Bucket时的请求记录记录为日志,用户可以指定访问Bucket的日志存放的位置。日志会包括请求者、Bucket名称、请求时间和请求操作等。关于Bucket日志的详细功能说明可参见[设置访问日志](https://cloud.baidu.com/doc/BOS/DevRef.html#.E6.97.A5.E5.BF.97.E6.A0.BC.E5.BC.8F)。 + +### 开启Bucket日志 + +用户通过设置用于放置日志的Bucket和日志文件前缀来开启Bucket日志功能。下面的示例代码可以设置访问日志的位置和前缀: + +``` +// import "github.com/baidubce/bce-sdk-go/bce" + +// 1. 从JSON字符串设置 +loggingStr := `{"targetBucket": "logging-bucket", "targetPrefix": "my-log/"}` +err := bosClient.PutBucketLoggingFromString(bucketName, loggingStr) + +// 2. 从参数对象设置 +args := new(api.PutBucketLoggingArgs) +args.TargetBucket = "logging-bucket" +args.TargetPrefix = "my-log/" +err := bosClient.PutBucketLoggingFromStruct(bucketName, args) + +// 3. 读取json格式的文件进行设置 +loggingStrem := bce.NewBodyFromFile("") +err := bosClient.PutBucketLogging(bucketName, loggingStream) +``` + +### 查看Bucket日志设置 + +下面的代码分别给出了如何获取给定Bucket的日志配置信息: + +```go +res, err := bosClient.GetBucketLogging(bucketName) +fmt.Println(res.Status) +fmt.Println(res.TargetBucket) +fmt.Println(res.TargetPrefix) +``` + +### 关闭Bucket日志 + +需要关闭Bucket的日志功能是,只需调用删除接口即可实现: + +```go +err := bosClient.DeleteBucketLogging(bucketName) +``` + +## 服务端加密 + +### 设置服务端加密功能 + +用户可针对一个Bucket设置开启服务端加密的功能,所有存储到该Bucket的数据将会进行加密存储,保证数据安全性。 + +```go +err := bosClient.PutBucketEncryption(bucketName, algorithm) +``` +`algorithm`参数为加密算法,当前只支持“AES256”加密算法。 + +### 获取服务端加密 + +用户可调用如下接口获取Bucket的服务端加密功能: + +```go +algorithm, err := bosClient.GetBucketEncryption(bucketName) +``` + +### 删除服务端加密功能 + +用户可调用如下接口删除指定Bucket的服务端加密功能: + +```go +err := bosClient.DeleteBucketEncryption(bucketName) +``` + +## 原图保护功能 + +用户可针对Bucket下存储的图片设置原图保护功能,用户需指定待保护的资源。 + +### 开启原图保护功能 + +通过如下代码开启原图保护功能: + +```go +err := bosClient.PutBucketCopyrightProtection(bucket, resources) +``` + +`resources`参数为可变参数,可指定多个。 + +### 获取原图保护设置 + +用户通过如下示例代码获取Bucket设置的原图保护的资源: + +```go +resources, err := bosClient.GetBucketCopyrightProtection(bucketName) +``` + +### 删除原图保护配置 + +```go +err := bosClient.DeleteBucketCopyrightProtection(bucketName) +``` + +## 静态网站托管 + +### 开启静态网站托管 + +用户可通过如下示例代码设置一个Bucket开启静态网站托管的功能: + +```go +// import "github.com/baidubce/bce-sdk-go/service/bos/api" + +// 1. 通过流式调用接口进行设置 +err := bosClient.PutBucketStaticWebsite(bucketName, body) + +// 2. 直接传入json字符串 +jsonStr := `{"index": "index.html", "notFound": "404.html"}` +err := bosClient.PutBucketStaticWebsiteFromString(bucketName, jsonStr) + +// 3. 传入对象 +args := &api.BucketStaticWebsiteType{ + Index: "index.html", + NotFound: "404.html", +} +err := bosClient.PutBucketStaticWebsiteFromStruct(bucketName, args) + +// 4. 简单接口设置 +err := bosClient.SimplePutBucketStaticWebsite(bucketName, "index.html", "404.html") +``` + +### 获取静态网站托管的设置 + +用户通过如下代码获取指定Bucket的静态网站托管的设置情况: + +```go +result, err := bosClient.SimplePutBucketStaticWebsite(bucketName) +fmt.Println(result.Index) +fmt.Println(result.NotFound) +``` + +### 删除静态网站托管的设置 + +通过如下示例代码删除指定Bucket的静态网站托管功能: + +```go +err := bosClient.DeleteBucketStaticWebsite(bucketName) +``` + +## 跨区域复制 + +BOS提供了跨区域复制功能,针对用户在某个物理区域创建的Bucket,为了数据安全或其他目的,可配置将整个Bucket的数据复制到物理上的另一个区域。 + +### 开启Bucket跨区域复制功能 + +用户可通过如下代码开启Bucket的跨区域复制功能: + +```go +// 1. json字符串 +jsonStr := `{ + "status":"enabled", + "resource":[ + "bucket/abc", + "bucket/cd*", + ], + "destination": { + "bucket":"bucket-name", + "storageClass":"COLD" + }, + "replicateHistory": { + "bucket":"bucket-name", + "storageClass":"COLD" + }, + "replicateDeletes":"enabled", + "id":"sample-bucket-replication-config" +}` +err := bosClient.PutBucketReplicationFromString(bucketName, jsonStr) + +// 2. 使用配置文件名 +err := bosClient.PutBucketReplicationFromFile(bucketName, configFile) + +// 3. 使用参数对象 +argsObj := &api.PutBucketReplicationArgs{ + Id: "sample-bucket-replication-config", + Status: "enabled", + Resource: []string{"bucket/abc"}, + ReplicateDeletes: "enabled", + Destination: &api.BucketReplicationDescriptor{"bucket-abc", "COLD"}, + ReplicateHistory: &api.BucketReplicationDescriptor{"bucket-abc", "COLD"}, +} +err := bosClient.PutBucketReplicationFromStruct(bucketName, argsObj) + +// 4. 使用流 +err := bosClient.PutBucketReplication(bucketName, bodyStream) +``` + +### 获取Bucket跨区域复制的配置 + +用户可使用如下示例代码获取Bucket的跨区域复制的配置,返回的结果与Put接口字段相同。 + +```go +result, err := bosClient.GetBucketReplication(bucketName) +``` + +### 删除Bucket跨区域复制配置 + +用户可使用如下示例代码删除Bucket跨区域复制功能: + +```go +err := bosClient.DeleteBucketReplication(bucketName) +``` + +### 获取跨区域复制到进度 + +由于跨区域复制需要后台进行异步复制操作,用户可通过如下接口查询当前复制到进度: + +```go +result, err := bosClient.GetBucketReplicationProgress(bucketName) +``` + +返回的结果对象包含了如下字段: + +- `Status`(string): 当前的状态 +- `HistoryReplicationPercent`(float64): 当前复制到进度 +- `LatestReplicationTime`(string): 最近一次执行复制的时间 + + +# 错误处理 + +GO语言以error类型标识错误,BOS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | BOS服务返回的错误 + +用户使用SDK调用BOS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// bosClient 为已创建的BOS Client对象 +bucketLocation, err := bosClient.PutBucket("test-bucket") +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("create bucket success, bucket location:", bucketLocation) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向BOS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当BOS服务端出现异常时,BOS服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BOS错误信息格式](https://cloud.baidu.com/doc/BOS/API.html#.E9.94.99.E8.AF.AF.E4.BF.A1.E6.81.AF.E6.A0.BC.E5.BC.8F) + +## SDK日志 + +BOS GO SDK自行实现了支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。详见示例代码。 + +### 默认日志 + +BOS GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the BOS go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the BOS go sdk") +``` + + +# 版本变更记录 + +## v0.9.3 [2018-09-21] + + - 支持Bucket跨区域复制、服务端加密、原图保护 + - 支持设置Bucket的CORS规则和静态网站托管 + - 支持Object级别的ACL设置 + - 修复GeneratePresignedUrl问题 + +## v0.9.2 [2018-3-16] + + - 修复go get下载时的错误提示信息 + - 修复重试请求时请求的body流丢失的问题 + - 完善UploadSuperFile返回的错误提示信息 + - 将GeneratePresignedUrl接口统一调整为bucket virtual hosting模式 + +## v0.9.1 [2018-1-4] + +首次发布: + + - 创建、查看、罗列、删除Bucket,获取位置和判断是否存在 + - 支持管理Bucket的生命周期、日志、ACL、存储类型 + - 上传、下载、删除、罗列Object,支持分块上传、分块拷贝 + - 提供AppendObject功能和FetchObject功能 + - 封装并发的下载和分块上传接口 diff --git a/bce-sdk-go/doc/BVW.md b/bce-sdk-go/doc/BVW.md new file mode 100644 index 0000000..ca939c6 --- /dev/null +++ b/bce-sdk-go/doc/BVW.md @@ -0,0 +1,596 @@ +# BVW服务 + +# 概述 + +本文档主要介绍videoworks(以下均简称BVW)GO SDK的使用。在使用本文档前,您需要先了解BVW的一些基本知识,并已开通了BVW服务。若您还不了解BVW,可以参考[产品描述](https://cloud.baidu.com/doc/VideoWorks/s/gjys24iww)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[服务域名](https://cloud.baidu.com/doc/VideoWorks/s/Xjyo34h6o)的部分,理解Endpoint相关的概念。 + +目前BVW服务仅支持“华北-北京”该区域。北京区域:`http://bvw.bj.baidubce.com`,对应信息为: + +| 访问区域 | 对应Endpoint | +| -------- | ------------------- | +| BJ | bvw.bj.baidubce.com | + +## 获取密钥 + +要使用百度云BVW,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BVW做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建BVW Client + +BVW Client是BVW服务的客户端,为开发者与BVW服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建BVW Client + +通过AK/SK方式访问BVW,用户可以参考如下代码新建一个BVW Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/bvw" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BVWClient + MEDIA_CLIENT, err := bvw.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《相关参考 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为BVW的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://bvw.bj.baidubce.com`。 + +# 媒资库 + +## 普通素材 + +### 上传素材 + +用户上传音频/视频/图片到素材库,创作视频时可从素材中心导入 + +```go +req := &api.MatlibUploadRequest{} +req.Key = "dog.mp4" +req.Bucket = "bvw-console" +req.Title = "split_result_267392.mp4" +req.MediaType = "video" +uploadResponse, err := BVW_CLIENT.UploadMaterial(req) +if err != nil { + fmt.Printf("upload error: %+v\n", err) + return +} +fmt.Printf("upload success : %+v\n", uploadResponse) +``` + +> 注意:这里上传的媒资类型需和MediaType严格对应,MediaType可选:video:视频, audio:音频,image:图片 + +### 查询素材 + +使用如下代码可以从媒资库查询一个素材。 + +```go +materialId := "d9b9f08ef1e0a28967fa0f7b5819db30" +materialGetResponse, err := BVW_CLIENT.GetMaterial(materialId) +if err != nil { + fmt.Printf("get material error: %+v\n", err) + return +} +fmt.Printf("get material success : %+v\n", materialGetResponse) +``` + +### 搜索素材 + +使用如下代码可以从媒资库搜索指定条件的素材。 + +```go +req := &api.MaterialSearchRequest{} +req.Size = 5 +req.PageNo = 1 +req.Status = "FINISHED" +req.MediaType = "video" +req.Begin = "2023-01-11T16:00:00Z" +req.End = "2023-04-12T15:59:59Z" +materialResp, err := BVW_CLIENT.SearchMaterial(req) +if err != nil { + fmt.Printf("search material error: %+v\n", err) + return +} +fmt.Printf("search material success : %+v\n", materialResp) +``` + +### 删除素材 + +使用如下代码可以从媒资库删除一个素材。 + +```go +materialId := "d9b9f08ef1e0a28967fa0f7b5819db30" +err := BVW_CLIENT.DeleteMaterial(materialId) +if err != nil { + fmt.Printf("delete material error: %+v\n", err) + return +} +fmt.Println("delete material success") +``` + +## 预置素材 + +预置素材分为音乐/贴图/背景/字幕/转场,除了系统自带的预置素材外,用户可以自定义音乐/贴图预置素材。创作视频时,不需要导入,可直接使用 + +### 上传预置素材 + +使用如下代码可以上传一个音乐/贴图预置素材到媒资库。 + +```go +req := &api.MatlibUploadRequest{} +req.Key = "item2.jpeg" +req.Bucket = "bvw-console" +req.Title = "item2.jpeg" +req.MediaType = "image" +type := "PICTURE" +uploadResponse, err := BVW_CLIENT.UploadMaterialPreset(type, req) +if err != nil { + fmt.Printf("upload preset material error: %+v\n", err) + return +} +fmt.Println("upload preset success : %+v\n", uploadResponse) +``` + +> 注意:预置素材类型type,只支持2种类型自定义:MUSIC:音乐,PICTURE:贴图。 + +### 搜索预置素材 + +使用如下代码可以查询一个指定预置素材。 + +```go +req := &api.MaterialPresetSearchRequest{} +req.PageSize = "10" +req.Status = "FINISHED" +req.PageNo = "1" +req.SourceType = "USER" +req.MediaType = "PICTURE" +response, err := BVW_CLIENT.SearchMaterialPreset(req) +if err != nil { + fmt.Printf("search preset material error: %+v\n", err) + return +} +fmt.Println("search preset success : %+v\n", response) +``` + +### 查询预置素材 + +使用如下代码可以从媒资库搜索指定条件的预置素材。 + +```go +id := "cc0aabdc71421abaa17e80a26caa009f" +response, err := BVW_CLIENT.GetMaterialPreset(id) +if err != nil { + fmt.Printf("get preset material error: %+v\n", err) + return +} +fmt.Println("get preset success : %+v\n", response) +``` + +### 删除预置素材 + +使用如下代码可以删除一个指定预置素材。 + +```go +id := "cc0aabdc71421abaa17e80a26caa009f" +err := BVW_CLIENT.DeleteMaterialPreset(id) +if err != nil { + fmt.Printf("delete preset material error: %+v\n", err) + return +} +fmt.Println("delete preset material success") +``` + +## 媒资库设置 + +媒资库相关操作需要预先设置bucket。 + +### 创建媒资库设置 + +使用如下代码可以创建媒资库设置,设置媒资库交互中使用的默认bucket。 + +```go +request := &api.MatlibConfigBaseRequest{ + Bucket: "go-test"} +response, err := BVW_CLIENT.CreateMatlibConfig(request) +if err != nil { + fmt.Printf("create config error: %+v\n", err) + return +} +fmt.Println("create config success : %+v\n", response) +``` + +### 更新媒资库设置 + +使用如下代码可以更新媒资库设置,设置媒资库交互中使用的默认bucket。 + +```go +err := BVW_CLIENT.UpdateMatlibConfig(&api.MatlibConfigUpdateRequest{Bucket: "go-test"}) +if err != nil { + fmt.Printf("update config error: %+v\n", err) + return +} +fmt.Println("update config success") +``` + +### 查询媒资库设置 + +使用如下代码可以查询媒资库设置,设置媒资库交互中使用的默认bucket。 + +```go +response, err := BVW_CLIENT.GetMatlibConfig() +if err != nil { + fmt.Printf("get config error: %+v\n", err) + return +} +fmt.Println("get config success : %+v\n", response) +``` + +# 快编 + +## 创建草稿 + +在进行视频合成前需要先创建草稿,以获取任务id用于后续视频合成任务 + +```go +response, err := BVW_CLIENT.CreateDraft(&api.CreateDraftRequest{ + Duration: "0", + Titile: "testCreateDraft3", + Ratio: "hori16x9"}) +if err != nil {     + fmt.Printf("create draft error: %+v\n", err)     + return +} +fmt.Println("create draft success taskId :", response.Id) +``` + +## 更新草稿 + +如下代码可更新所创建的草稿 + +```go +var request api.MatlibTaskRequest +jsonStr := "{\"title\":\"updatesucess\",\"draftId\":\"1017890\",\"timeline\":{\"timeline\":{\"video\":[{\"key\"" + +":\"name\",\"isMaster\":true,\"list\":[{\"type\":\"video\",\"start\":0,\"end\":5.859375,\"showStart\":0," + +"\"showEnd\":5.859375,\"xpos\":0,\"ypos\":0,\"width\":1280,\"height\":720,\"duration\":5.859375,\"extInfo" + +"\":{\"style\":\"\",\"lightness\":0,\"gifMode\":0,\"contrast\":0,\"saturation\":0,\"hue\":0,\"speed\":1" + +",\"transitionStart\":\"\",\"transitionEnd\":\"black\",\"transitionDuration\":1,\"volume\":1,\"rotate\":0," + +"\"mirror\":\"\",\"blankArea\":\"\"},\"mediaInfo\":{\"fileType\":\"video\",\"sourceType\":\"USER\",\"" + +"sourceUrl\":\"https://bj.bcebos.com/v1/bvw-console/360p/dog.mp4?x-bce-security-token=" + +"ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7x" + +"G%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hb" + +"SJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRp" + +"OC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ" + +"%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2" + +"F%2Fb227edbf73344bdfc9fed00ba491c5c0c3abe229792d7b3d026604cfbe541b68\",\"audioUrl\":\"" + +"https://bj.bcebos.com/v1/bvw-console/audio/dog.mp3?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjY" + +"yYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ" + +"5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3" + +"OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzT" + +"Cgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=" + +"bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F3dcc823c9497aca1154f" + +"f0007eca86af4e682363c3ceddba0b3c74ca14e2d154\",\"bucket\":\"bvw-console\",\"key\":\"dog.mp4\",\"audioKey\":" + +"\"audio/dog.mp3\",\"coverImage\":\"https://bj.bcebos.com/v1/bvw-console/thumbnail/dog00000500.jpg" + +"?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZp" + +"Ppsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQz" + +"FlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6P" + +"z36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQj" + +"Wm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cb" + +"c0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F21a92744dfb9fc3f46745e75d095da327bb04677f9028fb85e00ff5dc7df6" + +"daf\",\"duration\":18.73,\"width\":1920,\"height\":1080,\"status\":\"FINISHED\",\"name\":\"dog.mp4\"," + +"\"thumbnailPrefix\":\"\",\"thumbnailKeys\":[\"thumbnail/dog00000500.jpg\"],\"mediaId\":\"" + +"1f10ce0db10b8eb5b2f2755daf544900\",\"offstandard\":false},\"uid\":\"a081f1c6-9dc9-4e7b-a00e-6eb5217e771d" + +"\"},{\"type\":\"video\",\"start\":5.859375,\"end\":18.73,\"showStart\":5.859375,\"showEnd\":18.73,\"xpos" + +"\":0,\"ypos\":0,\"width\":1280,\"height\":720,\"duration\":12.870625,\"extInfo\":{\"style\":\"\",\"lightness" + +"\":0,\"gifMode\":0,\"contrast\":0,\"saturation\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"black\",\"" + +"transitionEnd\":\"\",\"transitionDuration\":1,\"volume\":1,\"rotate\":0,\"mirror\":\"\",\"blankArea\":\"\"}," + +"\"mediaInfo\":{\"fileType\":\"video\",\"sourceType\":\"USER\",\"sourceUrl\":" + +"\"https://bj.bcebos.com/v1/bvw-console/360p/dog.mp4?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyN" + +"jk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9" + +"RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7D" + +"GO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df" + +"5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%" + +"3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2Fb" + +"227edbf73344bdfc9fed00ba491c5c0c3abe229792d7b3d026604cfbe541b68\",\"audioUrl\":" + +"\"https://bj.bcebos.com/v1/bvw-console/audio/dog.mp3?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjY" + +"yYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5" + +"Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3O" + +"HDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCg" + +"h8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=" + +"bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F3dcc823c9497aca1" + +"154ff0007eca86af4e682363c3ceddba0b3c74ca14e2d154\",\"bucket\":\"bvw-console\",\"key\":\"dog.mp4\",\"" + +"audioKey\":\"audio/dog.mp3\",\"coverImage\":\"https://bj.bcebos.com/v1/bvw-console/thumbnail/dog00000500" + +".jpg?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZp" + +"Ppsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQz" + +"FlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz" + +"36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm" + +"231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0" + +"fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F21a92744dfb9fc3f46745e75d095da327bb04677f9028fb85e00ff5dc7df6da" + +"f\",\"duration\":18.73,\"width\":1920,\"height\":1080,\"status\":\"FINISHED\",\"name\":\"dog.mp4\",\"thumb" + +"nailPrefix\":\"\",\"thumbnailKeys\":[\"thumbnail/dog00000500.jpg\"],\"mediaId\":\"1f10ce0db10b8eb5b2f2755d" + +"af544900\",\"offstandard\":false},\"uid\":\"70af482e-0bf5-4c38-8f05-03c9e3b8ae03\"}],\"unlinkMaster\":true" + +"}],\"audio\":[{\"key\":\"\",\"isMaster\":false,\"list\":[{\"start\":0,\"end\":155.99,\"showStart\":" + +"0.234375,\"showEnd\":156.224375,\"duration\":155.99,\"xpos\":0,\"ypos\":0,\"hidden\":false,\"mediaInfo\"" + +":{\"fileType\":\"audio\",\"sourceUrl\":\"https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset" + +"/music/audio/%E5%8F%A4%E9%A3%8E%E9%A3%98%E6%89%AC.mp3?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772" + +"a1409590%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F2ddcf78c92de29ae3d7c3166a4e17e7c5d07fa38dcefd24c29c4f4d5b" + +"5ba46fe\",\"audioUrl\":\"https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset/music/audio/" + +"%E5%8F%A4%E9%A3%8E%E9%A3%98%E6%89%AC.mp3?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772a1409590%2F2" + +"023-04-14T07%3A16%3A35Z%2F86400%2F%2F2ddcf78c92de29ae3d7c3166a4e17e7c5d07fa38dcefd24c29c4f4d5b5ba46fe\"," + +"\"bucket\":\"videoworks-system-preprocess\",\"key\":\"systemPreset/music/古风飘扬.aac\",\"audioKey\":\"" + +"systemPreset/music/audio/古风飘扬.mp3\",\"coverImage\":\"\",\"duration\":155.99,\"name\":\"\",\"thumbnailList" + +"\":[],\"mediaId\":\"\",\"offstandard\":false},\"type\":\"audio\",\"uid\":\"bd52be7f-1f19-4368-8c41-44e991af" + +"8164\",\"name\":\"古风飘扬\",\"extInfo\":{\"style\":\"\",\"lightness\":0,\"gifMode\":0,\"contrast\":0,\"" + +"saturation\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"\",\"transitionEnd\":\"\",\"transitionDuration" + +"\":1,\"volume\":1,\"rotate\":0},\"boxDataLeft\":4,\"dragBoxWidth\":1996.6720000000003,\"lineType\":\"audio" + +"\"}]}],\"subtitle\":[{\"key\":\"\",\"list\":[{\"duration\":3,\"hidden\":false,\"name\":\"time-place\",\"" + +"tagExtInfo\":{\"marginBottom\":0,\"textFadeIn\":1,\"textFadeOut\":1,\"textOutMaskDur\":1},\"showStart\":" + +"5.859375,\"showEnd\":8.859,\"templateId\":\"6764ce3331ea7e406e4ab4475d1dff18\",\"type\":\"subtitle\",\"uid" + +"\":\"5aaa35f4-8fae-4b8c-b7ed-761a54550244\",\"xpos\":\"0\",\"ypos\":\"309\",\"config\":[{\"alpha\":0,\"" + +"fontColor\":\"#ffffff\",\"fontSize\":50,\"fontStyle\":\"normal\",\"fontType\":\"方正时代宋 简 Extrabold\"" + +",\"lineHeight\":1.2,\"name\":\"时间\",\"text\":\"haha\",\"backgroundColor\":\"#2468F2\",\"backgroundAlpha" + +"\":0,\"fontx\":0,\"fonty\":0,\"invisible\":false},{\"alpha\":0,\"fontColor\":\"#000000\",\"fontSize\":50," + +"\"fontStyle\":\"normal\",\"fontType\":\"方正时代宋 简 Extrabold\",\"lineHeight\":1.2,\"name\":\"地点\",\"" + +"text\":\"cd\",\"backgroundColor\":\"#ffffff\",\"backgroundAlpha\":0,\"fontx\":0,\"fonty\":0,\"invisible\"" + +":false}],\"boxDataLeft\":76,\"dragBoxWidth\":38.400000000000006,\"lineType\":\"subtitle\"}],\"master\":" + +"false}],\"sticker\":[{\"key\":\"\",\"isMaster\":false,\"list\":[{\"showStart\":0,\"showEnd\":3,\"duration\"" + +":3,\"xpos\":0,\"ypos\":0,\"width\":215,\"height\":120.9375,\"hidden\":false,\"mediaInfo\":{\"sourceUrl\":\"" + +"https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset/picture/%E9%9D%A2%E5%8C%85%E3%80%81%E8" + +"%82%A0.png?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772a1409590%2F2023-04-14T07%3A16%3A35Z%2F8640" + +"0%2F%2F84867e4874cc94eb374898017cb4367ed8c24a5750a9d8ebd14d8ca989cf2e53\",\"audioUrl\":\"" + +"https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset/picture/audio/%E9%9D%A2%E5%8C%85%E3%80%" + +"81%E8%82%A0.mp3?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772a1409590%2F2023-04-14T07%3A16%3A35Z%2F" + +"86400%2F%2F1807d3005f5f8fc270fa17238ec550c20162252c19952e6a45ae497ef7148086\",\"bucket\":\"" + +"videoworks-system-preprocess\",\"key\":\"systemPreset/picture/面包、肠.png\",\"audioKey\":\"systemPreset" + +"/picture/audio/面包、肠.mp3\",\"coverImage\":\"\",\"width\":215,\"height\":120,\"name\":\"\",\"thumbnailList" + +"\":[],\"mediaId\":\"\",\"offstandard\":false},\"type\":\"image\",\"uid\":\"e419b583-aedb-4265-" + +"9a67-7e21fc621f85\",\"name\":\"面包、肠\",\"extInfo\":{\"style\":\"\",\"lightness\":0,\"gifMode\":0," + +"\"contrast\":0,\"saturation\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"\",\"transitionEnd\":\"\"," + +"\"transitionDuration\":1,\"volume\":1,\"rotate\":0},\"lineType\":\"sticker\",\"boxDataLeft\":1,\"" + +"dragBoxWidth\":38.400000000000006}]}]}},\"ratio\":\"hori16x9\",\"resourceList\":[{\"id\":\"1f10ce0db10" + +"b8eb5b2f2755daf544900\",\"userId\":\"e7e47aa53fbb47dfb1e4c86424bb7ad3\",\"mediaType\":\"video\",\"" + +"sourceType\":\"USER\",\"status\":\"FINISHED\",\"title\":\"dog.mp4\",\"sourceUrl\":\"https://bj.bcebos.com" + +"/v1/bvw-console/dog.mp4?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM" + +"1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Z" + +"zgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkh" + +"MLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7" + +"D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1" + +"a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F4a3c399db912e35f6b6c008faffebe5752c47e36fcd21d4bf03" + +"bc908c3a29e5e\",\"sourceUrl360p\":\"https://bj.bcebos.com/v1/bvw-console/360p/dog.mp4?x-bce-security-toke" + +"n=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZT" + +"NAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwb" + +"rCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F" + +"9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujH" + +"KfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07" + +"%3A16%3A35Z%2F86400%2F%2Fb227edbf73344bdfc9fed00ba491c5c0c3abe229792d7b3d026604cfbe541b68\",\"audioUrl\"" + +":\"https://bj.bcebos.com/v1/bvw-console/audio/dog.mp3?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1Z" + +"jYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8" + +"sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46Nx" + +"S3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOF" + +"zTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorizatio" + +"n=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F3dcc823c9497aca1" + +"154ff0007eca86af4e682363c3ceddba0b3c74ca14e2d154\",\"thumbnailList\":[\"https://bj.bcebos.com/v1/bvw-cons" + +"ole/thumbnail/dog00000500.jpg?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAA" + +"BgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9" + +"xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSIS" + +"jn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCK" + +"r%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9" + +"411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F21a92744dfb9fc3f46745e75d095da327bb04677f902" + +"8fb85e00ff5dc7df6daf\"],\"subtitleUrls\":[],\"createTime\":\"2023-04-11 16:55:32\",\"updateTime\":\"2023-0" + +"4-11 16:55:43\",\"duration\":18.73,\"height\":1080,\"width\":1920,\"fileSizeInByte\":8948434,\"thumbnailK" + +"eys\":[\"thumbnail/dog00000500.jpg\"],\"subtitles\":[\"\"],\"bucket\":\"bvw-console\",\"key\":\"dog.mp4\"" + +",\"key360p\":\"360p/dog.mp4\",\"key720p\":\"720p/dog.mp4\",\"audioKey\":\"audio/dog.mp3\",\"used\":true}]" + +",\"coverBucket\":\"bvw-console\",\"coverKey\":\"thumbnail/dog00000500.jpg\"}" +jsonErr := json.Unmarshal([]byte(jsonStr), &request) +ExpectEqual(t.Errorf, jsonErr, nil) +err := BVW_CLIENT.UpdateDraft(1017890, &request) +if err != nil {     + fmt.Printf("update draft error: %+v\n", err)     + return +} +fmt.Println("update draft success") +``` + +## 获取草稿列表 + +使用如下代码可以获取所创建了所有快编草稿 + +```go +response, err := BVW_CLIENT.GetDraftList(&api.DraftListRequest{ + PageNo: 1, + PageSize: 20, + BeginTime: "2023-01-11T16:00:00Z", + EndTime: "2023-04-12T15:59:59Z"}) +if err != nil { + fmt.Printf("get draft list error: %+v\n", err) + return +} +fmt.Println("get draft list success : %+v\n", response) +``` + +## 获取单条草稿 + +如下代码可以通过快编任务id获取草稿信息 + +```go +taskId := 123456 +response, err := BVW_CLIENT.GetSingleDraft(taskId) +if err != nil { + fmt.Printf("get draft error: %+v\n", err) + return +} +fmt.Println("get draft success : %+v\n", response) +``` + +## 视频合成 + +视频合成功能支持将一段视频编辑的Timeline(不同媒体分类组成的时间轴数据)编码合成输出。 + +使用如下代码可以发起合成。 + +```go +var request api.VideoEditCreateRequest +jsonStr := "{\"title\":\"新建作品-202304141603\",\"taskId\":\"1017895\",\"bucket\":\"vwdemo\",\"cmd\":{\"timeline" + +"\":{\"video\":[{\"list\":[{\"type\":\"video\",\"start\":0,\"end\":7.65625,\"showStart\":0,\"showEnd\":" + +"7.65625,\"xpos\":0,\"ypos\":0,\"width\":1,\"height\":1,\"duration\":7.65625,\"extInfo\":{\"style\":\"\"" + +",\"lightness\":0,\"contrast\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"\",\"transitionEnd\":\"black\"" + +",\"transitionDuration\":1,\"mirror\":\"\",\"rotate\":0,\"blankArea\":\"\",\"volume\":1},\"mediaInfo\":{\"" + +"mediaId\":\"1f10ce0db10b8eb5b2f2755daf544900\",\"key\":\"dog.mp4\",\"bucket\":\"bvw-console\",\"fileType\"" + +":\"video\",\"width\":1920,\"height\":1080}},{\"type\":\"video\",\"start\":7.65625,\"end\":18.73,\"showStart" + +"\":7.65625,\"showEnd\":18.73,\"xpos\":0,\"ypos\":0,\"width\":1,\"height\":1,\"duration\":11.07375,\"" + +"extInfo\":{\"style\":\"\",\"lightness\":0,\"contrast\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"black\"" + +",\"transitionEnd\":\"\",\"transitionDuration\":1,\"mirror\":\"\",\"rotate\":0,\"blankArea\":\"\",\"volume\":" + +"1},\"mediaInfo\":{\"mediaId\":\"1f10ce0db10b8eb5b2f2755daf544900\",\"key\":\"dog.mp4\",\"bucket\":\"" + +"bvw-console\",\"fileType\":\"video\",\"width\":1920,\"height\":1080}}]}],\"audio\":[{\"list\":[{\"name\":" + +"\"古风飘扬\",\"start\":0,\"end\":155.99,\"duration\":155.99,\"showStart\":0.078125,\"showEnd\":156.068125,\"" + +"uid\":\"cc8c1ecc-fcd3-493d-be5b-8cce8c15ed15\",\"extInfo\":{\"volume\":\"1.0\",\"transitions\":[]},\"" + +"mediaInfo\":{\"fileType\":\"audio\",\"key\":\"systemPreset/music/古风飘扬.aac\",\"bucket\":\"videoworks-" + +"system-preprocess\",\"name\":\"古风飘扬\"}}]}],\"subtitle\":[{\"list\":[{\"templateId\":\"6764ce3331ea7e406e" + +"4ab4475d1dff18\",\"showStart\":0,\"showEnd\":3,\"duration\":3,\"uid\":\"05e59686-b23e-4b33-96d7-040eab63" + +"85b6\",\"tag\":\"time-place\",\"xpos\":0,\"ypos\":0.431,\"config\":[{\"text\":\"时间\",\"fontSize\":50,\"" + +"fontType\":\"方正时代宋 简 Extrabold\",\"fontColor\":\"#ffffff\",\"alpha\":0,\"fontStyle\":\"normal\",\"" + +"backgroundColor\":\"#2468F2\",\"backgroundAlpha\":0,\"fontx\":0.039,\"fonty\":0.028,\"rectx\":0,\"recty\"" + +":0.431,\"rectWidth\":0.156,\"rectHeight\":0.139},{\"text\":\"地点\",\"fontSize\":50,\"fontType\":\"" + +"方正时代宋 简 Extrabold\",\"fontColor\":\"#000000\",\"alpha\":0,\"fontStyle\":\"normal\",\"backgroundColor" + +"\":\"#ffffff\",\"backgroundAlpha\":0,\"fontx\":0.039,\"fonty\":0.028,\"rectx\":0.156,\"recty\":0.431,\"" + +"rectWidth\":0.156,\"rectHeight\":0.139}],\"tagExtInfo\":{\"glExtInfo\":{}}}]}],\"sticker\":[{\"list\":" + +"[{\"type\":\"image\",\"showStart\":0,\"showEnd\":3,\"duration\":3,\"xpos\":0,\"ypos\":0,\"width\":0.168" + +",\"height\":0.168,\"extInfo\":{},\"mediaInfo\":{\"key\":\"systemPreset/picture/面包、肠.png\",\"bucket\":" + +"\"videoworks-system-preprocess\",\"width\":215,\"height\":120.9375,\"fileType\":\"image\"}}]}]}},\"extInfo" + +"\":{\"aspect\":\"hori16x9\",\"resolutionRatio\":\"v720p\"}}" +jsonErr := json.Unmarshal([]byte(jsonStr), &request) +fmt.Println("jsonError: ", jsonErr) +t.Logf("%+v", &request) +response, err := BVW_CLIENT.CreateVideoEdit(&request) +if err != nil { + fmt.Printf("create edit job error: %+v\n", err) + return +} +fmt.Println("create edit job success : %+v\n", response) +``` + +> 上述代码模拟了前端请求后端数据结构进行视频合成任务,若不想采用上述方式也可自行构建VideoEditCreateRequest结构体进行视频合成任务。 + +## 查询视频合成结果 + +使用如下代码可以查询视频合成结果。 + +```json +editId := 123456 +response, err := BVW_CLIENT.PollingVideoEdit(editId) +if err != nil { + fmt.Printf("get edit job error: %+v\n", err) + return +} +fmt.Println("get edit job success : %+v\n", response) +``` + +# 错误处理 + +GO语言以error类型标识错误,BVW支持两种错误见下表: + +| 错误类型 | 说明 | +| --------------- | ------------------ | +| BceClientError | 用户操作产生的错误 | +| BceServiceError | BVW服务返回的错误 | + +用户使用SDK调用BVW相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// MEDIA_CLIENT 为已创建的BVW Client对象 +result, err := MEDIA_CLIENT.ListPipelines() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向BVW发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当BVW服务端出现异常时,BVW服务端会返回给用户相应的错误信息,以便定位问题。 + +## SDK日志 + +BVW GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +BVW GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +```go +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + +``` +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` +``` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +```go +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the BVW go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the BVW go sdk") +``` + +# 版本变更记录 + +首次发布: + +- BVW支持go-sdk啦,现在您可以通过golang调用BVW-SDK服务。当前SDK能力支持快编(视频编辑合成)服务、媒资库服务。 \ No newline at end of file diff --git a/bce-sdk-go/doc/CCE.md b/bce-sdk-go/doc/CCE.md new file mode 100644 index 0000000..55f9ace --- /dev/null +++ b/bce-sdk-go/doc/CCE.md @@ -0,0 +1,612 @@ +# CCE服务 + +# 概述 + +本文档主要介绍CCE GO SDK的使用。在使用本文档前,您需要先了解CCE的一些基本知识,并已开通了CCE服务。若您还不了解CCE,可以参考[产品描述](https://cloud.baidu.com/doc/CCE/s/Bjwvy0x5g)和[操作指南](https://cloud.baidu.com/doc/CCE/s/zjxpoqohb)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[CCE服务域名](https://cloud.baidu.com/doc/CCE/s/Fjwvy1fl4)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/CCE/s/Fjwvy1fl4)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | cce.bj.baidubce.com | HTTP and HTTPS +GZ | cce.gz.baidubce.com | HTTP and HTTPS +SU | cce.su.baidubce.com | HTTP and HTTPS +HKG| cce.hkg.baidubce.com| HTTP and HTTPS +FWH| cce.fwh.baidubce.com| HTTP and HTTPS +BD | cce.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云CCE,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CCE做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CCE Client + +CCE Client是CCE服务的客户端,为开发者与CCE服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CCE Client + +通过AK/SK方式访问CCE,用户可以参考如下代码新建一个CCE Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/cce" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个CCEClient + cceClient, err := cce.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为CCE的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`cce.bj.baidubce.com`。 + +### 使用STS创建CCE Client + +**申请STS token** + +CCE可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CCE,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建CCE Client** + +申请好STS后,可将STS Token配置到CCE Client中,从而实现通过STS Token创建CCE Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CCE Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/cce" //导入CCE服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CCE服务的Client对象,Endpoint使用默认值 + cceClient, err := cce.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "cce.bj.baidubce.com") + if err != nil { + fmt.Println("create cce client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + cceClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CCE Client时,无论对应CCE服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问CCE + +CCE支持HTTPS传输协议,您可以通过在创建CCE Client对象时指定的Endpoint中指明HTTPS的方式,在CCE GO SDK中使用HTTPS访问CCE服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +ENDPOINT := "https://cce.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +cceClient, _ := cce.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CCE Client + +如果用户需要配置CCE Client的一些细节的参数,可以在创建CCE Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CCE服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +//创建CCE Client对象 +AK, SK := , +ENDPOINT := "cce.bj.baidubce.com" +client, _ := cce.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +AK, SK := , +ENDPOINT := "cce.bj.baidubce.com" +client, _ := cce.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +AK, SK := , +ENDPOINT := "cce.bj.baidubce.com" +client, _ := cce.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CCE时,创建的CCE Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CCE Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# CCE管理 + +百度智能云容器引擎(Cloud Container Engine,即CCE)是高度可扩展的高性能容器管理服务,您可以在托管的云服务器实例集群上轻松运行应用程序。 + +> 注意: +> - 百度智能云容器引擎免费为用户提供服务,只会对其使用的资源例如BCC、BLB和EIP等资源收费 + +## 获取容器网络 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" +args := &cce.GetContainerNetArgs{ + // 容器所在VPC ID + VpcShortId: "vpc-xxxxxx", + VpcCidr: "192.168.0.0/24", +} +result, err := client.GetContainerNet(args) +if err != nil { + fmt.Printf("get container net error: %+v\n", err) + return +} +fmt.Printf("get cce container net success: %s\n", result.ContainerNet) +``` + +## 获取支持版本列表 +```go +result, err := client.ListVersions() +if err != nil { + fmt.Printf("list version error: %+v\n", err) + return +} +fmt.Printf("list version success with result: %+v\n", result) +``` + +## 创建CCE Cluster +使用以下代码可以创建一个CCE Cluster。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.CreateClusterArgs{ + // 指定CCE Cluster名称 + ClusterName: "sdk-test", + Version: listVersionResult.Data[0], + MainAvailableZone: "zoneA", + ContainerNet: getContainernetResult.ContainerNet, + // CCE 集群高级配置 + //AdvancedOptions: cce.AdvancedOptions{}, + // CCE CDS盘预挂载信息 + //CdsPreMountInfo: cce.CdsPreMountInfo{}, + Comment: "sdk create", + DeployMode: cce.DeployModeBcc, + OrderContent: &cce.BaseCreateOrderRequestVo{Items: []cce.Item{ + { + Config: cce.BccConfig{ + // BCC实例名称,若不指定,将随机生成 + Name: "sdk-create", + ProductType: cce.ProductTypePostpay, + InstanceType: cce.InstanceTypeG3, + Cpu: 1, + Memory: 2, + ImageType: cce.ImageTypeCommon, + SubnetUuid: SubnetId, + SecurityGroupId: Security, + AdminPass: AdminPass, + PurchaseNum: 2, + ImageId: "m-Nlv9C0tF", + ServiceType: cce.ServiceTypeBCC, + }, + }, + }}, +} +result, err := client.CreateCluster(args) +if err != nil { + fmt.Printf("create cce cluster error: %+v\n", err) + return +} +fmt.Printf("create cce cluster success with result: %+v\n", result) +``` + +## 获取CCE Cluster列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ListClusterArgs{} + +// 如果想获取某些状态下的集群,如RUNNING状态下的,可以配置参数 +args.Status = cce.ClusterStatusRunning + +result, err := client.ListClusters(args) +if err != nil { + fmt.Printf("list cce cluster error: %+v\n", err) + return +} +fmt.Printf("list cce cluster success with result: %+v\n", result) +``` + +## 获取CCE Cluster详情 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +result, err := client.GetCluster("cluster_uuid") +if err != nil { + fmt.Printf("get cce cluster error: %+v\n", err) + return +} +fmt.Printf("get cce cluster success with result: %+v\n", result) +``` + +## 获取CCE Cluster Node信息 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ListNodeArgs{ + ClusterUuid: "cluster_uuid", +} + +result, err := client.ListNodes(args) +if err != nil { + fmt.Printf("list cce cluster nodes error: %+v\n", err) + return +} +fmt.Printf("list cce cluster nodes success with result: %+v\n", result) +``` + +## CCE Cluster扩容 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ScalingUpArgs{ + ClusterUuid: "cluster_uuid", + // CCE CDS盘预挂载信息 + //CdsPreMountInfo: cce.CdsPreMountInfo{}, + OrderContent: &cce.BaseCreateOrderRequestVo{Items: []cce.Item{ + { + Config: cce.BccConfig{ + // BCC实例名称,若不指定,将随机生成 + Name: "sdk-create", + ProductType: cce.ProductTypePostpay, + InstanceType: cce.InstanceTypeG3, + Cpu: 1, + Memory: 2, + ImageType: cce.ImageTypeCommon, + SubnetUuid: SubnetId, + SecurityGroupId: Security, + AdminPass: AdminPass, + PurchaseNum: 2, + ImageId: "m-Nlv9C0tF", + ServiceType: cce.ServiceTypeBCC, + }, + }, + }}, +} + +result, err := client.ScalingUp(args) +if err != nil { + fmt.Printf("scaling up cce cluster error: %+v\n", err) + return +} +fmt.Printf("scaling up cce cluster success with result: %+v\n", result) +``` + +## CCE Cluster缩容 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ScalingDownArgs{ + ClusterUuid: "cluster_uuid", + // 可选择是否连带删除EIP和CDS + DeleteEipCds: true, + // 可选择是否连带删除快照 + DeleteSnap: true, + NodeInfo: []cce.NodeInfo{ + { + InstanceId: "instance_id", + }, + }, +} + +err = client.ScalingDown(args) +if err != nil { + fmt.Printf("scaling down cce cluster error: %+v\n", err) + return +} +``` + +## 移除CCE Cluster节点 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ShiftOutNodeArgs{ + ClusterUuid: "cluster_uuid", + NodeInfoList: []cce.CceNodeInfo{ + {InstanceId: "instance_id"}, + }, +} + +err = client.ShiftOutNode(args) +if err != nil { + fmt.Printf("shift node out from cce cluster error: %+v\n", err) + return +} +``` + +## 移入CCE Cluster节点 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ShiftInNodeArgs{ + ClusterUuid: "cluster_uuid", + // 是否要重装系统 + NeedRebuild: false, + // 若重装系统,则选择系统镜像ID + //ImageId: "", + // 若重装系统,则配置新的密码 + //AdminPass: AdminPass, + InstanceType: cce.ShiftInstanceTypeBcc, + NodeInfoList: []cce.CceNodeInfo{ + { + InstanceId: "instance_id", + // 若选择不重装系统,则需要输入该节点密码 + AdminPass: AdminPass, + }, + }, +} + +err = client.ShiftInNode(args) +if err != nil { + fmt.Printf("shift node into cce cluster error: %+v\n", err) + return +} +``` + +## 获取CCE Cluster可移入节点列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.ListExistedNodeArgs{ + ClusterUuid: "cluster_uuid", +} + +result, err := client.ListExistedBccNode(args) +if err != nil { + fmt.Printf("list cce cluster exist node error: %+v\n", err) + return +} +fmt.Printf("list cce cluster exist node success with result: %+v\n", result) +``` + +## 获取CCE Cluster kubeconfig配置 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.GetKubeConfigArgs{ + ClusterUuid: "cluster_uuid", +} + +// 若要获取公网访问配置,可以选择默认default +args.Type = cce.KubeConfigTypeDefault + +// 若要获取VPC内部访问配置,可以选择 +args.Type = cce.KubeConfigTypeIntraVpc + +// 若要获取B区内部访问配置,可以选择 +args.Type = cce.KubeConfigTypeInternal + +configResult, err := client.GetKubeConfig(configArgs) +if err != nil { + fmt.Printf("create cce cluster error: %+v\n", err) + return +} +fmt.Printf("create cce cluster success with result: %+v\n", result) +``` + +## 删除CCE 集群 +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +args := &cce.DeleteClusterArgs{ + ClusterUuid: "cluster_uuid", + // 是否需要删除EIP和CDS + DeleteEipCds: true, + // 是否需要删除快照 + DeleteSnap: true, +} +err = client.DeleteCluster(args) +if err != nil { + fmt.Printf("delete cce cluster error: %+v\n", err) + return +} +``` + +# 错误处理 + +GO语言以error类型标识错误,CCE支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | CCE服务返回的错误 + +用户使用SDK调用CCE相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// client 为已创建的cce Client对象 +args := &cce.ListClusterArgs{} +result, err := client.ListClusters(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CCE发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当CCE服务端出现异常时,CCE服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[CCE错误码](https://cloud.baidu.com/doc/CCE/s/4jwvy1evj) + +## SDK日志 + +CCE GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +CCE GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the CCE go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the CCE go sdk") +``` + + +# 版本变更记录 + +## v0.9.5 [2020-07-02] + +首次发布: + + - 获取CCE支持版本列表,获取CCE容器网络。 + - 支持创建CCE,获取CCE详情,获取CCE列表,CCE扩容,CCE缩容,获取CCE节点信息,删除CCE。 + - 节点移入CCE集群,节点移处CCE集群,获取可移入节点列表。 \ No newline at end of file diff --git a/bce-sdk-go/doc/CCEv2.md b/bce-sdk-go/doc/CCEv2.md new file mode 100644 index 0000000..d2151ce --- /dev/null +++ b/bce-sdk-go/doc/CCEv2.md @@ -0,0 +1,949 @@ +# CCE服务 v2版本 + +# 概述 + +本文档主要介绍CCE GO SDK的使用。在使用本文档前,您需要先了解CCE的一些基本知识,并已开通了CCE服务。若您还不了解CCE,可以参考[产品描述](https://cloud.baidu.com/doc/CCE/s/Bjwvy0x5g)和[操作指南](https://cloud.baidu.com/doc/CCE/s/zjxpoqohb)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[CCE服务域名](https://cloud.baidu.com/doc/CCE/s/Fjwvy1fl4)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/CCE/s/Fjwvy1fl4)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | cce.bj.baidubce.com | HTTP and HTTPS +GZ | cce.gz.baidubce.com | HTTP and HTTPS +SU | cce.su.baidubce.com | HTTP and HTTPS +HKG| cce.hkg.baidubce.com| HTTP and HTTPS +FWH| cce.fwh.baidubce.com| HTTP and HTTPS +BD | cce.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云CCE,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CCE做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CCE Client + +CCE Client是CCE服务的客户端,为开发者与CCE服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CCE Client + +通过AK/SK方式访问CCE,用户可以参考如下代码新建一个CCE Client: +```go +import ( + "github.com/baidubce/bce-sdk-go/services/ccev2" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + AK, SK := , + + //用户指定的endpoint + ENDPOINT := "endpoint" + + // 初始化一个CCEClient + ccev2Client, err := ccev2.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`AK`对应控制台中的“Access Key ID”,`SK`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为CCE的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`cce.bj.baidubce.com`。 + +### 使用STS创建CCE Client + +**申请STS token** + +CCE可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CCE,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建CCE Client** + +申请好STS后,可将STS Token配置到CCE Client中,从而实现通过STS Token创建CCE Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CCE Client对象: +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/cce" //导入CCE服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CCE服务的Client对象,Endpoint使用默认值 + ccev2Client, err := ccev2.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "cce.bj.baidubce.com") + if err != nil { + fmt.Println("create cce client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + ccev2Client.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CCE Client时,无论对应CCE服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问CCE + +CCE支持HTTPS传输协议,您可以通过在创建CCE Client对象时指定的Endpoint中指明HTTPS的方式,在CCE GO SDK中使用HTTPS访问CCE服务: +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" +AK, SK := , +ENDPOINT := "https://cce.bj.baidubce.com" //指明使用HTTPS协议 + +ccev2Client, _ := ccev2.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CCE Client + +如果用户需要配置CCE Client的一些细节的参数,可以在创建CCE Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CCE服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +//创建CCE Client对象 +AK, SK := , +ENDPOINT := "cce.bj.baidubce.com" + +ccev2Client, _ := ccev2.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +ccev2Client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +AK, SK := , +ENDPOINT := "cce.bj.baidubce.com" + +ccev2Client, _ := ccev2.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +ccev2Client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +ccev2Client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/cce" + +AK, SK := , +ENDPOINT := "ccev2.bj.baidubce.com" + +ccev2Client, _ := ccev2.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +ccev2Client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +ccev2Client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CCE时,创建的CCE Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CCE Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# CCE管理 + +百度智能云容器引擎(Cloud Container Engine,即CCE)是高度可扩展的高性能容器管理服务,您可以在托管的云服务器实例集群上轻松运行应用程序。 + +> 注意: +> - 百度智能云容器引擎免费为用户提供服务,只会对其使用的资源例如BCC、BLB和EIP等资源收费 + +## 创建集群 +使用以下代码可以创建一个CCE Cluster。 +```go +args := &ccev2.CreateClusterArgs{ + CreateClusterRequest: &ccev2.CreateClusterRequest{ + ClusterSpec: &types.ClusterSpec{ + ClusterName: "your-cluster-name", + K8SVersion: types.K8S_1_16_8, + RuntimeType: types.RuntimeTypeDocker, + VPCID: "vpc-id", + MasterConfig: types.MasterConfig { + MasterType: types.MasterTypeManaged, + ClusterHA: 1, + ExposedPublic: false, + ClusterBLBVPCSubnetID: "cluster-blb-vpc-subnet-id", + ManagedClusterMasterOption: types.ManagedClusterMasterOption{ + MasterVPCSubnetZone: types.AvailableZoneA, + MasterFlavor: types.MasterFlavorSmall, + }, + }, + ContainerNetworkConfig: types.ContainerNetworkConfig{ + Mode: types.ContainerNetworkModeKubenet, + LBServiceVPCSubnetID: "lb-service-vpc-subnet-id", + ClusterPodCIDR: "172.28.0.0/16", + ClusterIPServiceCIDR: "172.31.0.0/16", + }, + }, + NodeSpecs: []*ccev2.InstanceSet{ + &ccev2.InstanceSet{ + Count: 1, + InstanceSpec: types.InstanceSpec{ + InstanceName: "", + ClusterRole: types.ClusterRoleNode, + Existed: false, + MachineType: types.MachineTypeBCC, + InstanceType: bccapi.InstanceTypeN3, + VPCConfig: types.VPCConfig{ + VPCID: "vpc-id", + VPCSubnetID: "vpc-subnet-id", + SecurityGroupID: "security-group-id", + AvailableZone: types.AvailableZoneA, + }, + InstanceResource:types.InstanceResource{ + CPU: 4, + MEM: 8, + RootDiskSize: 40, + LocalDiskSize: 0, + CDSList: []types.CDSConfig{}, + }, + ImageID: "image-id", + InstanceOS: types.InstanceOS{ + ImageType: bccapi.ImageTypeSystem, + }, + NeedEIP: false, + AdminPassword: "admin-password", + SSHKeyID: "ssh-key-id", + InstanceChargingType: bccapi.PaymentTimingPostPaid, + RuntimeType: types.RuntimeTypeDocker, + }, + }, + }, + }, +} + +resp, err := ccev2Client.CreateCluster(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 查询集群详情 +使用以下代码可以查询一个集群的详细信息。 +```go +clusterID := "cluster-id" +resp, err := ccev2Client.GetCluster(clusterID) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 获取集群列表 +使用以下代码可以按关键字获取排序后的集群列表 +```go +args := &ccev2.ListClustersArgs{ + KeywordType: "clusterName", + Keyword: "", + OrderBy: "clusterID", + Order: ccev2.OrderASC, + PageSize: 10, + PageNum: 1, +} + +resp, err := ccev2Client.ListClusters(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 删除集群 +使用以下代码可以删除一个集群 +```go +args := &ccev2.DeleteClusterArgs{ + ClusterID: "cluster-id", + DeleteResource: true, + DeleteCDSSnapshot: true, +} + +resp, err := ccev2Client.DeleteCluster(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 创建节点(集群扩容) +使用以下代码可以新创建节点并对集群进行扩容 +```go +args := &ccev2.CreateInstancesArgs{ + ClusterID: "cluster-id", + Instances: []*ccev2.InstanceSet{ + { + Count: 1, + InstanceSpec: types.InstanceSpec{ + ClusterRole: types.ClusterRoleNode, + Existed: false, + MachineType: types.MachineTypeBCC, + InstanceType: bccapi.InstanceTypeN3, + VPCConfig: types.VPCConfig{ + VPCID: "vpc-id", + VPCSubnetID: "vpc-subnet-id", + SecurityGroupID: "security-group-id", + AvailableZone: types.AvailableZoneA, + }, + InstanceResource:types.InstanceResource{ + CPU: 1, + MEM: 4, + RootDiskSize: 40, + LocalDiskSize: 0, + }, + ImageID: "image-id", + InstanceOS: types.InstanceOS{ + ImageType: bccapi.ImageTypeSystem, + }, + NeedEIP: false, + AdminPassword: "admin-password", + SSHKeyID: "ssh-key-id", + InstanceChargingType: bccapi.PaymentTimingPostPaid, + RuntimeType: types.RuntimeTypeDocker, + }, + }, + }, +} + +resp, err := ccev2Client.CreateInstances(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + + +## 获取节点详情 +使用以下代码可以获取一个节点的详细信息 +```go +args := &ccev2.GetInstanceArgs{ + ClusterID: "cluster-id", + InstanceID: "instance-id", +} + +resp, err := ccev2Client.GetInstance(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 获取集群的节点列表 +使用以下代码可以获取一个集群的节点列表 +```go +args := &ccev2.ListInstancesByPageArgs { + ClusterID: "cluster-id", + Params: &ccev2.ListInstancesByPageParams{ + KeywordType: ccev2.InstanceKeywordTypeInstanceName, + Keyword: "", + OrderBy: "createdAt", + Order: ccev2.OrderASC, + PageNo: 1, + PageSize: 10, + }, +} + +resp, err := ccev2Client.ListInstancesByPage(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 获取节点组的节点列表 +使用以下代码可以获取节点组的节点列表 +```go +args := &ListInstanceByInstanceGroupIDArgs{ + ClusterID: "your-cluster-id", + InstanceGroupID: "your-instance-group-id", + PageSize: 0, + {ageNo: 0, +} +resp, err := ccev2Client.ListInstancesByInstanceGroupID(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 更新节点配置 +使用以下代码可以更新节点的配置信息。需要注意不是所有配置信息都是可更改的。 +```go +args := &UpdateInstanceArgs{ + ClusterID: "your-cluster-id", + InstanceID: "your-instance-id", + InstanceSpec: YOUR_NEW_INSTANCE_SPEC, +} +respUpdate, err := CCE_CLIENT.UpdateInstance(args) + +s, _ := json.MarshalIndent(respUpdate, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 删除节点(集群缩容) +使用以下代码可以删除集群内的一个节点 +```go +args := &ccev2.DeleteInstancesArgs{ + ClusterID: "cluster-id", + DeleteInstancesRequest: &ccev2.DeleteInstancesRequest{ + InstanceIDs: []string{ "instance-id" }, + DeleteOption: &types.DeleteOption{ + MoveOut: false, + DeleteCDSSnapshot: true, + DeleteResource: true, + }, + }, +} + +resp, err := ccev2Client.DeleteInstances(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 检查集群网络网段 +使用以下代码可以检查集群网络网段是否冲突 +```go +args := &ccev2.CheckClusterIPCIDArgs{ + VPCID: "vpc-id", + VPCCIDR: "192.168.0.0/16", + ClusterIPCIDR: "172.31.0.0/16", + IPVersion: "ipv4", +} + +resp, err := ccev2Client.CheckClusterIPCIDR(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 检查容器网络网段 +使用以下代码可以检测容器网络网段是否冲突 +```go +args := &ccev2.CheckContainerNetworkCIDRArgs{ + VPCID: "vpc-id", + VPCCIDR: "192.168.0.0/16", + ContainerCIDR: "172.28.0.0/16", + ClusterIPCIDR: "172.31.0.0/16", + MaxPodsPerNode: 256, +} + +resp, err := ccev2Client.CheckContainerNetworkCIDR(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 推荐集群网络网段 +使用以下代码可以推荐可使用的集群网络网段 +```go +args := &ccev2.RecommendClusterIPCIDRArgs{ + ClusterMaxServiceNum: 2, + ContainerCIDR: "172.28.0.0/16", + IPVersion: "ipv4", + PrivateNetCIDRs: []ccev2.PrivateNetString{ccev2.PrivateIPv4Net172}, + VPCCIDR: "192.168.0.0/16", +} + +resp, err := ccev2Client.RecommendClusterIPCIDR(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 推荐容器网络网段 +使用以下代码可以推荐可使用的容器网络网段 +```go +args := &ccev2.RecommendContainerCIDRArgs{ + ClusterMaxNodeNum: 2, + IPVersion: "ipv4", + K8SVersion: types.K8S_1_16_8, + MaxPodsPerNode: 32, + PrivateNetCIDRs: []ccev2.PrivateNetString{ccev2.PrivateIPv4Net172}, + VPCCIDR: "192.168.0.0/16", + VPCID: "vpc-id", +} + +resp, err := ccev2Client.RecommendContainerCIDR(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 获取集群配额 +使用以下代码可以获取集群配额 +```go +resp, err := ccev2Client.GetClusterQuota() +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 获取集群节点配额 +使用以下代码可以获取集群的节点配额 +```go +clusterID := "cluster-id" + +resp, err := ccev2Client.GetClusterNodeQuota(clusterID) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 创建节点组 +使用以下代码可以创建节点组 +```go +args := &CreateInstanceGroupArgs{ + ClusterID: CCE_CLUSTER_ID, + Request: &CreateInstanceGroupRequest{ + types.InstanceGroupSpec{ + InstanceGroupName: "your-instance-group-name", + CleanPolicy: types.DeleteCleanPolicy, + Replicas: 3, + InstanceTemplate: types.InstanceTemplate{ + InstanceSpec: types.InstanceSpec{ + ClusterRole: types.ClusterRoleNode, + Existed: false, + MachineType: types.MachineTypeBCC, + InstanceType: bccapi.InstanceTypeN3, + VPCConfig: types.VPCConfig{ + VPCID: "your-vpc-id", + VPCSubnetID: "your-vpc-subnet-id", + SecurityGroupID: "your-secuirity-group-id", + AvailableZone: types.AvailableZoneA, + }, + DeployCustomConfig: types.DeployCustomConfig{ + PreUserScript: "your-script", + PostUserScript:"your-script", + }, + InstanceResource: types.InstanceResource{ + CPU: 1, + MEM: 4, + RootDiskSize: 40, + LocalDiskSize: 0, + }, + ImageID: IMAGE_TEST_ID, + InstanceOS: types.InstanceOS{ + ImageType: bccapi.ImageTypeSystem, + }, + NeedEIP: false, + AdminPassword: "your-admin-password", + SSHKeyID: "your-ssh-key-id", + InstanceChargingType: bccapi.PaymentTimingPostPaid, + RuntimeType: types.RuntimeTypeDocker, + }, + }, + }, + }, +} +resp, err := ccev2Client.CreateInstanceGroup(args) + +s, _ = json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + + +## 获取节点组列表 +使用以下代码可以获取节点组列表 +```go +args := &ListInstanceGroupsArgs{ + ClusterID: "your-cluster-id", + ListOption: &InstanceGroupListOption{ + PageNo: 0, + PageSize: 0, + }, +} +resp, err := ccev2Client.ListInstanceGroups(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + + +## 查询节点组详情 +使用以下代码可以查询节点组详情 +```go +args := &GetInstanceGroupArgs{ + ClusterID: "your-cluster-id", + InstanceGroupID: "your-instance-group-id", +} +resp, err := ccev2Client.GetInstanceGroup(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + + +## 修改节点组内节点副本数 +使用以下代码可以修改节点组内节点副本数 +```go +args := &UpdateInstanceGroupReplicasArgs{ + ClusterID: "your-cluster-id", + InstanceGroupID: "your-instance-group-id", + Request: &UpdateInstanceGroupReplicasRequest{ + Replicas: 1, + DeleteInstance: true, + DeleteOption: &types.DeleteOption{ + MoveOut: false, + DeleteCDSSnapshot: true, + DeleteResource: true, + }, + }, +} +resp, err := ccev2Client.UpdateInstanceGroupReplicas(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 修改节点组Autoscaler配置 +使用以下代码可以修改节点Autoscaler配置 +```go +args := &UpdateInstanceGroupClusterAutoscalerSpecArgs{ + ClusterID: "your-cluster0id", + InstanceGroupID: "cce-instance-group-id", + Request: &ClusterAutoscalerSpec{ + Enabled: true, + MinReplicas: 2, + MaxReplicas: 5, + ScalingGroupPriority: 1, + }, +} + +resp, err := ccev2Client.UpdateInstanceGroupClusterAutoscalerSpec(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 删除节点组 +使用以下代码可以删除节点组 +```go +args := &DeleteInstanceGroupArgs{ + ClusterID: "your-cluster-id", + InstanceGroupID: "your-instance-group-id", + DeleteInstances: true, +} +resp, err := ccev2Client.DeleteInstanceGroup(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 创建Autoscaler +使用以下代码为集群创建Autoscaler +```go +args := &CreateAutoscalerArgs{ + ClusterID: "your-cce-cluster-id", +} + +resp, err := ccev2Client.CreateAutoscaler(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 查询Autoscaler +使用以下代码可以查询集群的Autoscaler +```go +args := &GetAutoscalerArgs{ + ClusterID: "your-cce-cluster-id", +} + +resp, err := ccev2Client.GetAutoscaler(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 更新Autoscaler +使用以下代码可以更新集群的Autoscaler +```go +args := &UpdateAutoscalerArgs{ + ClusterID: "your-cluster-id", + AutoscalerConfig: ClusterAutoscalerConfig{ + ReplicaCount: 5, + ScaleDownEnabled: true, + Expander: "random", + }, +} + +resp, err := ccev2Client.UpdateAutoscaler(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 获取Kubeconfig +使用以下代码可以获取集群的Kubeconfig +```go +args := &GetKubeConfigArgs{ + ClusterID: "your-cluster-id", + KubeConfigType: "kubeconfig-type-you-need", +} + +resp, err := ccev2Client.GetAdminKubeConfig(args) + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +# 错误处理 + +GO语言以error类型标识错误,CCE支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | CCE服务返回的错误 + +用户使用SDK调用CCE相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// client 为已创建的cce Client对象 +args := &ccev2.ListClusterArgs{} +result, err := ccev2Client.ListClusters(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CCE发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当CCE服务端出现异常时,CCE服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[CCE错误码](https://cloud.baidu.com/doc/CCE/s/4jwvy1evj) + +## SDK日志 + +CCE GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +CCE GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +```go +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +```go +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the CCE go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the CCE go sdk") +``` + + +# 版本变更记录 + +## v1.0.0 [2020-08-07] + +首次发布: + - 支持创建集群、获取集群列表、获取集群详情、删除集群。 + - 支持创建节点(集群扩容)、获取集群的节点列表、获取节点详情、删除节点(集群缩容) + - 支持检查集群网络网段、检查容器网络网段、推荐集群网络网段、推荐容器网络网段 + - 支持查询集群配额、集群节点配额 + + +## v1.1.0 [2020-08-20] + + 增加节点组相关接口: + - 支持节点组创建、获取节点组列表、查询节点组详情、修改节点组内节点副本数、删除节点组 + - 获取节点组的节点列表 + + +## v1.2.0 [2020-09-18] + +增加Autoscaler相关接口: + - 支持集群Autoscaler的初始化、查询与更新 +增加Kubeconfig相关接口: + - 支持获取集群的kubeconfig +增加Instance 相关接口: + - 支持对Instance部分属性的更新 + +## v1.3.0 [2021-06-17] + +Instance 增加字段: + - 支持新建和移入竞价实例(bid) + - 支持新建和移入实例时, 自定义 K8S Node Annotation + +## v1.4.0 [2021-06-29] + +增加InstanceGroup相关接口: + - 支持创建 InstanceGroup 扩容任务 + - 支持创建 InstanceGroup 缩容任务 +增加Task相关接口: + - 支持查询指定Task执行详情 + - 支持查询Task列表 diff --git a/bce-sdk-go/doc/CDN.md b/bce-sdk-go/doc/CDN.md new file mode 100644 index 0000000..09ae827 --- /dev/null +++ b/bce-sdk-go/doc/CDN.md @@ -0,0 +1,1440 @@ +CDN服务 + +# 概述 + +本文档主要介绍CDN GO SDK的使用。在使用本文档前,您需要先了解CDN的一些基本知识,并已开通了CDN服务。若您还不了解CDN,可以参考[产品描述](https://cloud.baidu.com/doc/CDN/index.html)和[快速入门](https://cloud.baidu.com/doc/CDN/s/ujwvye8ao)。 + +# 初始化 + +## 确认Endpoint + +目前使用CDN服务时,CDN的Endpoint都统一使用`https://cdn.baidubce.com`,这也是默认值。 + +## 获取密钥 + +要使用百度云CDN,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CDN做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 使用AK/SK新建CDN Client + +通过AK/SK方式访问CDN,用户可以参考如下代码新建一个CDN Client: + +```go +ak := "your_access_key_id" +sk := "your_secret_key_id" +endpoint := "https://cdn.baidubce.com" +client, err := cdn.NewClient(ak, sk, endpoint) +``` + +在上面代码中,变量`ak`对应控制台中的“Access Key ID”,变量`sk`对应控制台中的“Access Key Secret”,获取方式请参考《 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。变量`endpoint`必须为`https://cdn.baidubce.com`,也是默认值,为空表示使用默认值,设置为其他则SDK无法工作。 + +在下面的示例中,会频繁使用到GetDefaultClient函数,它的定义为: + +```go +func GetDefaultClient() *cdn.Client { + ak := "your_access_key_id" + sk := "your_secret_key_id" + endpoint := "https://cdn.baidubce.com" + + // ignore error in test, but you should handle error in dev + client, _ := cdn.NewClient(ak, sk, endpoint) + return client +} +``` + +## 自定义HTTP请求 + +> 支持对任何开放接口自定义HTTP请求 + +示例展示了不通过SDK的方法,而是自行根据[文档](https://cloud.baidu.com/doc/CDN/s/qjwvyexh6)构造请求,查询某个域名是否可以添加到百度云CDN系统。 + +```go +cli := GetDefaultClient() +method := "GET" +urlPath := fmt.Sprintf("/v2/domain/%s/valid", testDomain) +var params map[string]string +// 此请求头非必须,仅测试发送请求头 +reqHeaders := map[string]string{ + "X-Test": "go-sdk-test", +} +var bodyObj interface{} +var respObj interface{} +err := cli.SendCustomRequest(method, urlPath, params, reqHeaders, bodyObj, &respObj) +fmt.Printf("err:%+v\n", err) +fmt.Printf("respObj details:\n\ttype:%T\n\tvalue:%+v", respObj, respObj) +``` + +## 域名操作接口 + +### 域名列表查询 ListDomains + +> 查询该用户账户下拥有的加速域名 + +```go +marker := "" +cli := GetDefaultClient() +domains, nextMarker, err := cli.ListDomains(marker) +fmt.Printf("domains:%+v\n", domains) +fmt.Printf("nextMarker:%+v\n", nextMarker) +fmt.Printf("err:%+v\n", err) +``` + +`marker`参数表示从这个字符串所代表的索引开始查询域名列表,空表示从头开始。目前服务器处理分页size是一个很大的数,所以使用的时候将marker赋值为空即可。ListDomains返回的`nextMarker`表示下一个域名列表索引 ,空表示从`marker`开始之后的域名列表全部被获取,非空可用于传递到ListDomains参数。`domains`是一个string slice,表示域名列表数据,如: `["1.baidu.com", "2.baidu.com"]` + +### 查询用户名下所有域名 GetDomainStatus + +> 查询用户名下所有域名和域名状态,可以根据特定状态查询属于这个状态的域名。 + +```go +cli := client.GetDefaultClient() +status := "ALL" +domainStatus, err := cli.GetDomainStatus(status, "") +fmt.Printf("domainStatus:%+v\n", domainStatus) +fmt.Printf("err:%+v\n", err) +``` + +`status`表示域名的状态,如果为`ALL`,表示查询所有状态的域名,如果为`RUNNING`查询已经加速的域名,`STOPPED`查询停止加速的域名,`OPERATING`查询操作中的域名。 +`domainStatus`是**DomainStatus**类型对象,如下所示: + +| 字段 | 类型 | 说明 | +| ------ | ------ | --------------------------------------------------- | +| Domain | string | 域名,如`www.baidu.com` | +| Status | string | 域名状态,合法值为`RUNNING`、`STOPPED`和`OPERATING` | + +`domainStatus`的示例数据如:`[{"Domain":"1.baidu.com", "Status":"RUNNING"}, {"Domain":"2.baidu.com", "Status":"STOPPED"}]` + +### 查询域名是否可添加 IsValidDomain + +> 查询特定域名是否可以使用CDN加速,一个可以被添加的域名必须是合法的域名,不可重复添加,必须通过ICP备案。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" +domainValidInfo, err := cli.IsValidDomain(testDomain) +fmt.Printf("domainValidInfo:%+v\n", domainValidInfo) +fmt.Printf("err:%+v\n", err) +``` +`testDomain`是要测试的域名,`domainValidInfo`是**DomainValidInfo**类型对象,表示的是关于是否可添加的详细信息 + +| 字段 | 类型 | 说明 | +| ------ | ------ | --------------------------------------------------- | +| Domain | string | 域名,如`www.baidu.com` | +| IsValid | bool | true表示该域名可添加,false表示该域名不可被添加 | +| Message | string | 当IsValid为false,表示域名不可被添加的原因;当IsValid为true时,为空 | + +### 创建加速域名接口 CreateDomain + +> 添加一个加速域名到用户名下,该域名在调用IsValidDomain的时候返回必须为true。创建加速域名必须设置源站。 + +```go +cli := client.GetDefaultClient() +domainCreatedInfo, err := cli.CreateDomain("test_go_sdk.baidu.com", &api.OriginInit{ + Origin: []api.OriginPeer{ + { + Peer: "1.1.1.1", + Host: "www.baidu.com", + Backup: true, + Follow302: true, + }, + { + Peer: "http://2.2.2.2", + Host: "www.baidu.com", + Backup: false, + Follow302: true, + }, + }, + DefaultHost: "www.baidu.com", + Form: "default", +}) +fmt.Printf("domainCreatedInfo:%+v\n", domainCreatedInfo) +fmt.Printf("err:%+v\n", err) +``` + +`api.OriginPeer`表示一个源站,`api.OriginInit`表示对于这个加速域名的源站配置,包括一个或多个源站,和一个默认的回源host,表示为`DefaultHost`。`Form`表示加速服务类型,默认为`default`,其他可选的服务类型有`image`表示图片小文件,`download`表示大文件下载,`media`表示流媒体点播,`dynamic`表示动静态加速。 +源站信息**api.OriginPeer**的结构如下: + +| 字段 | 类型 | 说明 | +| --------- | ------ | ------------------------------------------------------------ | +| Peer | string | 源站的endpoint,如`http://2.2.2.2:9090`或 `https://test.baidu.com:9090`,源站类型可以为域名形式、IP形式和bucket,示例代码展示的是IP形式的源站类型,需要注意的是一个域名所有的源站必须具有相同的源站类型。**如果使用的是默认端口,即HTTP的80和HTTPS的443,CDN系统会将源站视为HTTP和HTTPS两种协议都支持**。 | +| Host | string | 表示回源时在HTTP请求头中携带的Host,如果没有设置则使用`DefaultHost` | +| Backup | bool | 表示是否为备用源站,备用源站在主源站都不可用的情况下才会使用,false表示这个源站是主源站。需要注意的是在golang中bool对象默认值为false,如果没有显式设置Backup的值,那么默认就是false。 | +| Follow302 | bool | true表示当回源到源站时源站返回302时,CDN系统会处理Location重定向,主动获取资源返回给客户端。false表示当源站返回302时,CDN系统透传302给客户端。**需要注意的是,目前Follow302已经修改为所有源站级别的配置,所以要求所有的源站Follow302必须一致,否则可能会出现不可预料的结果**。 | + +### 启用/停止/删除加速域名 EnableDomain/DisableDomain/DeleteDomain + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 启用加速域名 +err := cli.EnableDomain(testDomain) +fmt.Printf("err:%+v\n", err) + +// 停用加速域名 +err = cli.DisableDomain(testDomain) +fmt.Printf("err:%+v\n", err) + +// 删除该用户名下的加速域名 +err = cli.DeleteDomain(testDomain) +fmt.Printf("err:%+v\n", err) +``` + +## 域名配置接口 + +### 查询加速域名详情 GetDefaultClient + +> 查询某个特定域名的全部配置信息 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" +domainConfig, err := cli.GetDomainConfig(testDomain) +fmt.Printf("domainConfig:%+v\n", domainConfig) +fmt.Printf("err:%+v\n", err) +``` + +`domainConfig`是`*api.DomainConfig`类型的对象,他的结构相对比较复杂,如下所示: + +| 字段 | 类型 | 说明 | +| -------------- | ---------------- | ------------------------------------------------------------ | +| Domain | string | 域名信息,如:`test.baidu.com`。 | +| Cname | string | 域名的CNAME,如:`test.baidu.com.a.bdydns.com`。 | +| Status | string | 域名状态,合法值为`RUNNING`、`STOPPED`和`OPERATING`。 | +| CreateTime | string | 域名创建的时间,UTC时间,如:`2019-09-02T10:08:38Z。` | +| LastModifyTime | string | 上次修改域名配置的时间,UTC时间,如:`2019-09-06T15:00:21Z`。 | +| IsBan | string | 是否被禁用,禁用的意思是欠费或者其他违规操作被系统封禁,被封禁的域名不拥有加速服务。`ON`表示为被封禁,`YES`表示被封禁了。 | +| Origin | []api.OriginPeer | 源站信息,在创建加速域名接口有详细说明。 | +| DefaultHost | string | 默认的回源host,在创建加速域名接口有详细说明。 | +| CacheTTL | []api.CacheTTL | 文件类型与路径的缓存策略,在`设置/查询缓存过期规则`小段有详细说明。 | +| LimitRate | int | 下载限速,单位Byte/s。 | +| RequestAuth | api.RequestAuth | 访问鉴权配置,在设置访问鉴权有详细说明。 | +| Https | api.HTTPSConfig | HTTPS加速配置,在设置HTTPS加速有详细说明。 | +| FollowProtocol | bool | 是否开启了协议跟随回源,true表示开启了协议跟随回源,即访问资源是https://xxx或http://xxx之类的url,回源也使用相对应的scheme,即分别为HTTPS和HTTP。 | +| SeoSwitch | api.SeoSwitch | seo 开关配置,在设置SEO开关属性有详细说明。 | + +### 设置/查询缓存过期规则 SetCacheTTL/GetCacheTTL + +> 设置针对文件、目录和错误码等相关的缓存策略,合理设置缓存策略可以提高命中率。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置缓存策略使用源站规则 +err := cli.SetCacheTTL(testDomain, []api.CacheTTL{ + { + Type: "origin", + Value: "-", + TTL: 0, + }, +}) +fmt.Printf("err:%+v\n", err) + +// 设置缓存策略,分别设置后缀规则、目录规则、路径完全匹配和错误码 +err = cli.SetCacheTTL(testDomain, []api.CacheTTL{ + { + Type: "suffix", + Value: ".jpg", + TTL: 420000, + Weight: 30, + }, + { + Type: "path", + Value: "/js", + TTL: 10000, + }, + { + Type: "exactPath", + Value: "index.html", + TTL: 600, + Weight: 100, + }, + { + Type: "code", + Value: "404", + TTL: 600, + Weight: 100, + }, +}) +fmt.Printf("err:%+v\n", err) + +// 查询缓存策略 +cacheTTls, err := cli.GetCacheTTL(testDomain) +fmt.Printf("cacheTTls:%+v\n", cacheTTls) +fmt.Printf("err:%+v\n", err) +``` + +`cacheTTls`包含全部的缓存策略,每一个缓存策略用`api.CacheTTL`类型的对象表示,如下关于缓存策略结构的说明。 + +| 字段 | 类型 | 说明 | +| ------ | ------ | ------------------------------------------------------------ | +| Type | string | 缓存策略的类型。合法的类型有:`suffix`、`path`、`origin`、`code`和`exactPath`。"suffix"表示文件名后缀,"path"表示url中的目录,"origin"表示源站规则,此规则只有一条,只表示出权重即可,value为"-", ttl为 0,"code"表示异常码缓存,如可以配置404缓存100s ,“exactPath”表示路径完全匹配。 | +| Value | string | Type所指定类型的配置规则。 | +| Weight | int | 权重,0-100的整数,权重越高优先级越高,默认为0,优先级在为code类型下是没有作用的,可以忽略。权重越大,优先级越高,规则优先生效。不推荐两条缓存策略配置相同的权重,如果权重相同,会随机选择其中一条策略生效。 | +| TTL | int | 缓存时间,单位为秒。 | + +### 设置/查询缓存参数过滤规则 SetCacheUrlArgs/GetCacheUrlArgs + +> 设置缓存key,缓存key为CDN系统对某个资源的进行缓存的时候所采用的key,一个url可能带有很多参数,那么时候所有的参数都需要放在缓存key中呢?其实是不必的,下面展示了不同的设置。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置全URL缓存 +err := cli.SetCacheUrlArgs(testDomain, &api.CacheUrlArgs{ + CacheFullUrl: true, +}) +fmt.Printf("err:%+v\n", err) + +// 设置缓存带有部分参数 +err = cli.SetCacheUrlArgs(testDomain, &api.CacheUrlArgs{ + CacheFullUrl: false, + CacheUrlArgs: []string{"name", "id"}, +}) +fmt.Printf("err:%+v\n", err) + +// 设置忽略所有参数 +err = cli.SetCacheUrlArgs(testDomain, &api.CacheUrlArgs{ + CacheFullUrl: false, + CacheUrlArgs: []string{"name", "id"}, +}) +fmt.Printf("err:%+v\n", err) + +// 查询关于URL参数缓存设置 +cacheUrlArgs, err := cli.GetCacheUrlArgs(testDomain) +fmt.Printf("cacheUrlArgs:%+v\n", cacheUrlArgs) +``` + +`cacheUrlArgs`是`api.CacheUrlArgs`类型的对象,下面是详细说明: + +| 字段 | 类型 | 说明 | +| ------------ | -------- | ------------------------------------------------------------ | +| CacheFullUrl | bool | true或false,true表示支持全URL缓存,false表示忽略参数缓存(可保留部分参数)。注意golang中如果不显式赋值CacheFullUrl为true或false,那么取零值false。 | +| CacheUrlArgs | []string | CacheFullUrl为true时,此项不起作用;CacheFullUrl为false时,此项表示保留的参数列表,如果为空,表示忽略所有参数。 | + +### 设置/查询自定义错误码页面 SetErrorPage/GetErrorPage + +> 用户可以定义当访问源站或CDN系统内部出现错误时(通常是返回4xx或5xx错误码),有CDN系统返回给用户的重定向页面,用户可以设置这个重定向页面的链接。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置错误出现时的重定向页面 +err := cli.SetErrorPage(testDomain, []api.ErrorPage{ + { + Code: 510, + RedirectCode: 301, + Url: "/customer_404.html", + }, + { + Code: 403, + // 这里没有设置RedirectCode,表示使用默认的302重定向 + Url: "/custom_403.html", + }, +}) +fmt.Printf("err:%+v\n", err) + +// 取消设置错误出现时的重定向页面 +err = cli.SetErrorPage(testDomain, []api.ErrorPage{}) +fmt.Printf("err:%+v\n", err) + +// 设置错误出现时的重定向页面 +err = cli.SetErrorPage(testDomain, []api.ErrorPage{}) +fmt.Printf("err:%+v\n", err) + +// 查询设置的错误重定向页面 +errorPages, err := cli.GetErrorPage(testDomain) +fmt.Printf("errorPages:%+v\n", errorPages) +``` + +`errorPages`是`[]api.ErrorPage`类型的对象,`api.ErrorPage`结构的详细说明如下: + +| 字段 | 类型 | 说明 | +| ------------ | ------ | ------------------------------------------------------------ | +| Code | int | 特定的状态码,要求必须为HTTP的标准错误码,且不能是408、444、499等客户端异常/提前断开这类特殊状态码。 | +| RedirectCode | int | 重定向状态码,当出现code错误码时,重定向的类型。支持301和302,默认302。 | +| Url | string | 重定向目标地址 ,当出现code错误码是,重定向到这个用户自定义的url,即301或302重定向中HTTP报文中的Location的值为了Url。 | + +### 设置/查询和其他域名共享缓存配置 SetCacheShared/GetCacheShared + +> 用户可以设置域名与另外一个域名共享缓存,提升命中率,前提是两个域名必须属于同一账户。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置test_go_sdk.baidu.com和www.baidu.com共享缓存 +err := cli.SetCacheShared(testDomain, &api.CacheShared{ + Enabled: true, + SharedWith: "www.baidu.com", +}) +fmt.Printf("err:%+v\n", err) + +// 取消test_go_sdk.baidu.com和任何域名共享缓存 +err := cli.SetCacheShared(testDomain, &api.CacheShared{ + Enabled: false, +}) +fmt.Printf("err:%+v\n", err) + +// 查询test_go_sdk.baidu.com的共享缓存配置 +cacheSharedConfig, err := cli.GetCacheShared(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("cacheSharedConfig:%+v\n", cacheSharedConfig) +``` + +### 设置/查询访问Referer控制 SetRefererACL/GetRefererACL + +> 设置Referer的访问控制规则,当通过浏览器或者其他形式跳转到资源是,浏览器通常会在请求头中加入Referer信息。CDN系统提供对Referer进行过滤,可以设置Referer黑名单或者白名单。当Referer出现在黑名单中的请求到达时响应403,当Referer没有出现在白名单中的请求到达时响应403。黑名单和白名单设置只能选其一,要么设置黑名单要么设置白名单。当设置了白名单并且过滤规则为空时,白名单不生效。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" +isAllowEmpty := true + +// 设置白名单ACL +err := cli.SetRefererACL(testDomain, nil, []string{ + "a.bbbbbb.c", + "*.baidu.com.*", +}, isAllowEmpty) +fmt.Printf("err:%+v\n", err) + +// 设置白名单为空,白名单规则不生效 +err = cli.SetRefererACL(testDomain, nil, []string{}, isAllowEmpty) +fmt.Printf("err:%+v\n", err) + +// 设置黑名单ACL +err = cli.SetRefererACL(testDomain, []string{ + "a.b.c", + "*.xxxxx.com.*", +}, nil, isAllowEmpty) +fmt.Printf("err:%+v\n", err) + +// 查询referer ACL设置 +refererACL, err := cli.GetRefererACL(testDomain) +fmt.Printf("refererACL:%+v\n", refererACL) +fmt.Printf("err:%+v\n", err) +``` + +`isAllowEmpty`表示是否允许空Referer访问,true表示允许空Referer访问,即如果Referer为空,那么不管是设置了黑名单还是白名单都不会生效,大多数情况下这个值都设置为**true**;false表示不允许空Referer访问,当设置为false时,如果访问的HTTP报文中不存在Referer那么CDN系统将返回403。`refererACL`是`api.RefererACL`类型的对象,他的详细说明如下: + +| 字段 | 类型 | 说明 | +| ---------- | -------- | ------------------------------------------------------------ | +| BlackList | []string | 可选项,表示referer黑名单列表,支持使用通配符*,不需要加protocol,如设置某个黑名单域名,设置为"www.xxx.com"形式即可,而不是"http://www.xxx.com"。* | +| WhiteList | []string | *可选项,list类型,表示referer白名单列表,支持通配符*,同样不需要加protocol。 | +| AllowEmpty | bool | 必选项,bool类型,表示是否允许空referer访问,为true即允许空referer访问。 | + +### 设置/查询访问IP控制 SetIpACL/GetIpACL + +> CDN获取客户端IP,同配置中的IP黑/白名单进行匹配,对匹配上的客户端请求进行拒绝/放过。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置IP白名单 +err := cli.SetIpACL(testDomain, []string{ + "1.1.1.1", + "2.2.2.2", +}, nil) +fmt.Printf("err:%+v\n", err) + +// 设置IP黑名单,CIDR格式的IP +err = cli.SetIpACL(testDomain, nil, []string{ + "1.2.3.4/24", +}) +fmt.Printf("err:%+v\n", err) + +// 查询IP黑白设置 +ipACL, err := cli.GetIpACL(testDomain) +fmt.Printf("ipACL:%+v\n", ipACL) +fmt.Printf("err:%+v\n", err) +``` + +`ipACL`是`api.IpACL`类型对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| --------- | -------- | ------------------------------------------------------------ | +| BlackList | []string | IP黑名单列表,当设置黑名单生效时,当客户端的IP属于BlackList,CDN系统返回403。BlackList不可与WhiteList同时设置。 | +| WhiteList | []string | IP白名单列表,当设置白名单生效时,当WhiteList为空时,没有白名单效果。当WhiteList非空时,只有客户端的IP属于WhiteList才允许访问。同样不可与BlackList同时设置。 | + +### 设置/查询访问UA控制 SetUaACL/GetUaACL + +> CDN获取HTTP请求头中的User-Agent,同配置中的黑/白名单进行匹配,对匹配上的请求进行拒绝/放过。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置UA白名单 +err = cli.SetUaACL(testDomain, nil, []string{ + "curl/7.73.0", +}) +fmt.Printf("err:%+v\n", err) + +// 设置UA黑名单 +err := cli.SetUaACL(testDomain, []string{ + "Test-Bad-UA", +}, nil) +fmt.Printf("err:%+v\n", err) + +// 查询UA黑白设置 +uaACL, err := cli.GetUaACL(testDomain) +fmt.Printf("uaACL:%+v\n", uaACL) +fmt.Printf("err:%+v\n", err) +``` + +`ipACL`是`api.IpACL`类型对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| --------- | -------- | ------------------------------------------------------------ | +| BlackList | []string | IP黑名单列表,当设置黑名单生效时,当客户端的IP属于BlackList,CDN系统返回403。BlackList不可与WhiteList同时设置。 | +| WhiteList | []string | IP白名单列表,当设置白名单生效时,当WhiteList为空时,没有白名单效果。当WhiteList非空时,只有客户端的IP属于WhiteList才允许访问。同样不可与BlackList同时设置。 | + +### 设置访问鉴权 SetDomainRequestAuth + +> 高级鉴权也是为了防止客户源站内容被盗用,比Referer黑白名单和IP黑白名单更加安全。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" +err := cli.SetDomainRequestAuth(testDomain, &api.RequestAuth{ + Type: "c", + Key1: "secretekey1", + Key2: "secretekey2", + Timeout: 300, + WhiteList: []string{ + "/crossdomain.xml", + }, + SignArg: "sign", + TimeArg: "t", +}) + +fmt.Printf("err:%+v\n", err) +``` + +示例代码设置一个C类鉴权方式,对应的字段在[高级鉴权](https://cloud.baidu.com/doc/CDN/s/ujwvyeo0t)。有非常消息的说明。 + +### 设置域名限速 SetLimitRate (废弃,请使用SetTrafficLimit) + +> 限定此域名下向客户端传输的每份请求的最大响应速率。该速率是针对单个请求的,多请求自动翻倍。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置单请求限速1024Bytes/s +err := cli.SetLimitRate(testDomain, 1024) +fmt.Printf("err:%+v\n", err) + +// 不做任何限速 +err = cli.SetLimitRate(testDomain, 0) +fmt.Printf("err:%+v\n", err) +``` + +### 设置单连接限速 SetTrafficLimit/GetTrafficLimit + +```go +cli := client.GetDefaultClient() +// 开启单连接限速,开启时间为北京时间上午10~12点之间,单链接限速值为1000KB左右。 +trafficLimit := &api.TrafficLimit{ + Enable: true, + LimitRate: 1000, + LimitStartHour: 10, + LimitEndHour: 12, + TrafficLimitUnit: "k", + } +// 设置单连接限速 +err := cli.SetTrafficLimit(testDomain, trafficLimit) + +// 查询单连接限速配置 +trafficLimit, err := cli.GetTrafficLimit(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("trafficLimit:%+v\n", trafficLimit) +``` + +`trafficLimit`是`api.TrafficLimit`类型的对象,详细说明如下: + + +| 字段 | 类型 | 说明 | +| ------- | ---- | ------------------------------------------------------------ | +| Enabled | bool | true表示开启单链接限速,false表示关闭。当enable为false时,下面的配置均无效 | +| limitRate | int | 限速值,建议显示设置,否则效果未定义。单位为limitRateUnit设置的值,默认为Byte/s。 | +| limitStartHour | int | 限速开始时间,请输入0 - 24范围的数字,小于限速结束时间,默认值为0(可选) | +| limitEndHour | int | 限速结束时间,请输入0 - 24范围的数字,大于限速开始时间,默认值为24(可选) | +| limitRateAfter | int | 在发送了多少数据之后限速,单位Byte(可选) | +| trafficLimitArg | string | 限速参数名称,根据url中提取的arg进行限速(可选) | +| trafficLimitUnit | string | 限速参数单位,支持m、k、g,默认为Byte(可选) | + +### 设置/查询Cors跨域 SetCors/GetCors + +> 跨域访问是指发起请求的资源所在域不同于该请求所指向的资源所在域,出于安全考虑,浏览器会限制这种非同源的访问。开启此功能,用户可以自己进行清除缓存及跨域访问配置,当源站(BOS)对象更新后,CDN所有对应的缓存可进行同步自动更新。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置允许的跨域域名 +err := cli.SetCors(testDomain, true, []string{ + "http://www.baidu.com", + "http://*.bce.com", +}) +fmt.Printf("err:%+v\n", err) + +// 取消跨域设置 +err = cli.SetCors(testDomain, false, nil) +fmt.Printf("err:%+v\n", err) + +// 查询跨域设置 +cors, err := cli.GetCors(testDomain) +fmt.Printf("cors:%+v\n", cors) +fmt.Printf("err:%+v\n", err) +``` + +### 设置/查询IP访问限频 SetAccessLimit/GetAccessLimit + +> 限制IP单节点的每秒访问次数,针对所有的访问路径。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置单IP访问限频为200/s +err := cli.SetAccessLimit(testDomain, &api.AccessLimit{ + Enabled: true, + Limit: 200, +}) +fmt.Printf("err:%+v\n", err) + +// 取消IP访问限频 +err = cli.SetAccessLimit(testDomain, &api.AccessLimit{ + Enabled: false, + Limit: 0, +}) +fmt.Printf("err:%+v\n", err) + +// 查询IP访问限频设置 +accessLimit, err := cli.GetAccessLimit(testDomain) +fmt.Printf("accessLimit:%+v\n", accessLimit) +fmt.Printf("err:%+v\n", err) +``` + +`accessLimit`是`api.AccessLimit`类型的对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| ------- | ---- | ------------------------------------------------------------ | +| Enabled | bool | true表示开启IP单节点访问限频,false表示取消限频。这里要注意golang的bool对象的零值为false,设置Limit的值必须要设置Enabled为true。 | +| Limit | int | 1秒内单个IP节点请求次数上限,enabled为true时此项默认为1000,enabled为false此项无意义。 | + +### 设置/查询获取真实用户IP SetClientIp/GetClientIp + +> 用户在使用CDN加速的同时可获取访问源的真实IP地址或客户端IP地址.。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置Client IP,源站可以获取到访问源的客户端IP地址,携带True-Client-Ip +err := cli.SetClientIp(testDomain, &api.ClientIp{ + Enabled: true, + Name: "True-Client-IP", +}) +fmt.Printf("err:%+v\n", err) + +// 设置Real IP:源站可以获取到访问源的真实IP地址,携带X-Real-IP。 +err = cli.SetClientIp(testDomain, &api.ClientIp{ + Enabled: true, + Name: "X-Real-IP", +}) +fmt.Printf("err:%+v\n", err) + +// 关闭设置Client IP和Real IP +err = cli.SetClientIp(testDomain, &api.ClientIp{ + Enabled: false, +}) +fmt.Printf("err:%+v\n", err) + +// 查询关于客户端IP的设置 +clientIp, err := cli.GetClientIp(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("clientIp:%+v\n", clientIp) +``` + +`clientIp`是`api.ClientIp`类型的对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| ------- | ------ | ------------------------------------------------------------ | +| Enabled | bool | true表示开启,false表示关闭。 | +| Name | string | 只能设置为"True-Client-Ip"或"X-Real-IP"两种之一,默认为"True-Client-Ip",enabled为false时此项无意义。 | + +### 设置/查询回源重试条件 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置当回源遇到429、500、502或者503错误码时进行重试 +err := client.SetRetryOrigin(testDomain, &api.RetryOrigin{ + Codes: []int{429, 500, 502}, +}) +fmt.Printf("err:%+v\n", err) + +// 查询回源重试策略 +retryOrigin, err := client.GetRetryOrigin(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("retryOrigin:%+v\n", retryOrigin) +``` + + +### 更新加速域名回源地址 SetDomainOrigin + +> 加速域名的回源地址可以在创建域名的时候设置好,也可以在创建完成后进行更新。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +err := cli.SetDomainOrigin(testDomain, []api.OriginPeer{ + { + Peer: "1.1.1.1", + Host: "www.baidu.com", + Backup: true, + Follow302: true, + }, + { + Peer: "http://2.2.2.2", + Host: "www.baidu.com", + Backup: false, + Follow302: true, + }, +}, "www.baidu.com") +fmt.Printf("err:%+v\n", err) +``` + +`api.OriginPeer`类型的详细说明在**创建加速域名一节**已经有说明。 + +### 设置/查询回源协议 SetOriginProtocol/GetOriginProtocol + +> 设置回源协议指的是设置CDN侧接受请求miss的时候请求源站的协议,可以设置的回源协议有"http"、"https"或者"*","*"表示协议跟随回源(请求是HTTP/HTTPS协议那么请求源站也是HTTP/HTTPS协议)。默认是HTTP回源。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置回源协议为HTTP +err := cli.SetOriginProtocol(testDomain, "http") +fmt.Printf("err:%+v\n", err) + +// 设置回源协议为HTTPS(域名必须HTTPS,否则以下请求失败) +err = cli.SetOriginProtocol(testDomain, "https") +fmt.Printf("err:%+v\n", err) + +// 设置回源跟随协议 +err = cli.SetOriginProtocol(testDomain, "*") +fmt.Printf("err:%+v\n", err) + +// 查询回源协议 +originProtocol, err := cli.GetOriginProtocol(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("originProtocol:%s\n", originProtocol) +``` + +### 设置协议跟随回源 SetFollowProtocol(废弃,设置协议跟随请使用SetOriginProtocol) + +> 设置协议跟随回源,表示CDN节点回源协议与客户端访问协议保持一致。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置协议跟随回源 +err := cli.SetFollowProtocol(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 取消设置协议跟随回源 +err = cli.SetFollowProtocol(testDomain, false) +fmt.Printf("err:%+v\n", err) +``` + +### 设置/查询Range回源 SetRangeSwitch/GetRangeSwitch + +> 设置Range回源,有助于减少大文件分发时回源消耗并缩短响应时间。此功能需源站支持Range请求。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置range回源 +err := cli.SetRangeSwitch(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 取消设置range回源 +err = cli.SetRangeSwitch(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询range回源设置 +rangeSwitch, err := cli.GetRangeSwitch(testDomain) +fmt.Printf("rangeSwitch:%+v\n", rangeSwitch) +``` + +### 设置/查询移动访问控制 SetMobileAccess/GetMobileAccess + +> 开启移动访问控制,源站可有针对性地进行移动端/PC端的资源内容分发,暂不支持自定义进行移动端配置。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置移动访问 +err := cli.SetMobileAccess(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 取消设置移动访问 +err = cli.SetMobileAccess(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询移动访问设置 +mobileAccess, err := cli.GetMobileAccess(testDomain) +fmt.Printf("mobileAccess:%+v\n", mobileAccess) +fmt.Printf("err:%+v\n", err) +``` + +### 设置/查询HttpHeader SetHttpHeader/GetHttpHeader + +> CDN支持CDN节点到客户端的response(HTTP响应头)、CDN节点到源站的request(HTTP请求头)中的header信息修改。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置CDN系统工作时增删的HTTP请求头 +err := cli.SetHttpHeader(testDomain, []api.HttpHeader{ + { + Type: "origin", + Header: "x-auth-cn", + Value: "xxxxxxxxx", + Action: "remove", + }, + { + Type: "response", + Header: "content-type", + Value: "application/octet-stream", + Action: "add", + }, +}) +fmt.Printf("err:%+v\n", err) + +// 取消CDN系统工作时增删的HTTP请求头 +err = cli.SetHttpHeader(testDomain, []api.HttpHeader{}) +fmt.Printf("err:%+v\n", err) + +// 查询CDN系统工作时增删的HTTP请求头 +headers, err := cli.GetHttpHeader(testDomain) +fmt.Printf("headers:%+v\n", headers) +fmt.Printf("err:%+v\n", err) +``` + +`headers`是`api.HttpHeader`类型的对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| -------- | ------ | ------------------------------------------------------------ | +| Type | string | "origin"表示此header 回源生效,"response"表示给用户响应时生效。 | +| Header | string | header为http头字段,一般为HTTP的标准Header,也可以是用户自定义的;如x-bce-authoriztion。 | +| Value | string | 指定Header的值。 | +| Action | string | 表示是删除还是添加,可选remove/add,默认是add;目前console只支持add action; API做后端remove配置的兼容。 | +| Describe | string | 描述,可选,可以是中文,统一使用Unicode统码;长度不能超过100个字符。 | + +### 设置/查询SEO开关属性 SetDomainSeo/GetDomainSeo + +> SEO(Search Engine Optimization)优化是一种利用搜索引擎的规则提高网站在有关搜索引擎内的自然排名的方式。目前CDN系统支持两项优化配置:(1)搜索引擎开启自动回源;(2)数据与百度搜索链接。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置SEO优化 +err := cli.SetDomainSeo(testDomain, &api.SeoSwitch{ + DirectlyOrigin: "ON", + PushRecord: "OFF", +}) +fmt.Printf("err:%+v\n", err) + +// 查询SEO优化设置 +seoSwitch, err := cli.GetDomainSeo(testDomain) +fmt.Printf("seoSwitch:%+v\n", seoSwitch) +fmt.Printf("err:%+v\n", err) +``` + +`seoSwitch`是`api.SeoSwitch`类型的对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| -------------- | ------ | ------------------------------------- | +| DirectlyOrigin | string | ON表示设置直接回源,OFF则相反。 | +| PushRecord | string | ON表示给大搜推送访问记录,OFF则相反。 | + +### 设置/查询页面优化 SetFileTrim/GetFileTrim + +> 用户开启页面优化功能,将自动删除 html中的注释以及重复的空白符,这样可以有效地去除页面的冗余内容,减小文件体积,提高加速分发效率。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置页面优化 +err := cli.SetFileTrim(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 取消页面优化 +err = cli.SetFileTrim(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询页面优化设置 +fileTrim, err := cli.GetFileTrim(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("fileTrim:%+v\n", fileTrim) +``` + +### 设置/查询IPv6开关 SetIPv6/GetIPv6 + +> 开启后,IPv6的客户端请求将支持以IPv6协议访问CDN,CDN也将携带IPv6的客户端IP信息访问您的源站。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 开启IPv6 +err := cli.SetIPv6(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 关闭IPv6 +err = cli.SetIPv6(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询IPv6开关 +ipv6Switch, err := cli.GetIPv6(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("ipv6Switch:%+v\n", ipv6Switch) +``` + +### 设置/查询QUIC开关 SetQUIC/GetQUIC + +> Quick UDP Internet Connection(QUIC)协议是Google公司提出基于UDP的高效可靠的互联网传输层协议。 本接口用于查询特定域名的QUIC启用状态。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 开启QUIC +err := cli.SetQUIC(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 关闭QUIC +err = cli.SetQUIC(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询QUIC开关 +quicSwitch, err := cli.GetQUIC(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("quicSwitch:%+v\n", quicSwitch) +``` + +### 设置/查询离线模式 SetOfflineMode/GetOfflineMode + +> 离线模式指的是在资源过期回源的时候,如果源站异常,那么CDN会响应之前缓存的资源,响应客户端200,但是回源日志中还是显示5xx。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 开启离线模式 +err := cli.SetOfflineMode(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 关闭离线模式 +err = cli.SetOfflineMode(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询离线模式 +offlineMode, err := cli.GetOfflineMode(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("offlineMode:%+v\n", offlineMode) +``` + +### 设置/查询视屏拖拽 SetMediaDrag/GetMediaDrag + +> CDN支持flv与mp4视频类型的拖拽,开启拖拽可降低回源率,提升速度。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置视频拖拽设置 +err := cli.SetMediaDrag(testDomain, &api.MediaDragConf{ + Mp4: &api.MediaCfg{ + DragMode: "second", + FileSuffix: []string{ + "mp4", + "m4a", + "m4z", + }, + StartArgName: "startIndex", + }, + Flv: &api.MediaCfg{ + DragMode: "byteAV", + FileSuffix: []string{}, + }, +}) +fmt.Printf("err:%+v\n", err) + +// 查询视频拖拽设置 +mediaDragConf, err := cli.GetMediaDrag(testDomain) +fmt.Printf("mediaDragConf:%+v\n", mediaDragConf) +fmt.Printf("err:%+v\n", err) +``` + +`mediaDragConf`是`api.MediaDragConf`类型的对象,定义如下: + +```go +type MediaDragConf struct { + Mp4 *MediaCfg + Flv *MediaCfg +} +``` + +可以设置Mp4或Flv类型视频流相关的拖拽,`MediaCfg`的详细说明如下: + +| 字段 | 类型 | 说明 | +| ------------ | -------- | ------------------------------------------------------------ | +| FileSuffix | []string | CDN系统支持MP4文件的伪流(pseudo-streaming)播放,通常这些文件拓展名为.mp4,.m4v,.m4a,因此这个fileSuffix值为文件拓展名集合,如: ["mp4", "m4v", "m4a"],type为mp4,fileSuffix默认值为["mp4"];type为flv,fileSuffix默认值为["flv"] | +| StartArgName | string | start参数名称,默认为“start”,您可以自定义参数名称,但是要求不能和`endArgName`相同 | +| EndArgName | string | end参数名称,默认为“end”,您可以自定义参数名称,但是要求不能和`startArgName`相同 | +| DragMode | string | mp4类型按秒进行拖拽,flv类型按字节进行拖拽。type为flv可选择的模式为“byteAV”或”byte”;type为mp4只能是"second"模式 | + +### 设置/查询页面压缩 SetContentEncoding/GetContentEncoding + +> 开启页面压缩功能后,您可以对大多数静态文件进行压缩,有效减少用户传输内容大小,加速分发效果。目前页面压缩支持Brotli压缩和Gzip压缩两种方式。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 设置页面压缩算法为gzip +err := cli.SetContentEncoding(testDomain, true, "gzip") +fmt.Printf("err:%+v\n", err) + +// 设置页面压缩算法为br +err = cli.SetContentEncoding(testDomain, true, "br") +fmt.Printf("err:%+v\n", err) + +// 关闭页面压缩 +err = cli.SetContentEncoding(testDomain, false, "br") +fmt.Printf("err:%+v\n", err) + +// 查询页面压缩算法,当关闭页面压缩时contentEncoding为空 +contentEncoding, err := cli.GetContentEncoding(testDomain) +fmt.Printf("contentEncoding:%+v\n", contentEncoding) +``` + +### 设置HTTPS加速 SetDomainHttps + +> 配置HTTPS的一个加速域名,必须要上传证书,了解证书详情请参考[证书管理](https://cloud.baidu.com/doc/Reference/s/8jwvz26si/)。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +err := cli.SetDomainHttps(testDomain, &api.HTTPSConfig{ + Enabled: false, + CertId: "ssl-xxxxxx", + Http2Enabled: true, + HttpRedirect: true, + HttpRedirectCode: 301, +}) +fmt.Printf("err:%+v\n", err) + +err = cli.SetDomainHttps(testDomain, &api.HTTPSConfig{ + Enabled: false, +}) +fmt.Printf("err:%+v\n", err) +``` + +`api.HTTPSConfig`的结构比较复杂,详细说明如下: + +| 字段 | 类型 | 说明 | +| ----------------- | ------ | ------------------------------------------------------------ | +| Enabled | bool | 开启HTTPS加速,默认为false,当enabled=false,以下几列字段设置无效。 | +| CertId | string | 当enabled=true时此项为必选,为SSL证书服务返回的证书ID,当enabled=False此项无效。 | +| HttpRedirect | bool | 为true时将HTTP请求重定向到HTTPS(重定向状态码为httpRedirectCode所配置),默认为false,当enabled=false此项无效,不可与httpsRedirect同时为true。 | +| HttpRedirectCode | int | 重定向状态码,可选值301/302,默认302,当enabled=false此项无效,httpRedirect=false此项无效。 | +| HttpsRedirect | bool | 为true时将HTTPS请求重定向到HTTP重定向状态码为httpsRedirectCode所配置),默认为false,当enabled=false此项无效,不可与httpRedirect同时为true。 | +| HttpsRedirectCode | int | 重定向状态码,可选值301/302,默认302,当enabled=false此项无效,httpsRedirect=false此项无效。 | +| Http2Enabled | bool | 开启HTTP2特性,当enabled=false此项无效。必须要注意go的bool对象零值为false。 | +| ~~HttpOrigin~~ | bool | **已弃用**,设置回源协议请参考**SetOriginProtocol**。 | +| SslVersion | string | 设置TLS版本,默认为支持从TLSv1.0到TLSv1.3的版本,也可以设置为以下四个之一,SSLV3,TLSV1,TLSV11,TLSV12,当enabled=false时此项无效,此项一般取默认值,无需设置。 | + +### 设置/查询OCSP SetOCSP/GetOCSP + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 开启OCSP +err := cli.SetOCSP(testDomain, true) +fmt.Printf("err:%+v\n", err) + +// 关闭OCSP +err = cli.SetOCSP(testDomain, false) +fmt.Printf("err:%+v\n", err) + +// 查询OCSP +ocspSwitch, err := cli.GetOCSP(testDomain) +fmt.Printf("err:%+v\n", err) +fmt.Printf("ocspSwitch:%+v\n", ocspSwitch) +``` + +## 证书管理接口 + +### 添加/修改域名证书 PutCert + +> 给某个域名添加或修改证书,如果该域名已经绑定了一个证书,则该方法为修改(将用户新上传的证书替换掉证书库中的老证书,且给域名绑定新证书)。 如果域名之前没有绑定证书,则该方法为上传新证书。可自定义是否开启HTTPS。 + +```go +cli := client.GetDefaultClient() +// certData要带有证书链信息 +certData := "-----BEGIN CERTIFICATE-----\nMIIFPTCCBCWgAwIBAgISBGRxBpT9H0OPrHDku006DU9SMA0GCSqGSIb3DQEBCwUA\nMDIxCzAJBgNVBAYTAlVTMRYwFAYDVQQKEw1MZXQncyBFbmNyeXB0MQswCQYDVQQD\nEwJSMzAeFw0yMTAzMTgwNzE0MzNaFw0yMTA2MTYwNzE0MzNaMB0xGzAZBgNVBAMM\nEiouY29kaW5nMzY1eDI0LmNvbTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoC\nggEBALM1g+BnRWl26auFUgAEU6L/2OWixH6K1BOp7JtlHW1RYM1I72pohuXyu0Hc\n20vOYpIQHpN1UY1e7bTKHsWiE/qUO/MeORbuslkYLBi3rZDE6i3aiYIFmaxjeYL9\nVQEJFrJI8X1AiIoP3MyiA4QsPotBH++3FyBb6sl5HtgqmCqItbsh6NV2FDN9+bm0\nz4hGSlJ1Wg9N03pXTaE8FT4AsCJzd/m+z+5u02aO5tEHWHiwrL4Yj/Y5H39x8/Ax\nHyaUjK62bgFySYH/XpU89dAKKo+uwOx5iBLXR8ni7yUj3y5NJ5A+AZUa61WbNNh0\n3jmgXff+s1zSwSiK+GP8q+Fz9+sCAwEAAaOCAmAwggJcMA4GA1UdDwEB/wQEAwIF\noDAdBgNVHSUEFjAUwYBBQUHAwIwDAYDVR0TAQH/BAIwADAd\nBgNVHQ4EFgQUArIIp83mJ+O7zRPwVr5ehX6JVJ4wHwYDVR0jBBgwFoAUFC6zF7dY\nVsuuUAlA5h+vnYsUwsYwVQYIKwYBBQUHAQEESTBHMCEGCCsGAQUFBzABhhVodHRw\nOi8vcjMuby5sZW5jci5vcmcwIgYIKwYBBQUHMAKGFmh0dHA6Ly9yMy5pLmxlbmNy\nLm9yZy8wLwYDVR0RBCgwJoISKi5jb2RpbmczNjV4MjQuY29tghBjb2RpbmczNjV4\nMjQuY29tMEwGA1UdIARFMEMwCAYGZ4EMAQIBMDcGCysGAQQBgt8TAQEBMCgwJgYI\nKwYBBQUHAgEWGmh0dHA6Ly9jcHMubGV0c2VuY3J5cHQub3JnMIIBBQYKKwYBBAHW\neQIEAgSB9gSB8wDxAHcAXNxDkv7mq0VEsV6a1FbmEDf71fpH3KFzlLJe5vbHDsoA\nAAF4RGaGEA1Hh4zntDdVfmKVzQT5p/mQdczLsoQp2hmkHrKiTw\nl8cCIQDlceLBxn2RWzl+LD00gvTZDlqL/iWI/pAJ5qtTKzMH1QB2APZclC/RdzAi\nFFQYCDCUVo7jTRMZM7/fDC8gC8xO8WTjAAABeERmhrYAAAQDAEcwRQIhAKCycKu6\nNch4dkzO9gfQdjwhyCsaKi8nxNDgS199gp+eAiBkePK1AEwf+fvWGV+mXWDXcjjS\n6QCjL7w5lKi7CrVJLzANBgkqhkiG9w0BAQsFA0MKbiwTqtJdEb\nPaaATAtN/NXHoESO/KHFGjJT9ua1PByM0Qqn6mvonck+Tu9fWxM6ZOvXheEdcCbS\n5zLI4AJTdp5yySPRQe2v9UwVO6keDsk0Ux1JWFWgV7otwV5P22pDxaKOKqUQ11ZM\neu5Pk9dKFjlhT+oP88acHKVBJ0CJk/D72jWlDUhn4LwiEJ/+mfGW0oPu5ht+z0Zb\nQLMt7xTX6fATALSCELFPwVrBwleUpCYeafxAJC6XAMF1xeifFfZduORqPAUqyj7U\nYp6h3Wy+rJRKo0bN1roPxgu4aexXnOth6Qeyvi7zq7IO+jMY1/VaEBQJGS/hqity\nKQ==\n-----END CERTIFICATE-----\n-----BEGIN CERTIFICATE-----\nMIIEZTCCA02gAwIBAgIQQAF1BIMUpMghjISpDBbN3zANBgkqhkiG9w0BAQsFADA/\nMSQwIgYDVQQKExtEaWdpdGFsIFNpZ25hdHVyZSBUcnVzdCBDby4xFzAVBgNVBAMT\nDkRTVCBSb290IENBIFgzMB4XDTIwMTAwNzE5MjE0MFoXDTIxMDkyOTE5MjE0MFow\nMjELMAkGA1UEBhMCVVMxFjAUBgQxCzAJBgNVBAMT\nAlIzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAuwIVKMz2oJTTDxLs\njVWSw/iC8ZmmekKIp10mqrUrucVMsa+Oa/l1yKPXD0eUFFU1V4yeqKI5GfWCPEKp\nTm71O8Mu243AsFzzWTjn7c9p8FoLG77AlCQlh/o3cbMT5xys4Zvv2+Q7RVJFlqnB\nU840yFLuta7tj95gcOKlVKu2bQ6XpUA0ayvTvGbrZjR8+muLj1cpmfgwF126cm/7\ngcWt0oZYPRfH5wm78Sv3htzB2nFd1EbjzK0lwYi8YGd1ZrPxGPeiXOZT/zqItkel\n/xMY6pgJdz+dU/nPAeX1pnAXFK9jpP+Zs5Od3FOnBv5IhR2haa4ldbsTzFID9e1R\noYvbFQIDAQABo4IBaDCCAWQwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8E\nBAMCAYYwSwYIKwYBBQUHAQEEPzA9ModHRwOi8vYXBwcy5p\nZGVudHJ1c3QuY29tL3Jvb3RzL2RzdHJvb3RjYXgzLnA3YzAfBgNVHSMEGDAWgBTE\np7Gkeyxx+tvhS5B1/8QVYIWJEDBUBgNVHSAETTBLMAgGBmeBDAECATA/BgsrBgEE\nAYLfEwEBATAwMC4GCCsGAQUFBwIBFiJodHRwOi8vY3BzLnJvb3QteDEubGV0c2Vu\nY3J5cHQub3JnMDwGA1UdHwQ1MDMwMaAvoC2GK2h0dHA6Ly9jcmwuaWRlbnRydXN0\nLmNvbS9EU1RST09UQ0FYM0NSTC5jcmwwHQYDVR0OBBYEFBQusxe3WFbLrlAJQOYf\nr52LFMLGMB0GA1UdJQQWMBQGCCsGAQUFBwMBBggrBgEFBQcDAjANBgkqhkiG9w0B\nAQsFAAOCAQEA2UzgyfWEiDcx27sT4rP8i2tiEmxYt0l+PAK3qB8oYevO4C5z70kH\nejWEHx2taPDY/laBL21/WKZuNTYQHHPVvCadTQsvd8\nS8MXjohyc9z9/G2948kLjmE6Flh9dDYrVYA9x2O+hEPGOaEOa1eePynBgPayvUfL\nqjBstzLhWVQLGAkXXmNs+5ZnPBxzDJOLxhF2JIbeQAcH5H0tZrUlo5ZYyOqA7s9p\nO5b85o3AM/OJ+CktFBQtfvBhcJVd9wvlwPsk+uyOy2HI7mNxKKgsBTt375teA2Tw\nUdHkhVNcsAKX1H7GNNLOEADksd86wuoXvg==\n-----END CERTIFICATE-----" + +privateKey := "-----BEGIN RSA PRIVATE KEY-----\nMIIEowIBAAKCAQEAszWD4GdFaXbpq4VSAARTov/Y5aLEforUE6nsm2UdbVFgzUjv\namiG5fK7QdzbS85ikhAek3VRjV7ttMoexaIT+pQ78x45Fu6yWRgsGLetkMTqLdqJ\nggWZrGN5gv1VAQkWskjxfUCIig/czKIDhCw+i0Ef77cXIFvqyXke2CqYKoi1uyHo\n1XYUM335ubTPiEZKUnVaD03Te7P7m7TZo7m0QdYeLCsvhiP\n9jkff3Hz8DEfJpSMrrZuAXJJgf9elTz10Aoqj67A7HmIEtdHyeLvJSPfLk0nkD4B\nlRrrVZs02HTeOaBd9/6zXNLBKIr4Y/yr4XP36wIDAQABAoIBAHnKZcyNApxRJy7d\nFURTrG97RvGRM874FHckpVtaVaxkgNAiwCrlzL/bva1eJl8XbN/tOopmUb0tBYk3\nT8BqjP9f3Ho2UQAnymdISTenJLrdSHVPLuKBYdXJaNw/xJRGk/koH45K3EBP1XPw\nq0kZNIw4/zZPjNT+AstXmEGApnLPFIoiEuB8grbfqQfr\nvY5ywxkXZdKQzeUr2ZVEPBp27q6lT13L0VBCCtOxZNNXPca+Lv\nJKlfvXBckuoyqHaTythwnw1PFPjq+uVMWfaa6gttfGGr11NVPnucRHwCMWUO0Cba\nfPw5ShECgYEA6fmMLOK/xRvaax7Hkr/In7IXUwSR1yNYupSeo+OF7C/+lkvvdwJP\nj/An9So2wVWY+DK3gKB7GCrDjYHB7Lv0m0dw7b+vEXv39z86mwUZsD8rMHy+HuqH\nZ4NieBkARWDaP/iE3HbrsWUHog7YvOZLr529byTRRQZdga5R1Vmf5RkCgYEAxBQx\nTPD6PypvVpQ4fkg58EJsFKwkGYTgcfS9dfwsjWbOTNW5gM/hCKgI/LTjsU7a0YYH\nvEMCTim81kuUKZ9rYlfXqB1Xzk9k6mUFeoP4t5KCe79YFi1A\nBUxqHUArJiLyO1g8cZruKK37DQKpT0sYHw7AAaMCgYBuSNUc1yiDVTSn51M0xbdg\nJsa9t9qyaJPLJoB8SaN3h8vdth9CnlE4TH/ZHLPAf4NiAi3isEI1Svrv+WiaGKIc\nixkcx4xSlnd0EFakeUv5elz2NuY6lluKnDBO4aHyEcvt+UtOy7Me47ssVQkuSPMF\n7Tk8aUNG4NA0byFdiihHCQKBgQCBXOkh4CLaJb8LGgMjnbdMAiaYhPHUPExwIo4V\nF2i1acxV+PPIPl4zfdlgEF/gjSvk7E6SMIuG0haaM4bu5xTL7zSC38kcflkQI9Ja\nWy6WYJFh6kjsdfguDn+7bVfVGOqexv/j/wRLhBhzsrxvZOO\negbHjQKBgEe3ghxGKW8dl3+/PDZ3KF8YBb5xUxe9BO8ufM0Pe+tCn8iWrTeAHG16\ncl9JgGlN9eIgx9VOh7suKlb9SsZLbAN60IO9nIx23g2nLqH+HyEZmE6zK5onSxua\n9vgcKjhNmg5WLvmQwz0ECw050HtDpptawvfNPinUY1LsjvkWqwiX\n-----END RSA PRIVATE KEY-----" +certId, err := testCli.PutCert("my.domain.com", &api.UserCertificate{ + CertName: "test", + ServerData: certData, + PrivateData: privateKey, + }, "ON") +fmt.Printf("certId:%s\n", certId) +fmt.Printf("err:%+v\n", err) +``` + +### 查询域名证书 GetCert + +> 查询某个域名的证书信息,如果证书不存在此方法会返回404错误。 + +```go +cli := client.GetDefaultClient() +detail, err := testCli.GetCert("my.domain.com") +fmt.Printf("detail:%v\n", detail) +// {"certId":"cert-8j774s9y3ww2","certName":"test","status":"IN_USE","certCommonName":"*.domain.com","certDNSNames":"*.domain.com,domain.com","certStartTime":"2021-03-18T07:14:33Z","certStopTime":"2021-06-16T07:14:33Z","certCreateTime":"2021-04-25T06:50:55Z","certUpdateTime":"2021-04-25T14:50:54Z"} +fmt.Printf("err:%+v\n", err) +``` + +### 删除域名证书 DeleteCert + +> 删除某个域名的证书,且关闭HTTPS。如果该域名原来没有证书,那么什么都不会做。 + +```go +cli := client.GetDefaultClient() +err := testCli.DeleteCert("my.domain.com") +fmt.Printf("err:%+v\n", err) +``` + +## 缓存管理接口 + +### 刷新缓存/查询刷新状态 Purge/GetPurgedStatus + +> 缓存清除方式有URL刷新、目录刷新除。URL刷新除是以文件或一个资源为单位进行缓存刷新。目录刷新除是以目录为单位,将目录下的所有文件进行缓存清除。 + +```go +cli := client.GetDefaultClient() + +// 刷除 +purgedId, err := cli.Purge([]api.PurgeTask{ + { + Url: "http://my.domain.com/path/to/purge/2.data", + }, + { + Url: "http://my.domain.com/path/to/purege/html/", + Type: "directory", + }, +}) +fmt.Printf("purgedId:%+v\n", purgedId) +fmt.Printf("err:%+v\n", err) + +// 根据任务ID查询刷除状态 +purgedStatus, err := cli.GetPurgedStatus(&api.CStatusQueryData{ + Id: string(purgedId), +}) + +fmt.Printf("purgedStatus:%+v\n", purgedStatus) +fmt.Printf("err:%+v\n", err) +``` + +示例中刷除了两类资源,第一种是刷除一个文件,第二种是刷除某个目录的所有的文件。根据Purge返回的task id去查询任务进度。`api.CStatusQueryData`是一个相对较复杂的结构,可以根据不同的条件查询,具体可以查看定义。 + +### 预热资源/查询预热状态 Prefetch/GetPrefetchStatus + +> URL预热是以文件为单位进行资源预热。 + +```go +cli := client.GetDefaultClient() + +prefetchId, err := cli.Prefetch([]api.PrefetchTask{ + { + Url: "http://my.domain.com/path/to/purge/1.data", + }, +}) +fmt.Printf("prefetchId:%+v\n", prefetchId) +fmt.Printf("err:%+v\n", err) + + +prefetchStatus, err := cli.GetPrefetchStatus(&api.CStatusQueryData{ + Id: string(prefetchId), +}) +fmt.Printf("prefetchStatus:%+v\n", prefetchStatus) +fmt.Printf("err:%+v\n", err) +``` + +### 查询刷新/预热限额 GetQuota + +```go +cli := client.GetDefaultClient() +quotaDetail, err := cli.GetQuota() +fmt.Printf("quotaDetail:%+v\n", quotaDetail) +fmt.Printf("err:%+v\n", err) +``` + +`quotaDetail`是`api.QuotaDetail`类型的对象,详细说明如下: + +| 字段 | 类型 | 说明 | +| --------- | ---- | ------------------------------- | +| DirRemain | int | 当日刷新目录限额余量。 | +| UrlRemain | int | 当日刷新(含预热)URL限额余量。 | +| DirQuota | int | 刷新目录限额总量。 | +| UrlQuota | int | 刷新(含预热)URL限额总量。 | + +## 动态加速接口 + +### 配置动态加速服务 EnableDsa/DisableDsa + +> 开启/关闭DSA是针对用户级别的开启关闭。 + +```go +cli := client.GetDefaultClient() + +// 开启DSA服务 +err := cli.EnableDsa() +fmt.Printf("err:%+v\n", err) + +// 关闭DSA服务 +err = cli.DisableDsa() +fmt.Printf("err:%+v\n", err) +``` + +### 查询动态加速域名列表 ListDsaDomains + +> 查询某个用户配置了DSA加速规则的域名列表。 + +```go +cli := client.GetDefaultClient() +dsaDomains, err := cli.ListDsaDomains() +fmt.Printf("dsaDomains:%+v\n", dsaDomains) +fmt.Printf("err:%+v\n", err) +``` + +`dsaDomains`是string数组,代表配置了DSA加速规则的域名。 + +### 配置域名动态加速规则 SetDsaConfig + +> 配置某个域名的DSA加速规则。 + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" + +// 配置DSA规则 +err := cli.SetDsaConfig(testDomain, &api.DSAConfig{ + Enabled: true, + Rules: []api.DSARule{ + { + Type: "suffix", + Value: ".mp4;.jpg;.php", + }, + { + Type: "path", + Value: "/path", + }, + { + Type: "exactPath", + Value: "/path/to/file.mp4", + }, + }, + Comment: "test", +}) +fmt.Printf("err:%+v\n", err) + +// 取消DSA规则 +err = cli.SetDsaConfig(testDomain, &api.DSAConfig{ + Enabled: false, +}) +fmt.Printf("err:%+v\n", err) +``` + +`api.DSAConfig`的详细说明如下: + +| 字段 | 类型 | 说明 | +| ----- | ------ | ------------------------------------------------------------ | +| Type | string | "suffix"表示文件类型,"path"表示动态路径,“exactPath“表示动态URL。 | +| Value | string | Type所指定类型的配置规则,多条规则使用";"分割。 | + + +## 日志接口 + +### 获取单个域名日志 GetDomainLog + +```go +cli := client.GetDefaultClient() +testDomain := "test_go_sdk.baidu.com" +endTime := "2019-09-01T07:12:00Z" +startTime := "2019-09-09T07:18:00Z" +domainLogs, err := cli.GetDomainLog(testDomain, api.TimeInterval{ + StartTime: startTime, + EndTime: endTime, +}) + +fmt.Printf("domainLogs:%+v\n", domainLogs) +fmt.Printf("err:%+v\n", err) +``` + +示例查询了单个域名在2019-09-01T07:12:00Z~2019-09-09T07:18:00Z之间的日志,`domainLogs`是`api.LogEntry`数组类型,LogEntry包含日志名,所属域名,下载路径,起始时间等信息。 + +### 获取多个域名日志 GetMultiDomainLog + +```go +cli := client.GetDefaultClient() +endTime := "2019-09-01T07:12:00Z" +startTime := "2019-09-09T07:18:00Z" + +domainLogs, err := cli.GetMultiDomainLog(&api.LogQueryData{ + TimeInterval: api.TimeInterval{ + StartTime: startTime, + EndTime: endTime, + }, + Type: 1, + Domains: []string{"1.baidu.com", "2.baidu.com"}, +}) + +fmt.Printf("domainLogs:%+v\n", domainLogs) +fmt.Printf("err:%+v\n", err) +``` + +示例查询["1.baidu.com", "2.baidu.com"]这些域名的日志,`domainLogs`和上一节GetDomainLog返回格式一致。 + +## 工具接口 + +### IP检测 GetIpInfo + +> 验证指定的IP是否属于百度开放云CDN服务节点。 + +```go +cli := client.GetDefaultClient() +ipStr := "1.2.3.4" +ipInfo, err := cli.GetIpInfo(ipStr, "describeIp") + +fmt.Printf("ipInfo:%+v\n", ipInfo) +fmt.Printf("err:%+v\n", err) +``` + +其中GetIpInfo的第二个参数只能为**"describeIp"**,ipInfo包含IP的详细信息,包括区域和ISP,如果不属于百度开放云CDN的节点,区域和ISP都为空。 + +### 批量IP检测接口 GetIpListInfo + +> 验证多个IP是否属于百度开放云CDN服务节点。 + +```go +cli := client.GetDefaultClient() +ipStr := "1.2.3.4" +ipsInfo, err := cli.GetIpListInfo([]string{"116.114.98.35", "59.24.3.174"}, "describeIp") + +fmt.Printf("ipsInfo:%+v\n", ipInfo) +fmt.Printf("err:%+v\n", err) +``` + +第二个参数只能为**"describeIp"** + +### 获取百度云CDN的回源节点信息 GetBackOriginNodes + +```go +cli := client.GetDefaultClient() +backOriginNodes, err := testCli.GetBackOriginNodes() + +fmt.Printf("backOriginNodes:%+v\n", backOriginNodes) +fmt.Printf("err:%+v\n", err) +``` + +## 统计查询 + +### 通用统计接口 + +> 通用统计接口在文档[统计接口](https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn)中有详细说明。 + +`api.QueryCondition`结构包含了最基本的查询条件,如下: + +| **参数** | **类型** | **说明** | +| --------- | -------- | ------------------------------------------------------------ | +| StartTime | string | 查询的时间范围起始值,默认为endTime前推24小时。格式为UTC时间字符串,如:"2019-09-01T07:12:00Z"。 | +| EndTime | string | 查询的时间范围结束值,默认为当前时间。时间跨度最长90天,时间格式和StartTime一样。 | +| Period | int | 查询结果的粒度,单位秒,可选值为60,300,3600,86400;默认为300,uv 默认3600(选60s的时间粒度时建议StartTime和EndTime区间跨度建议选择0.5到1h,否则可能会因为数据量太大无法正常返回) | +| KeyType | int | 标识key的内容,0=>域名,1=>用户id,2=>tag,默认0。 | +| Key | []string | 域名、用户Id或Tag。 | +| GroupBy | string | 返回结果聚合粒度,key => 根据key聚合,最后的key是`total`, 空 => 返回整体结果,每个key的每个时间段都对应一组数据。 | + +`metric`表示查询的统计数据类型,如下,接口具体返回结果的格式在对应的函数中可以看到。 + +| metric | 函数 | 接口类型 | 额外参数 | +| ---------------- | ------------------- | ---------------------------------- | ------------------------------------------------------------ | +| avg_speed | GetAvgSpeed | 查询平均速率 | 无。 | +| avg_speed_region | GetAvgSpeedByRegion | 客户端访问分布查询平均速率 | prov和isp。prov是查询的省份全拼,默认为空,查询全国数据。isp是查询的运营商代码,默认为空,查询所有运营商数据。 | +| pv | GetPv | pv/qps查询 | level,查询边缘节点或者中心节点pv。可填写"all"或"edge"或者"internal",默认为“all”。 | +| pv_src | GetSrcPv | 回源pv/qps查询 | 无。 | +| pv_region | GetPvByRegion | 查询pv/qps(分客户端访问分布) | prov和isp。prov是查询的省份全拼,默认为空,查询全国数据。isp是查询的运营商代码,默认为空,查询所有运营商数据。 | +| uv | GetUv | uv查询 | 无。 | +| flow | GetFlow | 查询流量、带宽 | level,查询边缘节点或者中心节点带宽。可填写"all"或"edge"或"internal",默认为"all"。 | +| flow_protocol | GetFlowByProtocol | 查询流量、带宽(分协议) | protocol,查询http或https的流量、带宽, 取值"http", "https"或者 "all",默认"all"。 | +| flow_region | GetFlowByRegion | 查询流量、带宽(分客户端访问分布) | prov和isp。prov是查询的省份全拼,默认为空,查询全国数据。isp是查询的运营商代码,默认为空,查询所有运营商数据。 | +| src_flow | GetSrcFlow | 查询回源流量、回源带宽 | 无。 | +| real_hit | GetRealHit | 字节命中率查询 | 无。 | +| pv_hit | GetPvHit | 请求命中率查询 | 无。 | +| httpcode | GetHttpCode | 状态码统计查询 | 无。 | +| src_httpcode | GetSrcHttpCode | 回源状态码查询 | 无。 | +| httpcode_region | GetHttpCodeByRegion | 状态码统计查询(分客户端访问分布) | prov和isp。prov是查询的省份全拼,默认为空,查询全国数据。isp是查询的运营商代码,默认为空,查询所有运营商数据。 | +| top_urls | GetTopNUrls | TopN urls | extra,查询指定http状态码的记录,默认值: ""。 | +| top_referers | GetTopNReferers | TopN referers | extra,查询指定http状态码的记录,默认值: ""。 | +| top_domains | GetTopNDomains | TopN domains | extra,查询指定http状态码的记录,默认值: ""。 | +| error | GetError | cdn错误码分类统计查询 | 无。 | + +### 计费统计接口 + +#### 查询域名或者tag的95带宽 GetPeak95Bandwidth + +查询条件: +| **参数** | **类型** | **说明** | +| --------- | -------- | ------------------------------------------------------------ | +| StartTime | string | 查询的时间范围起始值,默认为endTime前推24小时。格式为UTC时间字符串,如:"2019-09-01T07:12:00Z"。 | +| EndTime | string | 查询的时间范围结束值,默认为当前时间。时间跨度最长90天,时间格式和StartTime一样。 | +| domains | []string | 域名集合,和tags互斥存在,设置了domains请设置tags为nil | +| tags | []string | tag集合,和domains互斥存在,设置了tags请设置domains为nil | + +请求示例: + +```go +cli := client.GetDefaultClient() +peak95Time, peak95Band, err := cli.GetPeak95Bandwidth( + "2020-05-01T00:00:00Z", "2020-05-10T00:00:00Z", nil, []string{"www.test.com"}) + +fmt.Printf("peak95Time:%s\n", peak95Time) +fmt.Printf("peak95Band:%d\n", peak95Band) +fmt.Printf("err:%+v\n", err) +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/CERT.md b/bce-sdk-go/doc/CERT.md new file mode 100644 index 0000000..31e965c --- /dev/null +++ b/bce-sdk-go/doc/CERT.md @@ -0,0 +1,496 @@ +# 证书管理服务 + +# 概述 + +本文档主要介绍CERT GO SDK的使用。在使用本文档前,您需要先了解CERT的一些基本知识。若您还不了解CERT,可以参考[证书管理](https://cloud.baidu.com/doc/Reference/s/8jwvz26si)。 + +# 初始化 + +## 确认Endpoint + +目前使用CERT服务时,Endpoint统一使用`certificate.baidubce.com`, 支持http和https两种协议。 + +## 获取密钥 + +要使用百度云CERT,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CERT做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CERT Client + +CERT Client是CERT服务的客户端,为开发者与CERT服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CERT Client + +通过AK/SK方式访问CERT,用户可以参考如下代码新建一个CERT Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/cert" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个CERTClient + certClient, err := cert.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + +### 使用STS创建CERT Client + +**申请STS token** + +CERT可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CERT,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建CERT Client** + +申请好STS后,可将STS Token配置到CERT Client中,从而实现通过STS Token创建CERT Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CERT Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/cert" //导入CERT服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CERT服务的Client对象,Endpoint使用默认值 + certClient, err := cert.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "certificate.baidubce.com") + if err != nil { + fmt.Println("create cert client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + certClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CERT Client时,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问CERT + +CERT支持HTTPS传输协议,您可以通过在创建CERT Client对象时指定的Endpoint中指明HTTPS的方式,在CERT GO SDK中使用HTTPS访问CERT服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +ENDPOINT := "https://certificate.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +certClient, _ := cert.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CERT Client + +如果用户需要配置CERT Client的一些细节的参数,可以在创建CERT Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CERT服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +//创建CERT Client对象 +AK, SK := , +ENDPOINT := "certificate.baidubce.com" +client, _ := cert.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +AK, SK := , +ENDPOINT := "certificate.baidubce.com" +client, _ := cert.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +AK, SK := , +ENDPOINT := "certificate.baidubce.com" +client, _ := cert.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CERT时,创建的CERT Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CERT Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# CERT管理 + +证书管理模块主要用于管理用户的SSL证书,方便用户录入以及查看SSL证书。 + +## 创建证书 + +使用以下代码可以创建证书。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +args := &cert.CreateCertArgs{ + // 指定证书名称, 必选 + CertName: "sdkcreateTest", + // 指定服务器证书的数据内容 (Base64编码), 必选 + CertServerData: testCertServerData, + // 指定证书的私钥数据内容 (Base64编码), 必选 + CertPrivateData: testCertPrivateData, + // 指定证书链数据内容 (Base64编码), 可选 + CertLinkData: certLinkData, +} +result, err := client.CreateCert(args) +if err != nil { + fmt.Printf("create cert error: %+v\n", err) + return +} + +fmt.Printf("create cert success: %+v\n", result) +``` + +> 注意: +> - 证书的名称: 长度限制为1-65个字符,以字母开头,只允许包含字母、数字、’-‘、’/’、’.’、’’,Java正则表达式` ^[a-zA-Z]a-zA-Z0-9\-/\.]{2,64}$` + +该请求可能存在的异常描述如下。 + +异常code | 说明 +--- | --- +CertExceedLimit (409) | 超过用户最大证书数 +UnmatchedPairParameterInvalidException (400) | 证书有效时间不包含当前时间 +PrivateKeyParameterInvalid (400) | 私钥解析异常 +CertificateParameterInvalid (400) | 证书解析异常 +CertChainParameterInvalid (400) | 证书链解析异常 +UnmatchedPairParameterInvalid (400) | 公钥私钥不匹配 + +## 修改证书名称 + +使用以下代码可以修改证书名称。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +args := &cert.UpdateCertNameArgs{ + CertName: "test-sdk-cert", +} +err = client.UpdateCertName(certId, args) +if err != nil { + fmt.Printf("update cert error: %+v\n", err) + return +} +fmt.Printf("update cert success\n") +``` + +该请求可能存在的异常描述如下。 + +异常code | 说明 +--- | --- +AccessDeniedException | 无权限访问 +ResourceNotFoundException | 证书不存在 + +## 查看证书列表 + +使用以下代码可以查看用户的证书列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +result, err := client.ListCerts() +if err != nil { + fmt.Printf("list certs error: %+v\n", err) + return +} + +// 查看证书列表的详细信息 +for _, c := range listResult.Certs { + fmt.Println("cert id: ", c.CertId) + fmt.Println("cert name: ", c.CertName) + fmt.Println("cert common name: ", c.CertCommonName) + fmt.Println("cert start time: ", c.CertStartTime) + fmt.Println("cert stop time: ", c.CertStopTime) + fmt.Println("cert create time: ", c.CertCreateTime) + fmt.Println("cert update time: ", c.CertUpdateTime) + fmt.Println("cert type: ", c.CertType) +} +``` + +## 获取证书信息(无证书公钥私钥) + +使用以下代码可以获取指定的证书信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +result, err := client.GetCertMeta(certId) +if err != nil { + fmt.Printf("get certs meta error: %+v\n", err) + return +} + +// 获取得到证书id +fmt.Println("cert id: ", result.CertId) +// 获取得到证书名称 +fmt.Println("cert name: ", result.CertName) +// 获取得到证书通用名称 +fmt.Println("cert common name: ", result.CertCommonName) +// 获取得到证书生效时间 +fmt.Println("cert start time: ", result.CertStartTime) +// 获取得到证书到期时间 +fmt.Println("cert stop time: ", result.CertStopTime) +// 获取得到证书创建时间 +fmt.Println("cert create time: ", result.CertCreateTime) +// 获取得到证书更新时间 +fmt.Println("cert update time: ", result.CertUpdateTime) +// 获取得到证书类型 +fmt.Println("cert type: ", result.CertType) +``` + +该请求可能存在的异常描述如下。 + +异常code | 说明 +--- | --- +AccessDeniedException | 无权限访问 +ResourceNotFoundException | 证书不存在 + +## 删除证书 + +使用以下代码可以删除指定的证书。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +if err := client.DeleteCert(certId); err != nil { + fmt.Printf("delete certs error: %+v\n", err) + return +} +fmt.Printf("delete certs success\n") +``` + +该请求可能存在的异常描述如下。 + +异常code | 说明 +--- | --- +OperationNotAllowedException | 证书使用中 +AccessDeniedException | 无权限访问 +ResourceNotFoundException | 证书不存在 + +## 替换证书 + +使用以下代码可以替换过期且不再使用中的证书。 +```go +// import "github.com/baidubce/bce-sdk-go/services/cert" + +args := &cert.UpdateCertDataArgs{ + // 指定要替换的证书名称 + CertName: "test-sdk-cert", + // 指定服务器证书的数据内容 (Base64编码) + CertServerData: testUpdateCertServerData, + // 指定证书的私钥数据内容 (Base64编码) + CertPrivateData: testUpdateCertPrivateData, + // 指定证书链数据内容 (Base64编码) + CertLinkData: certLinkData, +} +if err := client.UpdateCertData(createResult.CertId, args); err != nil { + fmt.Printf("update cert data error: %+v\n", err) + return +} +fmt.Printf("update cert data success\n") +``` + +> 注意: 使用该api替换证书后,证书的id保持不变。 + +该请求可能存在的异常描述如下。 + +异常code | 说明 +--- | --- +OperationNotAllowedException(409) | 证书使用中或者证书 +AccessDeniedException(403) | 证书非本用户或子用户无该证书运维权限 +ResourceNotFoundException(404)| 无证书 +CertExceedLimit (409) | 超过用户最大证书数 +UnmatchedPairParameterInvalidException (400) | 证书有效时间不包含当前时间 +PrivateKeyParameterInvalid (400) | 私钥解析异常 +CertificateParameterInvalid (400) | 证书解析异常 +CertChainParameterInvalid (400) | 证书链解析异常 +UnmatchedPairParameterInvalid (400) | 公钥私钥不匹配 + + +# 错误处理 + +GO语言以error类型标识错误,CERT支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | CERT服务返回的错误 + +用户使用SDK调用CERT相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// certClient 为已创建的CERT Client对象 +result, err := client.ListCerts() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CERT发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当CERT服务端出现异常时,CERT服务端会返回给用户相应的错误信息,以便定位问题。 + +## SDK日志 + +CERT GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +CERT GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the CERT go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the CERT go sdk") +``` + + +# 版本变更记录 + +## v0.9.5 [2019-09-24] + +首次发布: + + - 支持创建证书、修改证书名称、查看证书列表、获取证书信息(无证书公钥私钥)、删除证书、替换证书接口。 \ No newline at end of file diff --git a/bce-sdk-go/doc/CFC.md b/bce-sdk-go/doc/CFC.md new file mode 100644 index 0000000..231135f --- /dev/null +++ b/bce-sdk-go/doc/CFC.md @@ -0,0 +1,841 @@ +# CFC GO SDK文档 + +# 初始化 + +## 确认Endpoint + +目前支持“华北-北京”、“华南-广州” 两个区域。北京区域:`http://cfc.bj.baidubce.com`,广州区域:`http://cfc.gz.baidubce.com` 对应信息为: + +访问区域 | 对应Endpoint +---|--- +BJ | cfc.bj.baidubce.com +GZ | cfc.gz.baidubce.com + +## 获取密钥 + +要使用百度云BOS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问BOS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## CFC Client + +CFC Client是CFC服务的客户端,为开发者与CFC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CFC Client + +通过AK/SK方式访问CFC,用户可以参考如下代码新建一个CFC Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/cfc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个cfcClient + cfcClient, err := cfc.NewClient(AK, SK, ENDPOINT) +} +``` + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://cfc.bj.baidubce.com`。 + +### 使用STS创建CFC Client + +**申请STS token** + +CFC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CFC,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建CFC Client** + +申请好STS后,可将STS Token配置到CFC Client中,从而实现通过STS Token创建CFC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CFC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/cfc" //导入CFC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CFC服务的Client对象,Endpoint使用默认值 + cfcClient, err := cfc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create cfc client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + cfcClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CFC Client时,无论对应CFC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问CFC + +CFC支持HTTPS传输协议,您可以通过在创建CFC Client对象时指定的Endpoint中指明HTTPS的方式,在CFC GO SDK中使用HTTPS访问CFC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfc" + +ENDPOINT := "https://cfc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +cfcClient, _ := cfc.NewClient(AK, SK, ENDPOINT) +``` + +## 配置cfc Client + +如果用户需要配置CFC Client的一些细节的参数,可以在创建CFC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CFC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfc" + +//创建CFC Client对象 +AK, SK := , +ENDPOINT := "cfc.bj.baidubce.com" +client, _ := cfc.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfc" + +AK, SK := , +ENDPOINT := "cfc.bj.baidubce.com" +client, _ := cfc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfc" + +AK, SK := , +ENDPOINT := "cfc.bj.baidubce.com" +client, _ := cfc.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CFC时,创建的CFC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CFC Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +## 函数调用 + +使用以下代码可以调用执行一个指定的CFC函数 +```go +args := &api.InvocationsArgs{ + FunctionName: "sdk-create", + InvocationType: api.InvocationTypeRequestResponse, + Payload: nil, +} + +// 若想执行特定版本的函数,可以设置 +args.Qualifier = "1" + +result, err := client.Invocations(args) +if err != nil { + fmt.Println("invocation function failed:", err) +} else { + fmt.Println("invocation function success: ", result) +} +``` + +## 函数操作 + +### 创建函数 + +使用以下代码可以创建一个CFC函数 +```go +arge := &api.CreateFunctionArgs{ + // 配置函数的代码,需要上传代码的zip压缩包 + Code: &api.CodeFile{ZipFile: zipFile}, + // 函数名称,每个用户的函数名称不可重复,不可修改 + FunctionName: "sdk-create", + // 函数调用的入口函数 + Handler: "index.handler", + // 函数的runtime + Runtime: "nodejs8.5", + // 函数运行的内存大小,单位mb,必须是128的整数倍,最大可选1024 + MemorySize: 256, + // 函数执行超时时间,可选1-300s + Timeout: 3, + // 函数描述信息 + Description: "sdk create", + // 函数日志存放方式,可选bos,表示函数执行日志存放在bos中 + LogType: "bos", + // 若LogType配置为bos,此参数设置函数执行日志在bos中的存储地址 + LogBosDir: "bos://ashjfdklsfhlk/", +}) + +// 若要配置从bos bucket中上传函数代码,可以如下设置 +// 这两个参数不能和args.Code.ZipFile同时设置 +args.Code.BosBucket = "bucketName" +args.Code.BosObject = "objectKey" + +// 若要直接发布函数,可以设置 +args.Code.Publish = true + +// 若要配置函数访问VPC网络,可以如下设置 +args.VpcConfig = &api.VpcConfig{ + SubnetIds: []string{"subnet_id1"}, + SecurityGroupIds: []string{"security_group_id1"}, +} + +// 若要配置环境变量,可以如下设置 +args.Environment = &api.Environment{ + Variables: map[string]string{ + "key": "value", + }, +}, + +result, err := client.CreateFunction(args) +if err != nil { + fmt.Println("create function failed:", err) +} else { + fmt.Println("create function success: ", result) +} +``` + +### 函数列表 + +使用以下代码可以获取CFC函数的列表 +```go +args := &api.ListFunctionArgs{} + +// 若想查询指定版本1的函数,可以如下设置 +args.FunctionVersion = "1" + +result, err := client.ListFunctions(args) +if err != nil { + fmt.Println("list function failed:", err) +} else { + fmt.Println("list function success: ", result) +} +``` + +### 函数信息 + +使用以下代码可以获取特定函数的信息 +```go +args := &api.GetFunctionArgs{ + FunctionName: "functionName" +} +result, err := client.GetFunction(args) +if err != nil { + fmt.Println("get function failed:", err) +} else { + fmt.Println("get function success: ", result) +} +``` + +### 删除函数 + +使用以下代码可以删除一个特定的CFC函数 +```go +args := &api.DeleteFunctionArgs{ + FunctionName: "sdk-create", +} + +// 若想删除函数的某个版本,可以设置 +args.Qualifier = "1" + +err := client.DeleteFunction(args) +if err != nil { + fmt.Println("delete function failed:", err) +} +``` + +### 更新函数代码 + +使用以下代码可以更新特定CFC函数的代码 +```go +args := &api.UpdateFunctionCodeArgs{ + FunctionName: "sdk-creat" + ZipFile: []byte(functionZipCode) +} + +// 若要配置从bos bucket中上传函数代码,可以如下设置 +// 这两个参数不能和args.ZipFile同时设置 +args.BosBucket = "bucketName" +args.BosObject = "objectKey" + +// 若要直接发布函数,可以设置 +args.Publish = true + +result, err := client.UpdateFunctionCode(args) +if err != nil { + fmt.Println("update function code failed:", err) +} else { + fmt.Println("update function code success: ", result) +} +``` + +### 获取函数配置 + +使用以下代码可以获取特定CFC函数的配置 +```go +args := &api.GetFunctionConfigurationArgs{ + FunctionName: "sdk-create", +} + +// 若想查询特定版本的函数的配置,可以设置 +args.Qualifier = functionBrn + +if err != nil { + fmt.Println("get function configure failed:", err) +} else { + fmt.Println("get function configure success: ", result) +} +``` + +### 更新函数配置 + +使用以下代码可以更新特定CFC函数的配置 +```go +args := &api.UpdateFunctionConfigurationArgs{ + FunctionName: "sdk-create", + Timeout: 20, + Description: "sdk update", + Runtime: "nodejs8.5", + MemorySize: &memorySize, + Environment: &api.Environment{ + Variables: map[string]string{ + "name": "Test", + }, + }, +}) + +result, err := client.UpdateFunctionConfiguration(args) +if err != nil { + fmt.Println("update function configure failed:", err) +} else { + fmt.Println("update function configure success: ", result) +} +``` + +### 设置函数预留并发度 + +使用以下代码可以设置和更新特定CFC函数的预留并发度 +```go +args := &api.ReservedConcurrentExecutionsArgs{ + FunctionName: "sdk-create", + // 预留并发度会由本函数的所有版本共享,最高能设置90 + ReservedConcurrentExecutions: 10, +}) + +err := client.SetReservedConcurrentExecutions(args) +if err != nil { + fmt.Println("set function reserved concurrent executions failed:", err) +} +``` + +### 删除函数预留并发度设置 + +使用以下代码可以删除特定CFC函数的预留并发度设置 +```go +args := &api.DeleteReservedConcurrentExecutionsArgs{ + FunctionName: "sdk-create", +}) + +err := client.DeleteReservedConcurrentExecutions(args) +if err != nil { + fmt.Println("delete function reserved concurrent executions failed:", err) +} +``` + +## 版本操作 + +### 获取函数版本列表 + +使用以下代码可以获取函数版本列表 +```go +args := &api.ListVersionsByFunctionArgs{ + FunctionName: "sdk-create", +} + +result, err := client.ListVersionsByFunction(args) +if err != nil { + fmt.Println("get function version failed:", err) +} else { + fmt.Println("get function version success: ", result) +} +``` + +### 发布版本 + +使用以下代码可以为函数发布一个版本 +```go +args := &api.PublishVersionArgs{ + FunctionName: "sdk-create", +} + +// 若想添加版本描述,可以设置 +args.Descirption = "publish description" + +// 若想对版本的部署包进行sha256验证,可以设置 +args.CodeSha256 = "codeSha256" + +result, err := client.PublishVersion(args) +if err != nil { + fmt.Println("publish function version failed:", err) +} else { + fmt.Println("publish function version success: ", result) +} +``` + +## 别名操作 + +### 获取别名列表 + +使用以下代码可以获取函数的别名列表 +```go +args := &api.ListAliasesArgs{ + FunctionName: "sdk-create", +} + +// 若想获取特定函数版本的别名,可以设置 +args.FunctionVersion = "1" + +result, err := client.ListAliases(args) +if err != nil { + fmt.Println("list function alias failed:", err) +} else { + fmt.Println("list function alias success: ", result) +} +``` + + +### 创建别名 + +使用以下代码可以为特定函数版本创建一个别名 +```go +args := &api.CreateAliasArgs{ + FunctionName: "sdk-create", + Name: "alias-create", +} + +// 若要将别名绑定到特定函数版本,可以设置 +args.FunctionVersion = "1" + +// 若要设置别名标书,可以设置 +args.Description = "alias description" + + +result, err := client.CreateAlias(args) +if err != nil { + fmt.Println("create function alias failed:", err) +} else { + fmt.Println("create function alias success: ", result) +} +``` + +### 获取别名信息 + +使用以下代码可以获取一个特定函数的别名的信息 +```go +args := &api.GetAliasArgs{ + FunctionName: "sdk-create", + AliasName: "alias-create", +} + +result, err := client.GetAlias(args) +if err != nil { + fmt.Println("get function alias failed:", err) +} else { + fmt.Println("get function alias success: ", result) +} +``` + +### 更新别名 + +使用以下代码可以更新一个函数的别名 +```go +args := &api.UpdateAliasArgs{ + FunctionName: "sdk-create", + AliasName: "alias-create", + Description: "test alias", +} + +// 若要修改别名绑定的函数版本,可以设置 +args.FunctionVersion = "$LATEST" + +result, err := client.UpdateAlias(args) +if err != nil { + fmt.Println("update function alias failed:", err) +} else { + fmt.Println("update function alias success: ", result) +} +``` + +### 删除别名 + +使用以下代码可以删除一个函数的别名 +```go +args := &api.DeleteAliasArgs{ + FunctionName: "sdk-create", + AliasName: "alias-create", +} + +err := client.DeleteAlias(args) +if err != nil { + fmt.Println("delete function alias failed:", err) +} +``` + +## 触发器操作 + +### 获取触发器列表 + +使用以下代码可以获取一个触发器的列表 +```go +args := &api.ListTriggersArgs{ + FunctionBrn: "functionBrn", +} + +// 默认不返回cfc-edge触发器,若想查询所有的触发器,可以设置 +args.ScopeType = "all" + +result, err := client.ListTriggers(args) +if err != nil { + fmt.Println("get function trigger failed:", err) +} else { + fmt.Println("get function trigger success: ", result) +} +``` + +### 创建触发器 + +使用以下代码可以创建一个特定的触发器并绑定 +```go +args := &api.CreateTriggerArgs{ + Target: "functionBrn", + Source: api.SourceTypeCrontab, + // 创建crontab触发器所需的数据 + Data: &api.CrontabTriggerData{ + Name: "sdkName", + Brn: "functionBrn", + ScheduleExpression: "cron(0 10 * * ?)", + Enabled: "Disabled", + }, +} + +result, err := client.CreateTrigger(args) +if err != nil { + fmt.Println("create function trigger failed:", err) +} else { + fmt.Println("create function trigger success: ", result) +} +``` + +> **提示:** +> 1. 不同类型的触发器,其Data字段所需内容不同,具体可以参考文档[触发器配置](https://cloud.baidu.com/doc/CFC/s/Kjwvz47o9#relationconfiguration) + +### 更新触发器 + +使用以下代码可以更新一个函数的触发器 +```go +args := &api.UpdateTriggerArgs{ + RelationId: RelationId, + Target: functionBRN, + Source: api.SourceTypeHTTP, + Data: &api.HttpTriggerData{ + ResourcePath: fmt.Sprintf("tr99-%s", time.Now().Format("2006-01-02T150405")), + Method: "GET", + AuthType: "anonymous", + }, +} + +result, err := client.UpdateTrigger(args) +if err != nil { + fmt.Println("update function trigger failed:", err) +} else { + fmt.Println("update function trigger success: ", result) +} +``` + +### 删除触发器 + +使用以下代码可以删除一个触发器 +```go +args := &api.DeleteTriggerArgs{ + RelationId: RelationId, + Target: functionBRN, + Source: api.SourceTypeHTTP, +} + +err := client.DeleteTrigger(args) +if err != nil { + fmt.Println("delete function trigger failed:", err) +} +``` +## 消息触发器EventSourceMappings操作 + +### 获取消息触发器EventSourceMappings列表 + +使用以下代码可以获取某个函数的消息触发器EventSourceMappings的列表 +```go +args := &api.ListEventSourceArgs{ + FunctionName: "functionBrn", + Marker: 0, + MaxItems: 100, +} + +// 返回指定函数的消息触发器列表 +result, err := client.ListEventSource(args) +if err != nil { + fmt.Println("list function event source mappings failed:", err) +} else { + fmt.Println("list function event source mappings success: ", result) +} +``` +### 获取某个消息触发器EventSourceMappings配置信息 + +使用以下代码可以获取某个消息触发器EventSourceMapping配置信息 +```go +args := &api.GetEventSourceArgs{ + UUID: "uuid", +} + +// 返回指定函数的消息触发器列表 +result, err := client.GetEventSource(args) +if err != nil { + fmt.Println("get function event source mapping info failed:", err) +} else { + fmt.Println("get function event source mapping info success: ", result) +} +``` + +### 创建消息触发器EventSourceMapping + +使用以下代码可以创建一个特定的消息触发器Event Source Mapping并绑定函数 +```go +FunctionBRN = "" +enabled := true +args := &api.CreateEventSourceArgs{ + Enabled: &enabled, + BatchSize: 3, + Type: api.TypeEventSourceDatahubTopic, + FunctionName: FunctionBRN, + DatahubConfig: api.DatahubConfig{ + MetaHostEndpoint: "endpoint", + MetaHostPort: 2181, + ClusterName: "clusterName", + PipeName: "pipeName", + PipeletNum: 1, + StartPoint: -1, + AclName: "aclName", + AclPassword: "aclPaaaword", + }, + } + +result, err := client.CreateEventSource(args) +if err != nil { + fmt.Println("create function event source mapping failed:", err) +} else { + fmt.Println("create function event source mapping success: ", result) +} +``` + +> **提示:** +> 1. 不同类型的消息触发器,其Type字段不同,目前只支持api.TypeEventSourceBms和api.TypeEventSourceDatahubTopic +> 2. 不同类型的触发器,其Data字段所需内容不同,具体可以参考文档[触发器配置](https://cloud.baidu.com/doc/CFC/s/Kjwvz47o9#relationconfiguration) + +### 更新消息触发器EventSourceMapping + +使用以下代码可以更新一个函数的消息触发器EventSourceMapping配置 +```go +unEnabled := false +FunctionBRN = "" +args := &api.UpdateEventSourceArgs{ + UUID: "uuid", + FuncEventSource: api.FuncEventSource{ + Enabled: &unEnabled, + BatchSize: 3, + Type: api.TypeEventSourceDatahubTopic, + FunctionName: FunctionBRN, + DatahubConfig: api.DatahubConfig{ + MetaHostEndpoint:"endpoint", + MetaHostPort: 80, + ClusterName: "clusterName", + PipeName:"pipeName", + PipeletNum:1, + StartPoint:-1, + AclName: "aclName", + AclPassword: "aclPassword", + }, + }, +} + +result, err := client.UpdateEventSource(args) +if err != nil { + fmt.Println("update function event source failed:", err) +} else { + fmt.Println("update function event source success: ", result) +} +``` + +### 删除一个消息触发器 + +使用以下代码可以删除一个触发器 +```go +args := &api.DeleteEventSourceArgs{ + UUID: "uuid", +} + +err := client.DeleteEventSource(args) +if err != nil { + fmt.Println("delete function event source mapping failed:", err) +} +``` + +# 错误处理 + +GO语言以error类型标识错误,CFC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +CFCClientError | 用户操作产生的错误 +BceServiceError | CFC服务返回的错误 + +用户使用SDK调用CFC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// cfcClient 为已创建的CFC Client对象 +args := &api.GetFunctionArgs{ + FunctionName: "functionName" +} +result, err := cfcClient.GetFunction(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get function detail success: ", result) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CFC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当CFC服务端出现异常时,CFC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[CFC错误返回](https://cloud.baidu.com/doc/CFC/s/Djwvz4cwc) + +# 版本变更记录 + +## v0.9.1 [2019-09-26] +首次发布: + + - 执行函数 + - 创建、查看、列表、删除函数,更新函数代码,更新、获取函数配置 + - 设置、删除函数预留并发度 + - 列表、创建函数版本 + - 列表、创建、获取、更新、删除别名 + - 获取、创建、更新、删除触发器 +## v0.9.2 [2021-09-06] +- ## v0.9.2 [2021-09-06] +- 列表、获取、创建、更新、删除消息触发器,包括百度消息bms触发器及Datahub触发器 + diff --git a/bce-sdk-go/doc/CFS.md b/bce-sdk-go/doc/CFS.md new file mode 100644 index 0000000..587096c --- /dev/null +++ b/bce-sdk-go/doc/CFS.md @@ -0,0 +1,427 @@ +# CFS服务 + +# 概述 + +本文档主要介绍CFS GO SDK的使用。在使用本文档前,您需要先了解普通型CFS的一些基本知识。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[CFS访问域名](https://cloud.baidu.com/doc/CFS/s/pjwvy1siw)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云CFS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CFS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CFS Client + +CFS Client是CFS控制面服务的客户端,为开发者与CFS控制面服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CFS Client + +通过AK/SK方式访问CFS,用户可以参考如下代码新建一个CFS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/cfs" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个CFSClient + cfsClient, err := cfs.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/CFS/index.html)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为CFS的控制面服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`cfs.bj.baidubce.com`。 + +### 使用STS创建CFS Client + +**申请STS token** + +CFS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CFS,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建CFS Client** + +申请好STS后,可将STS Token配置到CFS Client中,从而实现通过STS Token创建CFS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CFS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/cfs" //导入CFS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CFS控制面服务的Client对象,Endpoint使用默认值 + cfsClient, err := cfs.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create cfs client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + cfsClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CFS Client时,无论对应CFS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问CFS + +CFS支持HTTPS传输协议,您可以通过在创建CFS Client对象时指定的Endpoint中指明HTTPS的方式,在CFS GO SDK中使用HTTPS访问CFS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfs" + +ENDPOINT := "https://cfs.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +cfsClient, _ := cfs.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CFS Client + +如果用户需要配置CFS Client的一些细节的参数,可以在创建CFS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CFS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfs" + +//创建CFS Client对象 +AK, SK := , +ENDPOINT := "cfs.bj.baidubce.com +client, _ := cfs.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfs" + +AK, SK := , +ENDPOINT := "cfs.bj.baidubce.com" +client, _ := cfs.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfs" + +AK, SK := , +ENDPOINT := "cfs.bj.baidubce.com" +client, _ := cfs.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CFS时,创建的CFS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CFS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +CFS通过对标准NFS协议的支持,兼容POSIX接口,为云上的虚机、容器资源提供了跨操作系统的文件存储及共享能力。同时,百度智能云CFS提供简单、易操作的对外接口,并支持按实际使用量计费(公测期间免费),免去部署、维护费用的同时,最大化提升您的业务效率 + +## 文件系统管理 + +### 创建文件系统实例 + +通过以下代码,可以创建一个CFS文件系统实例,返回对应的文件实例ID + +```go +args := &cfs.CreateFSArgs{ + ClientToken: "be31b98c-5e41-4838-9830-9be700de5a20", + // 设置实例名称 + Name: "sdkCFS", + // 设置实例所属vpc + VpcId: vpcId, + // 设置实例所属协议类型:1.nfs 2.smb + Protocol: protocol, + // 设置实例所属可用区 + Zone: zone, +} + + +result, err := client.CreateFS(args) +if err != nil { + fmt.Println("create cfs failed:", err) +} else { + fmt.Println("create cfs success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[CreateFileSystem创建文件系统](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#createfilesystem%E5%88%9B%E5%BB%BA%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F) + +### 更新实例 + +通过以下代码,可以更新一个CFS实例的配置信息,如实例名称 + +```go +args := &cfs.UpdateFSArgs{ + // 实例ID + FSID: "cfs-xxxxx" + Name: "testSdk", +} +err := client.UpdateFS(args) +if err != nil { + fmt.Println("update cfs failed:", err) +} else { + fmt.Println("update cfs success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[UpdateFileSystem更新文件系统](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#updatefilesystem%E6%9B%B4%E6%96%B0%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F) + +### 查询已有的实例 + +通过以下代码,可以查询用户账户下所有CFS的信息 + +```go +args := &cfs.DescribeFSArgs{} + +// 支持按fsId、userId,匹配规则支持部分包含(不支持正则) +args.FSID = cfsId +args.UserId = userId + + +result, err := client.DescribeFS(args) +if err != nil { + fmt.Println("list all cfs failed:", err) +} else { + fmt.Println("list all cfs success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[DescribeFileSystem查询文件系统](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#describefilesystem%E6%9F%A5%E8%AF%A2%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F) + + +### 释放实例 + +通过以下代码,可以释放指定CFS实例,被释放的CFS无法找回 + +```go +args := &cfs.DropFSArgs{} +args.FSID = cfsId + +err := client.DropFS(args) +if err != nil { + fmt.Println("delete cfs failed:", err) +} else { + fmt.Println("delete cfs success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[DropFileSystem释放文件系统实例](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#dropfilesystem%E9%87%8A%E6%94%BE%E6%96%87%E4%BB%B6%E7%B3%BB%E7%BB%9F%E5%AE%9E%E4%BE%8B) + + +## 挂载点管理 + +### 创建挂载点 + +通过以下代码,在指定CFS实例下,创建一个文件系统的挂载点,返回domain + +```go +args := &cfs.CreateMountTargetArgs{ + // 所属文件系统实例ID + FSID: cfsId, + // 所属子网ID + SubnetId: subnetId, + // 所属vpc短ID + VpcID: vpcId, +} +err := client.CreateMountTarget(args) +if err != nil { + fmt.Println("create Mount Target failed:", err) +} else { + fmt.Println("create Mount Target success") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[CreateMountTarget创建挂载点](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#createmounttarget%E5%88%9B%E5%BB%BA%E6%8C%82%E8%BD%BD%E7%82%B9) + + +### 查询挂载点 + +通过以下代码,查询指定CFS实例下下所有挂载点信息,支持按挂载点匹配查询,结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定 + +```go +args := &cfs.DescribeMountTargetArgs{ + // 要查询的文件系统实例id + FSID: cfsid, +} +result, err := client.DescribeMountTarget(args) +if err != nil { + fmt.Println("describe Mount Target failed:", err) +} else { + fmt.Println("describe Mount Target success: ", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[DescribeMountTarget描述挂载点](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#describemounttarget%E6%8F%8F%E8%BF%B0%E6%8C%82%E8%BD%BD%E7%82%B9) + + +### 删除挂载点 + +通过以下代码,释放指定CFS实例下的挂载点 + +```go +args := &cfs.DropMountTargetArgs{ + // 要删除的文件系统实例ID + FSID: cfsId, + MountId: mountId, +} +err := client.DropMountTarget(args) +if err != nil { + fmt.Println("delete Mount Target failed:", err) +} else { + fmt.Println("delete Mount Target success: ") +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考CFS API 文档[DeleteMountTarget删除挂载点](https://cloud.baidu.com/doc/CFS/s/mjwvy1reo#deletemounttarget%E5%88%A0%E9%99%A4%E6%8C%82%E8%BD%BD%E7%82%B9) + + +# 错误处理 + +GO语言以error类型标识错误,CFS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | CFS服务返回的错误 + +用户使用SDK调用CFS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// cfsClient 为已创建的CFS Client对象 +describeArgs := &DescribeFSArgs { + FSID: CFS_ID, +} +cfsDetail, err := cfsClient.DescribeFS(describeArgs) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get cfs detail success: ", cfsDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CFS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当CFS服务端出现异常时,CFS服务端会返回给用户相应的错误信息,以便定位问题 + +# 版本变更记录 + +## v0.9.107 [2022-02-28] + +首次发布: + + - 创建、查看、列表、更新、删除CFS实例 + - 创建、查看、列表、更新、删除挂载点 diff --git a/bce-sdk-go/doc/CFW.md b/bce-sdk-go/doc/CFW.md new file mode 100644 index 0000000..c7dcd37 --- /dev/null +++ b/bce-sdk-go/doc/CFW.md @@ -0,0 +1,492 @@ +# CFW服务 + +# 概述 + +本文档主要介绍CFW GO SDK的使用。在使用本文档前,您需要先了解CFW的一些基本知识,并已开通了CFW服务。若您还不了解CFW,可以参考[产品描述](https://cloud.baidu.com/doc/CFW/s/ql0lu2yzg )和[操作指南](https://cloud.baidu.com/doc/CFW/s/al0m5cuka) 。 + +# 初始化 + +## 确认Endpoint + +云防火墙 API 的服务域名为:cfw.baidubce.com + +API支持HTTP和HTTPS两种调用方式。为了提升数据的安全性,建议通过HTTPS调用。 + + +## 获取密钥 + +要使用百度云CFW,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CFW做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CFW Client + +CFW Client是CFW服务的客户端,为开发者与CFW服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CFW Client + +通过AK/SK方式访问CFW,用户可以参考如下代码新建一个CFW Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/cfw" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个CFWClient + cfwClient, err := cfw.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为CFW的服务地址。 + +### 使用STS创建CFW Client + +**申请STS token** + +CFW可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CFW,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建CFW Client** + +申请好STS后,可将STS Token配置到CFW Client中,从而实现通过STS Token创建CFW Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CFW Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/cfw" //导入CFW服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CFW服务的Client对象,Endpoint使用默认值 + cfwClient, err := cfw.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "cfw.baidubce.com") + if err != nil { + fmt.Println("create cfw client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + cfwClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CFW Client时,STS的Endpoint需配置为http://sts.bj.baidubce.com。 + +# 配置HTTPS协议访问CFW + +CFW支持HTTPS传输协议,您可以通过在创建CFW Client对象时指定的Endpoint中指明HTTPS的方式,在CFW GO SDK中使用HTTPS访问CFW服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfw" + +ENDPOINT := "https://cfw.baidubce.com " //指明使用HTTPS协议 +AK, SK := , +cfwClient, _ := cfw.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CFW Client + +如果用户需要配置CFW Client的一些细节的参数,可以在创建CFW Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CFW服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfw" + +//创建CFW Client对象 +AK, SK := , +ENDPOINT := "cfw.baidubce.com" +client, _ := cfw.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfw" + +AK, SK := , +ENDPOINT := "cfw.baidubce.com" +client, _ := cfw.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/cfw" + +AK, SK := , +ENDPOINT := "cfw.baidubce.com" +client, _ := cfw.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CFW时,创建的CFW Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CFW Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 创建CFW策略 + +```go +args := &CreateCfwRequest{ + Name: "hzb_1", + Description: "desc", + CfwRules: []CreateRule{ + { + IpVersion: 4, + Priority: 4, + Protocol: "TCP", + Direction: "in", + SourceAddress: "192.168.0.4", + DestAddress: "192.168.0.5", + SourcePort: "80", + DestPort: "88", + Action: "allow", + }, + }, + } +result, err := CfwClient.CreateCfw(args) +ExpectEqual(t.Errorf, nil, err) +CfwId := result.CfwId +log.Debug(CfwId) +``` + +## 查询CFW策略列表 + +```go +args := &ListCfwArgs{ + Marker: "cfw-ius2qz1btkvm", +} +result, err := CfwClient.ListCfw(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询指定CFW策略 + +```go +result, err := CfwClient.GetCfw("cfw-ius2qz1btkvm") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 修改指定CFW策略 + +```go +args := &UpdateCfwRequest{ + Name: "hzb_1_1", + Description: "test", +} +err := CfwClient.UpdateCfw("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 删除指定CFW策略 + +```go +err := CfwClient.DeleteCfw("cfw-g0hs3v1scskq") +ExpectEqual(t.Errorf, nil, err) +``` + +## 批量创建CFW规则 + +```go +args := &CreateCfwRuleRequest{ + CfwRules: []CreateRule{ + { + IpVersion: 4, + Priority: 5, + Protocol: "TCP", + Direction: "in", + SourceAddress: "192.168.0.3", + DestAddress: "192.168.0.4", + SourcePort: "80", + DestPort: "88", + Action: "allow", + }, + }, +} +err := CfwClient.CreateCfwRule("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 修改指定CFW规则 + +```go +args := &UpdateCfwRuleRequest{ + IpVersion: 4, + Priority: 2, + Protocol: "TCP", + Direction: "in", + SourceAddress: "192.168.0.1", + DestAddress: "192.168.0.2", + SourcePort: "80", + DestPort: "88", + Action: "allow", +} +err := CfwClient.UpdateCfwRule("cfw-ius2qz1btkvm", "cfwr-9rjvf28r48s3", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 批量删除CFW规则 + +```go +args := &DeleteCfwRuleRequest{ + CfwRuleIds: []string{ + "cfwr-9rjvf28r48s3", + }, +} +err := CfwClient.DeleteCfwRule("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 防护边界实例列表 + +```go +args := &ListInstanceRequest{ + InstanceType: "eip", + MaxKeys: 2, + Marker: "ip-46d82b8b", +} +result, err := CfwClient.ListInstance(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 批量实例绑定CFW + +```go +args := &BindCfwRequest{ + InstanceType: "eip", + Instances: []CfwBind{ + { + Region: "bj", + InstanceId: "ip-06583aaf", + }, + { + Region: "bj", + InstanceId: "ip-0ad38b01", + }, + }, +} +err := CfwClient.BindCfw("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 批量实例解绑CFW + +```go +args := &UnbindCfwRequest{ + InstanceType: "eip", + Instances: []CfwBind{ + { + Region: "bj", + InstanceId: "ip-06583aaf", + }, + { + Region: "bj", + InstanceId: "ip-0ad38b01", + }, + }, +} +err := CfwClient.UnbindCfw("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 实例开启CFW保护 + +```go +args := &EnableCfwRequest{ + InstanceId: "ip-0ad38b01", +} +err := CfwClient.EnableCfw("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 实例关闭CFW保护 + +```go +args := &DisableCfwRequest{ + InstanceId: "ip-0ad38b01", +} +err := CfwClient.DisableCfw("cfw-ius2qz1btkvm", args) +ExpectEqual(t.Errorf, nil, err) +``` + +# 错误处理 + +GO语言以error类型标识错误,CFW支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | CFW服务返回的错误 + +用户使用SDK调用CFW相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +args := &ListInstanceRequest{ + InstanceType: "eip", +} +result, err := CfwClient.ListInstance(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CFW发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当CFW服务端出现异常时,CFW服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[CFW错误码](https://cloud.baidu.com/doc/CFW/s/Cl13c6svf) + +## SDK日志 + +CFW GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +CFW GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the CFW go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the CFW go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/CSN.md b/bce-sdk-go/doc/CSN.md new file mode 100644 index 0000000..2281c86 --- /dev/null +++ b/bce-sdk-go/doc/CSN.md @@ -0,0 +1,667 @@ +# CSN服务 + +# 概述 + +本文档主要介绍CSN GO SDK的使用。在使用本文档前,您需要先了解CSN的一些基本知识,并已开通了CSN服务。若您还不了解CSN,可以参考[产品描述](https://cloud.baidu.com/doc/CSN/s/ukk7yyait )和[操作指南](https://cloud.baidu.com/doc/CSN/s/Uklrk4o7b) 。 + +# 初始化 + +## 确认Endpoint + +云智能网 API 的服务域名为:csn.baidubce.com + +API支持HTTP和HTTPS两种调用方式。为了提升数据的安全性,建议通过HTTPS调用。 + + +## 获取密钥 + +要使用百度云CSN,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CSN做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CSN Client + +CSN Client是CSN服务的客户端,为开发者与CSN服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CSN Client + +通过AK/SK方式访问CSN,用户可以参考如下代码新建一个CSN Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个CSNClient + csnClient, err := csn.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`取值`csn.baidubce.com`,如果设置为空字符串,会使用默认域名作为CSN的服务地址。 + +### 使用STS创建CSN Client + +**申请STS token** + +CSN可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CSN,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建CSN Client** + +申请好STS后,可将STS Token配置到CSN Client中,从而实现通过STS Token创建CSN Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CSN Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/csn" //导入CSN服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CSN服务的Client对象,Endpoint使用默认值 + csnClient, err := csn.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "csn.baidubce.com") + if err != nil { + fmt.Println("create csn client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + csnClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CSN Client时,STS的Endpoint需配置为http://sts.bj.baidubce.com。 + +# 配置HTTPS协议访问CSN + +CSN支持HTTPS传输协议,您可以通过在创建CSN Client对象时指定的Endpoint中指明HTTPS的方式,在CSN GO SDK中使用HTTPS访问CSN服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/csn" + +ENDPOINT := "https://csn.baidubce.com " //指明使用HTTPS协议 +AK, SK := , +csnClient, _ := csn.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CSN Client + +如果用户需要配置CSN Client的一些细节的参数,可以在创建CSN Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CSN服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/csn" + +//创建CSN Client对象 +AK, SK := , +ENDPOINT := "csn.baidubce.com" +client, _ := csn.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/csn" + +AK, SK := , +ENDPOINT := "csn.baidubce.com" +client, _ := csn.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/csn" + +AK, SK := , +ENDPOINT := "csn.baidubce.com" +client, _ := csn.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CSN时,创建的CSN Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CSN Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +# 主要接口 +## 创建云智能网 + +```go +desc := "desc" +args := &CreateCsnRequest{ + Name: "csn_api_1", + Description: &desc, +} + +result, err := CsnClient.CreateCsn(args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +CsnId := result.CsnId +log.Debug(CsnId) +``` + +## 更新云智能网 + +```go +name := "csn_api_2" +args := &UpdateCsnRequest{ + Name: &name, +} + +err := CsnClient.UpdateCsn("csn-jf1tqjuvndzganap", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 删除云智能网 + +```go +err := CsnClient.DeleteCsn("csn-jf1tqjuvndzganap", getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询云智能网列表 + +```go +args := &ListCsnArgs{ + MaxKeys : 1, + Marker: "csn-jf1tqjuvndzganap", +} +result, err := CsnClient.ListCsn(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询云智能网详情 + +```go +result, err := CsnClient.GetCsn("csn-3cq38gxc8irzuu0x") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询云智能网网络实例列表 + +```go +args := &ListInstanceArgs{ + MaxKeys: 1, + Marker: "tgwAttach-rvu8tkaubphb78eg", +} +result, err := CsnClient.ListInstance("csn-3cq38gxc8irzuu0x", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 云智能网加载网络实例 + +```go +args := &AttachInstanceRequest{ + InstanceId: "vpc-f7lkcxldfcwq", + InstanceType: "bec_vpc", + InstanceRegion: "cn-hangzhou-cm", +} +err := CsnClient.AttachInstance("csn-3cq38gxc8irzuu0x", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 云智能网卸载网络实例 + +```go +args := &DetachInstanceRequest{ + InstanceId: "vpc-05y94xgfpujx", + InstanceType: "vpc", + InstanceRegion: "bj", +} +err := CsnClient.DetachInstance("csn-3cq38gxc8irzuu0x", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + + +## 查询路由表列表 + +```go +args := &ListRouteTableArgs{} +result, err := CsnClient.ListRouteTable("csn-3cq38gxc8irzuu0x", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 添加路由条目 + +```go +args := &CreateRouteRuleRequest{ + AttachId: "tgwAttach-rvu8tkaubphb78eg", + DestAddress: "0.0.0.0/0", + RouteType: "custom", +} +err := CsnClient.CreateRouteRule("csnRt-qjv5vtzxf53qq3wr", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询路由条目 + +```go +args := &ListRouteRuleArgs{} +result, err := CsnClient.ListRouteRule("csnRt-qjv5vtzxf53qq3wr", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 删除路由条目 + +```go +err := CsnClient.DeleteRouteRule("csnRt-qjv5vtzxf53qq3wr", +"7bb14cb1-fb02-4ae3-97d6-4e295338936c", getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 创建学习关系 + +```go +desc := "desc" +args := &CreatePropagationRequest{ + AttachId: "tgwAttach-uff0gvjkis95f6xg", + Description: &desc, +} +err := CsnClient.CreatePropagation("csnRt-qjv5vtzxf53qq3wr", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询学习关系 + +```go +result, err := CsnClient.ListPropagation("csnRt-qjv5vtzxf53qq3wr") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 删除学习关系 + +```go +err := CsnClient.DeletePropagation("csnRt-qjv5vtzxf53qq3wr", +"tgwAttach-uff0gvjkis95f6xg", getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 创建关联关系 + +```go +desc := "desc" +args := &CreateAssociationRequest{ + AttachId: "tgwAttach-uff0gvjkis95f6xg", + Description: &desc, +} +err := CsnClient.CreateAssociation("csnRt-qjv5vtzxf53qq3wr", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询关联关系 + +```go +result, err := CsnClient.ListAssociation("csnRt-qjv5vtzxf53qq3wr") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 删除关联关系 + +```go +err := CsnClient.DeleteAssociation("csnRt-qjv5vtzxf53qq3wr", +"tgwAttach-uff0gvjkis95f6xg", getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 创建带宽包 + +```go +instanceType := "center-edge" +args := &CreateCsnBpRequest{ + Name: "csnBp_api_2", + Bandwidth: 100, + InterworkType: &instanceType, + GeographicA: "China", + GeographicB: "China", + Billing: Billing{ + PaymentTiming: "Postpaid", + }, +} +result, err := CsnClient.CreateCsnBp(args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 更新带宽包 + +```go +args := &UpdateCsnBpRequest{ + Name: "csnBp_api_2", +} +err := CsnClient.UpdateCsnBp("csnBp-nyfb3wn198y7", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 删除带宽包 + +```go +err := CsnClient.DeleteCsnBp("csnBp-d51bzt2ah6ka", getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询带宽包列表 + +```go +args := &ListCsnBpArgs{} +result, err := CsnClient.ListCsnBp(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询指定带宽包详情 + +```go +result, err := CsnClient.GetCsnBp("csnBp-nyfb3wn198y7") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 带宽包的带宽升降级 + +```go +args := &ResizeCsnBpRequest{ + Bandwidth: 200, +} +err := CsnClient.ResizeCsnBp("csnBp-nyfb3wn198y7", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 带宽包绑定云智能网 + +```go +args := &BindCsnBpRequest{ + CsnId: "csn-3cq38gxc8irzuu0x", +} +err := CsnClient.BindCsnBp("csnBp-sj44m8xnq1z9", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 带宽包解绑云智能网 + +```go +args := &UnbindCsnBpRequest{ + CsnId: "csn-3cq38gxc8irzuu0x", +} +err := CsnClient.UnbindCsnBp("csnBp-nyfb3wn198y7", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 创建地域带宽 + +```go +args := &CreateCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "cn-hangzhou-cm", + Bandwidth: 10, +} +err := CsnClient.CreateCsnBpLimit("csnBp-sj44m8xnq1z9", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 更新地域带宽 + +```go +args := &UpdateCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "cn-hangzhou-cm", + Bandwidth: 20, +} +err := CsnClient.UpdateCsnBpLimit("csnBp-sj44m8xnq1z9", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 删除地域带宽 + +```go +args := &DeleteCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "cn-hangzhou-cm", +} +err := CsnClient.DeleteCsnBpLimit("csnBp-sj44m8xnq1z9", args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询地域带宽 + +```go +result, err := CsnClient.ListCsnBpLimit("csnBp-sj44m8xnq1z9") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询指定云智能网的地域带宽 + +```go +result, err := CsnClient.ListCsnBpLimitByCsnId("csn-3cq38gxc8irzuu0x") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询TGW列表 + +```go +args := &ListTgwArgs{} +result, err := CsnClient.ListTgw("csn-3cq38gxc8irzuu0x", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 更新TGW信息 + +```go +name := "tgw_1" +desc := "desc" +args := &UpdateTgwRequest{ + Name: &name, + Description: &desc, +} +err := CsnClient.UpdateTgw("csn-3cq38gxc8irzuu0x", "tgw-kyn0dc0e1qrvvaz5", +args, getClientToken()) +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询TGW路由条目 + +```go +args := &ListTgwRuleArgs{} +result, err := CsnClient.ListTgwRule("csn-3cq38gxc8irzuu0x", "tgw-kyn0dc0e1qrvvaz5", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +# 错误处理 + +GO语言以error类型标识错误,CSN支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | CSN服务返回的错误 + +用户使用SDK调用CSN相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +args := &ListInstanceRequest{ + InstanceType: "eip", +} +result, err := CsnClient.ListInstance(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向CSN发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当CSN服务端出现异常时,CSN服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[CSN错误码](https://cloud.baidu.com/doc/CSN/s/Tl56j65ym) + +## SDK日志 + +CSN GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +CSN GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the CSN go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the CSN go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/DBSC.md b/bce-sdk-go/doc/DBSC.md new file mode 100644 index 0000000..aaac743 --- /dev/null +++ b/bce-sdk-go/doc/DBSC.md @@ -0,0 +1,173 @@ +# DBSC服务 + +# 概述 + +本文档主要介绍DBSC GO SDK的使用。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BCC访问域名](https://cloud.baidu.com/doc/BCC/s/0jwvyo603)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云DBSC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问DBSC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建DBSC Client + +DBSC Client是BCC服务的客户端,为开发者与DBSC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建DBSC Client + +通过AK/SK方式使用DBSC,用户可以参考如下代码新建一个dbsc Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/dbsc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + AK, SK := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个BCCClient + dbscClient, err := dbsc.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`AK`对应控制台中的“Access Key ID”,`SK`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BCC/s/ojwvynrqn)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为dbsc的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + + +# 主要接口 + + +### 创建磁盘专属集群 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &CreateVolumeClusterArgs{ + // 创建一个磁盘磁盘专属集群,若要同时创建多个,可以修改此参数 + PurchaseCount: 1, + // 集群大小,支持最小容量:85TB(87040GB),支持最大容量:1015TB(1039360GB),购买步长:10TB + ClusterSizeInGB: 97280, + // 集群名称 + ClusterName: "dbsc", + // 集群磁盘类型:通用型HDD,通用型SSD + StorageType: StorageTypeHdd, + Billing: &Billing{ + // 只支持预付费 + Reservation: &Reservation{ + // 购买时长 + ReservationLength: 6, + ReservationTimeUnit: "MONTH", + }, + }, + // 自动续费时长 + RenewTimeUnit: "MONTH", + RenewTime: 6, +} +result, err := DBSC_CLIENT.CreateVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +clusterId := result.ClusterIds[0] +fmt.Print(clusterId) +``` + +### 磁盘专属集群列表 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &ListVolumeClusterArgs{ +} +result, err := DBSC_CLIENT.ListVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +fmt.Println(result) +``` + +### 磁盘专属集群详情 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +result, err := DBSC_CLIENT.GetVolumeClusterDetail(clusterId) +if err != nil { + fmt.Println(err) +} +fmt.Println(result) +``` + +### 磁盘专属集群扩容 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +args := &ResizeVolumeClusterArgs{ + NewClusterSizeInGB int `json:"newClusterSizeInGB"` +} +err := DBSC_CLIENT.ResizeVolumeCluster(clusterId, args) +if err != nil { + fmt.Println(err) +} +``` + +### 磁盘专属集群续费 +以下代码可以根据实例ID批量查询实例列表 +```go +args := &PurchaseReservedVolumeClusterArgs{ + Billing: &Billing{ + Reservation: &Reservation{ + // 续费时长 + ReservationLength: 6, + ReservationTimeUnit: "MONTH", + }, + }, +} +clusterId := "clusterId" +err := DBSC_CLIENT.PurchaseReservedVolumeCluster(clusterId, args) +if err != nil { + fmt.Println(err) +} +``` + +### 磁盘专属集群自动续费 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +args := &AutoRenewVolumeClusterArgs{ + ClusterId: clusterId, + RenewTime: 6, + RenewTimeUnit: "month", +} +err := DBSC_CLIENT.AutoRenewVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +``` + +### 磁盘专属集群取消自动续费 +以下代码可以根据实例ID批量查询实例列表 +```go +clusterId := "clusterId" +args := &CancelAutoRenewVolumeClusterArgs{ + ClusterId: clusterId, +} +err := DBSC_CLIENT.CancelAutoRenewVolumeCluster(args) +if err != nil { + fmt.Println(err) +} +``` + +首次发布: + + - 创建磁盘专属集群、磁盘专属集群列表、磁盘专属集群详情、磁盘专属集群扩容、磁盘专属集群续费、磁盘专属集群自动续费、磁盘专属集群取消自动续费 diff --git a/bce-sdk-go/doc/DDC.md b/bce-sdk-go/doc/DDC.md new file mode 100644 index 0000000..15e757b --- /dev/null +++ b/bce-sdk-go/doc/DDC.md @@ -0,0 +1,1221 @@ +# DDC服务 + +# 概述 + +本文档主要介绍DDC GO SDK的使用。在使用本文档前,您需要先了解DDC的一些基本知识,并已开通了DDC服务。 + +# 初始化 + +## 确认Endpoint + + +目前支持“华东-苏州”区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +SU | ddc.su.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云DDC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问DDC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建DDC Client + +DDC Client是DDC服务的客户端,为开发者与DDC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建DDC Client + +通过AK/SK方式访问DDC,用户可以参考如下代码新建一个DDC Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/ddc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个DDCClient + ddcClient, err := ddc.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为DDC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为苏州,则为`ddc.su.baidubce.com`。 + +### 使用STS创建DDC Client + +**申请STS token** + +DDC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问DDC,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建DDC Client** + +申请好STS后,可将STS Token配置到DDC Client中,从而实现通过STS Token创建DDC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建DDC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/ddc" //导入DDC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建DDC服务的Client对象,Endpoint使用默认值 + ddcClient, err := ddc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "ddc.su.baidubce.com") + if err != nil { + fmt.Println("create ddc client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + ddcClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置DDC Client时,无论对应DDC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问DDC + +DDC支持HTTPS传输协议,您可以通过在创建DDC Client对象时指定的Endpoint中指明HTTPS的方式,在DDC GO SDK中使用HTTPS访问DDC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +ENDPOINT := "https://ddc.su.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +ddcClient, _ := ddc.NewClient(AK, SK, ENDPOINT) +``` + +## 配置DDC Client + +如果用户需要配置DDC Client的一些细节的参数,可以在创建DDC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问DDC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +//创建DDC Client对象 +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddc.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddc.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问DDC时,创建的DDC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建DDC Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# DDC管理 + +云数据库专属集群 DDC (Dedicated Database Cluster)是专业、高性能、高可靠的云数据库服务。云数据库 DDC 提供 Web 界面进行配置、操作数据库实例,还为您提供可靠的数据备份和恢复、完备的安全管理、完善的监控、轻松扩展等功能支持。相对于自建数据库,云数据库 DDC 具有更经济、更专业、更高效、更可靠、简单易用等特点,使您能更专注于核心业务。 + +# 部署集管理 + +## 创建部署集 +使用以下代码可以在指定资源池下创建一个新的部署集。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.CreateDeployRequest{ + // 幂等 Token + ClientToken: "xxxyyyzzz", + // 部署集名称 + DeployName: "api-from-go", + // 部署策略 支持集中部署(centralized)/完全打散(distributed) + Strategy: "distributed", +} +err = client.CreateDeploySet(poolId, args) +if err != nil { + fmt.Printf("create deploy set error: %+v\n", err) + return +} + +fmt.Println("create deploy set success.") +``` + +## 查询部署集列表 +使用以下代码可以查询指定资源池下的部署集列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.ListDeploySets(poolId, nil) +if err != nil { + fmt.Printf("list deploy set error: %+v\n", err) + return +} + +for i := range result.Result { + deploy := result.Result[i] + fmt.Println("ddc deploy id: ", deploy.DeployID) + fmt.Println("ddc deploy name: ", deploy.DeployName) + fmt.Println("ddc deploy strategy: ", deploy.Strategy) + fmt.Println("ddc deploy create time: ", deploy.CreateTime) + fmt.Println("ddc instance ids: ", deploy.Instances) +} +``` + +## 查询特定部署集信息 +使用以下代码可以查询特定部署集的详细信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +deploy, err := client.GetDeploySet(poolId, deployId) +if err != nil { + fmt.Printf("get deploy set error: %+v\n", err) + return +} + +// 获取部署集的详细信息 +fmt.Println("ddc deploy id: ", deploy.DeployID) +fmt.Println("ddc deploy name: ", deploy.DeployName) +fmt.Println("ddc deploy strategy: ", deploy.Strategy) +fmt.Println("ddc deploy create time: ", deploy.CreateTime) +fmt.Println("ddc instance ids: ", deploy.Instances) +``` + +## 删除部署集 +使用以下代码可以删除某个资源池下特定的部署集。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +err := DDC_CLIENT.DeleteDeploySet(poolId, deployId) +if err != nil { + fmt.Printf("delete deploy set error: %+v\n", err) + return +} +fmt.Printf("delete deploy set success\n") +``` + +# 账号管理 + +## 创建账号 + +使用以下代码可以在某个主实例下创建一个新的账号。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.CreateAccountArgs{ + // 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 + ClientToken: "xxxyyyzzz", + // 账号名称,由小写字母、数字、下划线组成、字母开头,字母或数字结尾,最长16个字符,不能为保留关键字,必选 + AccountName: "accountName", + // 账号的密码,由字母、数字和特殊字符(!@#%^_)中的至少两种组成,长度8-32位,必选 + Password: "password", + // 账号权限类型,Common:普通帐号,Super:super账号。可选,默认为 Common + AccountType: "Common", + // 权限设置,可选 + DatabasePrivileges: []ddc.DatabasePrivilege{ + { + // 数据库名称 + DbName: "user_photo_001", + // 授权类型。ReadOnly:只读,ReadWrite:读写 + AuthType: "ReadOnly", + }, + }, + // 帐号备注,最多256个字符(一个汉字等于三个字符),可选 + Desc: "账号user1", +} +err = client.CreateAccount(instanceId, args) +if err != nil { + fmt.Printf("create account error: %+v\n", err) + return +} + +fmt.Println("create account success.") +``` + +> 注意: +> - 实例状态为Available,实例必须是主实例。 +> - 没有超出实例最大账号数量。 + +## 更新账号密码 + +使用以下代码可以更新账号的密码。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.UpdateAccountPasswordArgs{ + // 密码,由字母、数字和特殊字符(!@#%^_)中的至少两种组成,长度8-32位,必选 + Password: "password", +} +err = client.UpdateAccountPassword(instanceId, accountName, args) +if err != nil { + fmt.Printf("update account password error: %+v\n", err) + return +} + +fmt.Println("update account password success.") +``` + +## 更新账号备注 + +使用以下代码可以更新账号的备注。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.UpdateAccountDescArgs{ + // 帐号备注,最多256个字符(一个汉字等于三个字符),可选 + Desc: "desc", +} +err = client.UpdateAccountDesc(instanceId, accountName, args) +if err != nil { + fmt.Printf("update account desc error: %+v\n", err) + return +} + +fmt.Println("update account desc success.") +``` + +## 更新账号权限 + +使用以下代码可以更新账号的权限。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +databasePrivileges := []ddc.DatabasePrivilege{ + { + DbName: "hello", + // 授权类型。ReadOnly:只读,ReadWrite:读写 + AuthType: "ReadOnly", + }, +} + +args := &ddc.UpdateAccountPrivilegesArgs{ + DatabasePrivileges: databasePrivileges, +} +err = client.UpdateAccountPrivileges(instanceId, accountName, args) +if err != nil { + fmt.Printf("update account privileges error: %+v\n", err) + return +} + +fmt.Println("update account privileges success.") +``` + +## 查询特定账号信息 + +使用以下代码可以查询特定账号信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.GetAccount(instanceId,accountName) +if err != nil { + fmt.Printf("get account error: %+v\n", err) + return +} + +// 获取account的信息 +fmt.Println("ddc accountName: ", result.AccountName) +fmt.Println("ddc desc: ", result.Desc) +// 账号状态(创建中:Creating;可用中:Available;更新中:Updating;删除中:Deleting;已删除:Deleted) +fmt.Println("ddc accountStatus: ", result.AccountStatus) +// 账号类型(super账号:Super;普通账号:Common) +fmt.Println("ddc accountType: ", result.AccountType) +fmt.Println("ddc databasePrivileges: ", result.DatabasePrivileges) +``` + +## 查询账号列表 + +使用以下代码可以查询指定实例的账号列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.ListAccount(instanceId) +if err != nil { + fmt.Printf("list account error: %+v\n", err) + return +} + +// 获取account的列表信息 +for _, account := range result.Accounts { + fmt.Println("ddc accountName: ", account.AccountName) + fmt.Println("ddc desc: ", account.Desc) + // 账号状态(创建中:Creating;可用中:Available;更新中:Updating;删除中:Deleting;已删除:Deleted) + fmt.Println("ddc accountStatus: ", account.AccountStatus) + // 账号类型(super账号:Super;普通账号:Common) + fmt.Println("ddc accountType: ", account.AccountType) + fmt.Println("ddc databasePrivileges: ", account.DatabasePrivileges) +} +``` + +## 删除特定账号信息 + +使用以下代码可以删除特定账号信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +err := client.DeleteAccount(instanceId,accountName) +if err != nil { + fmt.Printf("delete account error: %+v\n", err) + return +} +fmt.Printf("delete account success\n") +``` + +# 数据库管理 + +## 创建数据库 + +使用以下代码可以在某个主实例下创建一个新的数据库。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.CreateDatabaseArgs{ + // 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 + ClientToken: "xxxyyyzzz", + // 数据库名称(由大小写字母、数字、下划线组成、字母开头,字母或数字结尾,最长64个字符) + DbName: "dbName", + // 数据库字符集(取值范围:utf8、gbk、latin1、utf8mb4) + CharacterSetName: "utf8", + // 数据库备注,最多256个字符(一个汉字等于三个字符) + Remark: "remark", +} +err = client.CreateDatabase(instanceId, args) +if err != nil { + fmt.Printf("create database error: %+v\n", err) + return +} + +fmt.Println("create database success.") +``` + +> 注意: +> - 实例状态为available,实例必须是主实例。 + +## 更新数据库备注 + +使用以下代码可以更新数据库的备注。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.UpdateDatabaseRemarkArgs{ + // 数据库备注,最多256个字符(一个汉字等于三个字符) + Remark: "remark", +} +err = client.UpdateDatabaseRemark(instanceId, dbName, args) +if err != nil { + fmt.Printf("update database remark error: %+v\n", err) + return +} + +fmt.Println("update database remark success.") +``` + +## 查询特定数据库信息 + +使用以下代码可以查询特定数据库信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.GetDatabase(instanceId,dbName) +if err != nil { + fmt.Printf("get database error: %+v\n", err) + return +} + +// 获取account的列表信息 +fmt.Println("ddc dbName: ", result.DbName) +fmt.Println("ddc characterSetName: ", result.CharacterSetName) +// 数据库状态(创建中:Creating;可用中:Available;删除中:Deleting;已删除:Deleted) +fmt.Println("ddc dbStatus: ", result.DbStatus) +fmt.Println("ddc remark: ", result.Remark) +fmt.Println("ddc accountPrivileges: ", result.AccountPrivileges) +``` + +## 查询数据库列表 + +使用以下代码可以查询指定实例的账号列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.ListDatabase(instanceId) +if err != nil { + fmt.Printf("list database error: %+v\n", err) + return +} + +// 获取account的列表信息 +for _, database := range result.Databases { + fmt.Println("ddc dbName: ", database.DbName) + fmt.Println("ddc characterSetName: ", database.CharacterSetName) + // 数据库状态(创建中:Creating;可用中:Available;删除中:Deleting;已删除:Deleted) + fmt.Println("ddc dbStatus: ", database.DbStatus) + fmt.Println("ddc remark: ", database.Remark) + fmt.Println("ddc accountPrivileges: ", database.AccountPrivileges) +} +``` + +## 删除特定数据库信息 + +使用以下代码可以删除特定数据库信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +err := client.DeleteDatabase(instanceId,dbName) +if err != nil { + fmt.Printf("delete database error: %+v\n", err) + return +} +fmt.Printf("delete database success\n") +``` + +# 实例管理 + +## 创建实例 +使用以下代码可以创建主实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +args := &ddc.CreateRdsArgs{ + // 指定ddc的数据库引擎,取值mysql,必选 + Engine: "mysql", + // 指定ddc的数据库版本,必选 + EngineVersion: "5.6", + // 计费相关参数,PaymentTiming取值为 预付费:Prepaid,后付费:Postpaid;Reservation:支付方式为后支付时不需要设置,预支付时必须设置;必选 + Billing: ddc.Billing{ + PaymentTiming: "Postpaid", + //Reservation: ddc.Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + // 预付费时可指定自动续费参数 AutoRenewTime 和 AutoRenewTimeUnit + // 自动续费时长(续费单位为year 不大于3,续费单位为mouth 不大于9) + // AutoRenewTime: 1, + // 自动续费单位("year";"mouth") + // AutoRenewTimeUnit: "year", + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //批量创建云数据库 ddc 实例个数, 最大不超过10,默认1,可选 + PurchaseCount: 1, + //ddc实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //所属系列,Basic:单机基础版,Standard:双机高可用版。仅SQLServer 2012sp3 支持单机基础版。默认Standard,可选 + Category: "Standard", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + ZoneNames: ["cn-bj-a"], + //vpc,如果不提供则属于默认vpc,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []ddc.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, +// 实例绑定的标签信息,可选 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + // 部署集id 可选 + DeployId:"xxxyyy-123", + // 资源池id 必选 + PoolId:"xxxyzzzyy-123", + // 创建双机版主实例支持选择同步方式 Semi_sync:开启半同步/Async:异步 + SyncMode:"Semi_sync", +} +result, err := client.CreateRds(args) +if err != nil { + fmt.Printf("create ddc error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create ddc success, instanceId: ", e) +} +``` + +## 创建只读实例 +使用以下代码可以创建只读实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +args := &ddc.CreateReadReplicaArgs{ + //主实例ID,必选 + SourceInstanceId: "sourceInstanceId" + // 计费相关参数,只读实例只支持后付费Postpaid,必选 + Billing: ddc.Billing{ + PaymentTiming: "Postpaid", + }, + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //批量创建云数据库 ddc 只读实例个数, 目前只支持一次创建一个,可选 + PurchaseCount: 1, + //实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + ZoneNames: ["cn-bj-a"], + //与主实例 vpcId 相同,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []ddc.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + // 部署集id 可选 + DeployId:"xxxyyy-123", + // 资源池id 必选与主实例保持一致 + PoolId:"xxxyzzzyy-123", + // RO组ID。(创建只读实例时) 可选 + // 如果不传,默认会创建一个RO组,并将该只读加入RO组中 + RoGroupId:"yyzzcc", + // RO组是否启用延迟剔除,默认不启动。(创建只读实例时)可选 + EnableDelayOff:false, + // 延迟阈值。(创建只读实例时)可选 + DelayThreshold: 1, + // RO组最少保留实例数目。默认为1. (创建只读实例时)可选 + LeastInstanceAmount: 1, + // 只读实例在RO组中的读流量权重。默认为1(创建只读实例时)可选 + RoGroupWeight: 1, +} +result, err := client.CreateReadReplica(args) +if err != nil { + fmt.Printf("create ddc readReplica error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create ddc readReplica success, instanceId: ", e) +} +``` + +## 实例详情 + +使用以下代码可以查询指定实例的详情。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.GetDetail(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取实例详情信息 +fmt.Println("ddc instanceId: ", result.InstanceId) +fmt.Println("ddc instanceName: ", result.InstanceName) +fmt.Println("ddc engine: ", result.Engine) +fmt.Println("ddc engineVersion: ", result.EngineVersion) +fmt.Println("ddc instanceStatus: ", result.InstanceStatus) +fmt.Println("ddc cpuCount: ", result.CpuCount) +fmt.Println("ddc memoryCapacity: ", result.MemoryCapacity) +fmt.Println("ddc volumeCapacity: ", result.VolumeCapacity) +fmt.Println("ddc usedStorage: ", result.UsedStorage) +fmt.Println("ddc paymentTiming: ", result.PaymentTiming) +fmt.Println("ddc instanceType: ", result.InstanceType) +fmt.Println("ddc instanceCreateTime: ", result.InstanceCreateTime) +fmt.Println("ddc instanceExpireTime: ", result.InstanceExpireTime) +fmt.Println("ddc publicAccessStatus: ", result.PublicAccessStatus) +fmt.Println("ddc vpcId: ", result.VpcId) +fmt.Println("ddc Subnets: ", result.Subnets) +fmt.Println("ddc BackupPolicy: ", result.BackupPolicy) +fmt.Println("ddc RoGroupList: ", result.RoGroupList) +fmt.Println("ddc NodeMaster: ", result.NodeMaster) +fmt.Println("ddc NodeSlave: ", result.NodeSlave) +fmt.Println("ddc NodeReadReplica: ", result.NodeReadReplica) +fmt.Println("ddc DeployId: ", result.DeployId) +``` + +## 实例列表 +使用以下代码可以查询实例列表信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.ListRdsArgs{ + // 批量获取列表的查询的起始位置,实例列表中Marker需要指定实例Id,可选 + // Marker: "marker", + // 指定每页包含的最大数量(主实例),最大数量不超过1000,缺省值为1000,可选 + MaxKeys: 1, +} +resp, err := client.ListRds(args) + +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("ddc list marker: ", resp.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("ddc list isTruncated: ", resp.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("ddc list nextMarker: ", resp.NextMarker) +// 每页包含的最大数量 +fmt.Println("ddc list maxKeys: ", resp.MaxKeys) + +// 获取instance的列表信息 +for _, e := range resp.Result { + fmt.Println("ddc instanceId: ", e.InstanceId) + fmt.Println("ddc instanceName: ", e.InstanceName) + fmt.Println("ddc engine: ", e.Engine) + fmt.Println("ddc engineVersion: ", e.EngineVersion) + fmt.Println("ddc instanceStatus: ", e.InstanceStatus) + fmt.Println("ddc cpuCount: ", e.CpuCount) + fmt.Println("ddc memoryCapacity: ", e.MemoryCapacity) + fmt.Println("ddc volumeCapacity: ", e.VolumeCapacity) + fmt.Println("ddc usedStorage: ", e.UsedStorage) + fmt.Println("ddc paymentTiming: ", e.PaymentTiming) + fmt.Println("ddc instanceType: ", e.InstanceType) + fmt.Println("ddc instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("ddc instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("ddc publicAccessStatus: ", e.PublicAccessStatus) + fmt.Println("ddc vpcId: ", e.VpcId) +} +``` + +## 删除实例 +使用以下代码可以批量删除实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +// 多个实例间用英文半角逗号","隔开,最多可输入10个 +err := client.DeleteRds(instanceIds) +if err != nil { + fmt.Printf("delete instance error: %+v\n", err) + return +} +fmt.Printf("delete instance success\n") +``` + +## 修改实例名称 +使用以下代码可以修改实例名称。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.UpdateInstanceNameArgs{ + // DDC实例名称,允许小写字母、数字,中文,长度限制为1~64 + InstanceName: "instanceName", +} +err := client.UpdateInstanceName(instanceId, args) +if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return +} +fmt.Printf("update instance name success\n") +``` + +## 主备切换 +使用以下代码可以进行主备切换。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +err := client.SwitchInstance(instanceId) +if err != nil { + fmt.Printf(" main standby switching of the instance error: %+v\n", err) + return +} +fmt.Printf(" main standby switching of the instance success\n") +``` +## 只读组列表 +使用以下代码可以查询只读组列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +resp, err := client.ListRoGroup(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取只读组信息 +for _, e := range resp.RoGroups { + fmt.Println("ddc roGroupId: ", e.RoGroupId) + fmt.Println("ddc vnetIp: ", e.VnetIp) +} +``` + +## VPC列表 +使用以下代码可以查询vpc列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +resp, err := client.ListVpc() +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取vpc列表信息 +for _, e := range* resp { + fmt.Println("ddc vpcId: ", e.VpcId) + fmt.Println("ddc shortId: ", e.ShortId) + fmt.Println("ddc name: ", e.Name) + fmt.Println("ddc cidr: ", e.Cidr) + fmt.Println("ddc status: ", e.Status) + fmt.Println("ddc createTime: ", e.CreateTime) + fmt.Println("ddc description: ", e.Description) + fmt.Println("ddc defaultVpc: ", e.DefaultVpc) + fmt.Println("ddc ipv6Cidr: ", e.Ipv6Cidr) + fmt.Println("ddc auxiliaryCidr: ", e.AuxiliaryCidr) + fmt.Println("ddc relay: ", e.Relay) +} +``` + +## 可用区列表 +使用以下代码可以获取可用区列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +resp, err = client.GetZoneList() +if err != nil { + fmt.Printf("get zone list error: %+v\n", err) + return +} +for _, e := range resp.Zones { + fmt.Println("ddc zoneNames: ", e.ZoneNames) + fmt.Println("ddc apiZoneNames: ", e.ApiZoneNames) + fmt.Println("ddc available: ", e.Available) + fmt.Println("ddc defaultSubnetId: ", e.DefaultSubnetId) +} +``` + +## 子网列表 +使用以下代码可以获取一个实例下的子网列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +args := &rds.ListSubnetsArgs{} +resp, err := client.ListSubnets(args) +if err != nil { + fmt.Printf("get subnet list error: %+v\n", err) + return +} +for _, e := range resp.Subnets { + fmt.Println("ddc name: ", e.Name) + fmt.Println("ddc subnetId: ", e.SubnetId) + fmt.Println("ddc zoneName: ", e.ZoneName) + fmt.Println("ddc shortId: ", e.ShortId) + fmt.Println("ddc vpcId: ", e.VpcId) + fmt.Println("ddc vpcShortId: ", e.VpcShortId) + fmt.Println("ddc az: ", e.Az) + fmt.Println("ddc cidr: ", e.Cidr) + fmt.Println("ddc createdTime: ", e.CreatedTime) + fmt.Println("ddc updatedTime: ", e.UpdatedTime) +} +``` +# 参数管理 + +## 实例参数列表 +使用以下代码可以查询实例参数列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +resp, err := client.ListParameters(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取参数列表信息 +for _, e := range resp.Items { + fmt.Println("ddc name: ", e.Name) + fmt.Println("ddc defaultValue: ", e.DefaultValue) + fmt.Println("ddc value: ", e.Value) + fmt.Println("ddc pendingValue: ", e.PendingValue) + fmt.Println("ddc type: ", e.Type) + fmt.Println("ddc dynamic: ", e.Dynamic) + fmt.Println("ddc modifiable: ", e.Modifiable) + fmt.Println("ddc allowedValues: ", e.AllowedValues) + fmt.Println("ddc desc: ", e.Desc) +} +``` + +## 修改实例参数 +使用以下代码可以修改云数据库 DDC 的参数配置。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.UpdateParameterArgs{ + Parameters: []ddc.KVParameter{ + { + Name: "connect_timeout", + Value: "15", + }, + }, +} +err := client.UpdateParameter(instanceId, args) +if err != nil { + fmt.Printf("update parameter: %+v\n", err) + return +} +fmt.Printf("update parameter success\n") +``` + +# 安全管理 + +## 白名单列表 +使用以下代码可以查询实例白名单列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +result, err := client.GetSecurityIps(instanceId) +if err != nil { + fmt.Printf("get securityIp list error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Printf("get securityIp list success\n") +``` + +## 更新白名单 +使用以下代码可以更新一个实例下的白名单列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.UpdateSecurityIpsArgs{ +SecurityIps: []string{ + "%", + "192.0.0.1", + "192.0.0.2", + }, +} +er := client.UpdateSecurityIps(instanceId, args) +if er != nil { + fmt.Printf("update securityIp list error: %+v\n", er) + return +} +fmt.Printf("update securityIp list success\n") +``` + +# 备份管理 +## 获取备份列表 +使用以下代码可以获取一个实例下的备份列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +resp, err := client.GetBackupList(instanceId) +if err != nil { + fmt.Printf("get backup list error: %+v\n", err) + return +} +// 返回标记查询的起始位置 +fmt.Println("ddc usedSpaceInMB: ", resp.UsedSpaceInMB) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("ddc freeSpaceInMB: ", resp.FreeSpaceInMB) +// 获取参数列表信息 +for _, e := range resp.Snapshots { + fmt.Println("ddc snapshotId: ", e.SnapshotId) + fmt.Println("ddc snapshotSizeInBytes: ", e.SnapshotSizeInBytes) + fmt.Println("ddc snapshotType: ", e.SnapshotType) + fmt.Println("ddc snapshotStatus: ", e.SnapshotStatus) + fmt.Println("ddc snapshotStartTime: ", e.SnapshotStartTime) + fmt.Println("ddc snapshotEndTime: ", e.SnapshotEndTime) +} +``` + +## 创建备份 +使用以下代码创建实例备份。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +err := client.CreateBackup(instanceId) +if err != nil { + fmt.Printf("create backup error: %+v\n", err) + return +} +fmt.Printf("create backup success\n") +``` + +## 备份详情 +使用以下代码可以查询一个备份的详情。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +resp, err := client.GetBackupDetail(instanceId, snapshotId) +if err != nil { + fmt.Printf("get backup detail error: %+v\n", err) + return +} + +fmt.Println("ddc snapshotId: ", resp.Snapshot.SnapshotId) +fmt.Println("ddc instanceName: ", resp.Snapshot.SnapshotSizeInBytes) +fmt.Println("ddc engine: ", resp.Snapshot.SnapshotType) +fmt.Println("ddc engineVersion: ", resp.Snapshot.SnapshotStatus) +fmt.Println("ddc instanceStatus: ", resp.Snapshot.SnapshotStartTime) +fmt.Println("ddc cpuCount: ", resp.Snapshot.SnapshotEndTime) +fmt.Println("ddc downloadUrl: ", resp.Snapshot.DownloadUrl) +fmt.Println("ddc downloadExpires: ", resp.Snapshot.DownloadExpires) +``` + +## 设置备份 +使用以下代码设置实例的备份策略。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +args := &ddc.BackupPolicy{ + // 以英文半角逗号分隔的备份时日间,周日为第一天,取值0 + BackupDays: "0,1,2,3,5,6", + // 备份开始时间,使用UTC时间 + BackupTime: "17:00:00Z", + // 是否启用备份数据持久化 + Persistent: true, + // 持久化天数,范围7-730天;未启用则为0或不填 + ExpireInDays: 7, +} +err := client.ModifyBackupPolicy(instanceId, args) +if err != nil { + fmt.Printf("modify instance's backupPolicy error: %+v\n", err) + return +} +fmt.Printf("modify instance's backupPolicy success\n") +``` + +## binlog列表 +使用以下代码可以获取一个实例下的binlog列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" +// datetime UTC时间 +resp, err := client.GetBinlogList(instanceId, datetime) +if err != nil { + fmt.Printf("get binlog list error: %+v\n", err) + return +} +// 获取参数列表信息 +for _, e := range resp.Binlogs { + fmt.Println("ddc binlogId: ", e.BinlogId) + fmt.Println("ddc binlogSizeInBytes: ", e.BinlogSizeInBytes) + fmt.Println("ddc binlogStatus: ", e.BinlogStatus) + fmt.Println("ddc binlogStartTime: ", e.BinlogStartTime) + fmt.Println("ddc binlogEndTime: ", e.BinlogEndTime) +} +``` + +## binlog 详情 +使用以下代码可以查询一个binlog详情。 +```go +// import "github.com/baidubce/bce-sdk-go/services/ddc" + +resp, err := client.GetBinlogDetail(instanceId, binlog) +if err != nil { + fmt.Printf("get binlog detail error: %+v\n", err) + return +} + +fmt.Println("ddc binlogId: ", resp.Binlog.BinlogId) +fmt.Println("ddc binlogSizeInBytes: ", resp.Binlog.BinlogSizeInBytes) +fmt.Println("ddc binlogStatus: ", resp.Binlog.BinlogStatus) +fmt.Println("ddc binlogStartTime: ", resp.Binlog.BinlogStartTime) +fmt.Println("ddc binlogEndTime: ", resp.Binlog.BinlogEndTime) +fmt.Println("ddc downloadUrl: ", resp.Binlog.DownloadUrl) +fmt.Println("ddc downloadExpires: ", resp.Binlog.DownloadExpires) +``` + + +# 错误处理 + +GO语言以error类型标识错误,DDC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | DDC服务返回的错误 + +用户使用SDK调用DDC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// ddcClient 为已创建的DDC Client对象 +result, err := client.ListDdcInstance() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向DDC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当DDC服务端出现异常时,DDC服务端会返回给用户相应的错误信息,以便定位问题。 + +## SDK日志 + +DDC GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +DDC GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the DDC go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the DDC go sdk") +``` + + + +首次发布: + + - 支持创建账号、更新账号密码、更新账号备注、更新账号权限、查询账号列表、查询特定账号信息、删除特定账号信息 +- 支持创建数据库、更新数据库备注、查询数据库列表、查询特定数据库信息、删除特定数据库信息 \ No newline at end of file diff --git a/bce-sdk-go/doc/DDCv2.md b/bce-sdk-go/doc/DDCv2.md new file mode 100644 index 0000000..79edd81 --- /dev/null +++ b/bce-sdk-go/doc/DDCv2.md @@ -0,0 +1,2831 @@ +# DDC-RDS服务 + +# 概述 + +本文档主要介绍DDC-RDS GO SDK的使用。在使用本文档前,您需要先了解DDC和RDS的一些基本知识,并已开通了DDC服务和RDS服务。 + +# 初始化 + +## 确认Endpoint + + +目前支持“华东-苏州”区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +SU | ddc.su.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云DDC-RDS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问DDC-RDS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建DDC-RDS Client + +DDC-RDS Client是同时支持DDC和RDS服务的客户端,为开发者与DDC和RDS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建DDC-RDS Client + +通过AK/SK方式访问DDC-RDS,用户可以参考如下代码新建一个DDC-RDS Client: + +```go +import ( + ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个DDC-RDSClient + client, err := ddcrds.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。 +第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名`ddc.su.baidubce.com`作为DDC-RDS的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为苏州,则为`ddc.su.baidubce.com`。 + +### 使用STS创建DDC-RDS Client + +**申请STS token** + +DDC-RDS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问DDC-RDS,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建DDC-RDS Client** + +申请好STS后,可将STS Token配置到DDC-RDS Client中,从而实现通过STS Token创建DDC-RDS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建DDC-RDS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 + ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" //导入DDC-RDS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建DDC-RDS服务的Client对象,Endpoint使用默认值 + client, err := ddcrds.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "ddc.su.baidubce.com") + if err != nil { + fmt.Println("create v2 client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + client.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置DDC-RDS Client时,无论对应DDC-RDS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问DDC-RDS + +DDC-RDS支持HTTPS传输协议,您可以通过在创建DDC-RDS Client对象时指定的Endpoint中指明HTTPS的方式,在DDC-RDS GO SDK中使用HTTPS访问DDC-RDS服务: + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +ENDPOINT := "https://ddc.su.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +client, _ := ddcrds.NewClient(AK, SK, ENDPOINT) +``` + +## 配置DDC-RDS Client + +如果用户需要配置DDC-RDS Client的一些细节的参数,可以在创建DDC-RDS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 +### 切换地域 + +下面一段代码可以让客户端使用切换地域: +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +//创建DDC-RDS Client对象 +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddcrds.NewClient(AK, SK, ENDPOINT) + +// 切换到北京地域 +client.ConfigRegion("BJ") +``` + + +### 使用代理 + +下面一段代码可以让客户端使用代理访问DDC-RDS服务: + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +//创建DDC-RDS Client对象 +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddcrds.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.ConfigProxyUrl("127.0.0.1:8080") +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddcrds.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.ConfigRetry(bce.NewNoRetryPolicy()) + +// 配置连接超时时间为30秒 +client.ConfigConnectionTimeoutInMillis(30 * 1000) +``` + +### 配置生成签名字符串选项 + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +AK, SK := , +ENDPOINT := "ddc.su.baidubce.com" +client, _ := ddcrds.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.ConfigSignOptionHeadersToSign(headersToSign) + +// 配置签名的有效期为30秒 +client.ConfigSignOptionExpireSeconds(30) +``` + +**参数说明** + +用户使用GO SDK访问DDC-RDS时,创建的DDC-RDS Client对象的`Config`字段支持的所有参数如下表所示,可以通过 +`Config{Field}()`等方法设置配置项,例如:`ConfigRegion("BJ")` + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建DDC-RDS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# DDC-RDS管理 +DDC-RDS服务可以管理以下两种服务 +- 云数据库专属集群 DDC (Dedicated Database Cluster)是专业、高性能、高可靠的云数据库服务。云数据库 DDC 提供 Web 界面进行配置、操作数据库实例,还为您提供可靠的数据备份和恢复、完备的安全管理、完善的监控、轻松扩展等功能支持。相对于自建数据库,云数据库 DDC 具有更经济、更专业、更高效、更可靠、简单易用等特点,使您能更专注于核心业务。 +- 云数据库 RDS (Relational Database Service)是专业、高性能、高可靠的云数据库服务。云数据库 RDS 提供 Web 界面进行配置、操作数据库实例,还为您提供可靠的数据备份和恢复、完备的安全管理、完善的监控、轻松扩展等功能支持。相对于自建数据库,云数据库 RDS 具有更经济、更专业、更高效、更可靠、简单易用等特点,使您能更专注于核心业务。 + +# 资源池管理 + +## 查询资源池列表 +使用以下代码可以查询当前用户的资源池列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +result, err := client.ListPool(nil, "ddc") +if err != nil { + fmt.Printf("list pool error: %+v\n", err) + return +} + +for i := range result.Result { + pool := result.Result[i] + fmt.Println("ddc pool id: ", pool.PoolID) + fmt.Println("ddc pool vpc id: ", pool.VpcID) + fmt.Println("ddc pool engine: ", pool.Engine) + fmt.Println("ddc pool create time: ", pool.CreateTime) + fmt.Println("ddc pool hosts: ", pool.Hosts) +} +``` + +## 查询资源池余量 +使用以下代码可以查询当前指定资源池的资源余量(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +residual, err := client.GetResidual(poolId) +if err != nil { + fmt.Printf("get residual of pool error: %+v\n", err) + return +} +fmt.Println("get residual of pool success.") +for zoneName, residualByZone := range residual.Residual { + // 可用区名称 + fmt.Println("Zone name: ", zoneName) + // 单机版余量 + fmt.Printf("Single residual: disk %v GB, memory %v GB, cpu cores %d\n", + residualByZone.Single.DiskInGb, residualByZone.Single.MemoryInGb, residualByZone.Single.CPUInCore) + // 只读资源余量 + fmt.Printf("Slave residual: disk %v GB, memory %v GB, cpu cores %d\n", + residualByZone.Slave.DiskInGb, residualByZone.Slave.MemoryInGb, residualByZone.Slave.CPUInCore) + // 双机版余量 + fmt.Printf("HA residual: disk %v GB, memory %v GB, cpu cores %d\n", + residualByZone.HA.DiskInGb, residualByZone.HA.MemoryInGb, residualByZone.HA.CPUInCore) +} +``` + +## 查询资源池套餐余量 +使用以下代码可以查询当前指定资源池的套餐余量(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// 指定套餐 +args := &ddcrds.GetFlavorCapacityArgs{ + CpuInCore: 2, + MemoryInGb: 4, + DiskInGb: 50, + // 指定亲和度 + Affinity: 2, +} +// 使用默认亲和度,默认为10 +// args := ddcrds.NewDefaultGetFlavorCapacityArgs(2,4,50) +capacityResult, err := client.GetFlavorCapacity(poolId, args) +if err != nil { + fmt.Printf("get flavor capacity of pool error: %+v\n", err) + return +} +fmt.Println("get flavor capacity of pool success.") +for zoneName, residualByZone := range capacityResult.Capacity { + // 可用区名称 + fmt.Println("Zone name: ", zoneName) + // 双机版余量 + fmt.Printf("HA capacity: %d\n", residualByZone.HA) + // 单机版余量 + fmt.Printf("Single capacity: %d\n", residualByZone.Single) + // 只读实例余量 + fmt.Printf("Slave capacity: %d\n", residualByZone.Slave) +} +``` + +# 部署集管理 + +## 创建部署集 +使用以下代码可以在指定资源池下创建一个新的部署集(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +args := &ddcrds.CreateDeployRequest{ + // 幂等 Token + ClientToken: "xxxyyyzzz", + // 部署集名称 + DeployName: "api-from-go", + // 亲和度阈值 取值范围【0-96】 + CentralizeThreshold: 23, +} +deploy,err := client.CreateDeploySet(poolId, args) +if err != nil { + fmt.Printf("create deploy set error: %+v\n", err) + return +} + +fmt.Println("create deploy set success.") +fmt.Println("returned deploy id: ", deploy.DeployID) +``` + +## 查询部署集列表 +使用以下代码可以查询指定资源池下的部署集列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +result, err := client.ListDeploySets(poolId, nil) +if err != nil { + fmt.Printf("list deploy set error: %+v\n", err) + return +} + +for i := range result.Result { + deploy := result.Result[i] + fmt.Println("ddc deploy id: ", deploy.DeployID) + fmt.Println("ddc deploy name: ", deploy.DeployName) + fmt.Println("ddc deploy strategy: ", deploy.Strategy) + fmt.Println("ddc deploy create time: ", deploy.CreateTime) + fmt.Println("ddc deploy centralizeThreshold: ", deploy.CentralizeThreshold) + fmt.Println("ddc instance ids: ", deploy.Instances) +} +``` + +## 查询特定部署集信息 +使用以下代码可以查询特定部署集的详细信息(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +deploy, err := client.GetDeploySet(poolId, deployId) +if err != nil { + fmt.Printf("get deploy set error: %+v\n", err) + return +} + +// 获取部署集的详细信息 +fmt.Println("ddc deploy id: ", deploy.DeployID) +fmt.Println("ddc deploy name: ", deploy.DeployName) +fmt.Println("ddc deploy strategy: ", deploy.Strategy) +fmt.Println("ddc deploy create time: ", deploy.CreateTime) +fmt.Println("ddc deploy centralizeThreshold: ", deploy.CentralizeThreshold) +fmt.Println("ddc instance ids: ", deploy.Instances) +``` +## 更新部署集 +使用以下代码更新部署集的部署策略和亲和度(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +args := &ddcrds.UpdateDeployRequest{ + // 幂等 Token + ClientToken: "xxxyyyzzz", + // 部署策略 支持集中部署(centralized)/完全打散(distributed) + Strategy: "distributed", + // 亲和度阈值 取值范围【0-96】,必须大于原亲和度阈值 + CentralizeThreshold: 30, +} +err := client.UpdateDeploySet(poolId, deployId, args) +if err != nil { + fmt.Printf("update deploy set error: %+v\n", err) + return +} + +fmt.Println("update deploy set success.") +``` + +## 删除部署集 +使用以下代码可以删除某个资源池下特定的部署集(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +err := DDC_CLIENT.DeleteDeploySet(poolId, deployId) +if err != nil { + fmt.Printf("delete deploy set error: %+v\n", err) + return +} +fmt.Printf("delete deploy set success\n") +``` + +# 实例管理 + +## 创建实例 +使用以下代码可以创建主实例。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +args := &ddcrds.CreateRdsArgs{ + // 指定ddc的数据库引擎,取值mysql,必选 + Engine: "mysql", + // 指定ddc的数据库版本,必选 + EngineVersion: "5.6", + // 计费相关参数,PaymentTiming取值为 预付费:Prepaid,后付费:Postpaid;Reservation:支付方式为后支付时不需要设置,预支付时必须设置;必选 + // 目前仅支持预付费 + Billing: ddcrds.Billing{ + PaymentTiming: "Prepaid", + Reservation: ddcrds.Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + // 预付费时可指定自动续费参数 AutoRenewTime 和 AutoRenewTimeUnit + // 自动续费时长(续费单位为year 不大于3,续费单位为mouth 不大于9) + AutoRenewTime: 1, + // 自动续费单位("year";"month") + AutoRenewTimeUnit: "month", + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //批量创建云数据库 ddc 实例个数, 最大不超过10,默认1,可选 + PurchaseCount: 1, + //ddc实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //所属系列,Singleton:单机版,Basic:单机基础版,Standard:双机高可用版。仅SQLServer 2012sp3 支持单机基础版。默认Standard,可选 + Category: "Standard", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + ZoneNames:[]string{"cn-bj-a"}, + //vpc ShortId 如果不提供则属于默认vpc,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认true,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑 + IsDirectPay: true, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []ddcrds.SubnetMap{ + { + ZoneName: "cn-bj-a", + // 指定子网的ShortId + SubnetId: "subnet-short-id", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []ddcrds.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + // 部署集id 产品类型为DDC时必选,产品类型为RDS忽略该参数 + DeployId:"xxxyyy-123", + // 资源池id 产品类型为DDC时必选,产品类型为RDS忽略该参数 + PoolId:"xxxyzzzyy-123", + // 创建双机版主实例支持选择同步方式 Semi_sync:开启半同步/Async:异步 + SyncMode:"Semi_sync", +} +// 创建DDC数据库专属集群产品,需要传入产品类型参数ddc +result, err := client.CreateRds(args,"ddc") +if err != nil { + fmt.Printf("create ddc error: %+v\n", err) + return +} + +fmt.Println("create ddc success, orderId: ", result.OrderId) +for _, e := range result.InstanceIds { + fmt.Println("create ddc success, instanceId: ", e) +} + +// RDS +// 创建RDS数据库,需要传入产品类型参数rds +result, err = client.CreateRds(args,"rds") +if err != nil { + fmt.Printf("create ddc error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create ddc success, instanceId: ", e) +} +``` + +## 创建只读实例 +使用以下代码可以创建只读实例。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC +args := &ddcrds.CreateReadReplicaArgs{ + //主实例ID,必选 + SourceInstanceId: "sourceInstanceId", + // 计费相关参数,只读实例只支持后付费Prepaid,必选 + Billing: ddcrds.Billing{ + PaymentTiming: "Prepaid", + Reservation: ddcrds.Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + // 预付费时可指定自动续费参数 AutoRenewTime 和 AutoRenewTimeUnit + // 自动续费时长(续费单位为year 不大于3,续费单位为mouth 不大于9) + AutoRenewTime: 1, + // 自动续费单位("year";"month") + AutoRenewTimeUnit: "month", + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //批量创建云数据库 只读实例个数, 目前rds产品只支持一次创建一个,必选 + PurchaseCount: 1, + //实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + ZoneNames: []string{"cn-bj-a"}, + //与主实例 vpcId 相同,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认true,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: true, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []ddcrds.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []ddcrds.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + // 部署集id 产品类型为DDC时必选,产品类型为RDS忽略该参数 + DeployId:"xxxyyy-123", + // 资源池id 产品类型为DDC时必选,产品类型为RDS忽略该参数 与主实例保持一致 + PoolId:"xxxyzzzyy-123", + // RO组ID。(创建只读实例时) 可选 + // 如果不传,默认会创建一个RO组,并将该只读加入RO组中 + RoGroupId:"yyzzcc", + // RO组是否启用延迟剔除,默认为0。可选值0和1,0代表不开启,1代表开启(创建只读实例时)可选 + EnableDelayOff:"1", + // 延迟阈值,单位为秒。(创建只读实例时)可选 + DelayThreshold: "1", + // RO组最少保留实例数目。默认为1. (创建只读实例时)可选 + LeastInstanceAmount: "1", + // 只读实例在RO组中的读流量权重,取值范围为[0-100]。默认为50(创建只读实例时)可选 + RoGroupWeight: "50", +} +result, err := client.CreateReadReplica(args) +if err != nil { + fmt.Printf("create ddc readReplica error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create ddc readReplica success, instanceId: ", e) +} + +// RDS +result, err = client.CreateReadReplica(args) +if err != nil { + fmt.Printf("create rds readReplica error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create rds readReplica success, instanceId: ", e) +} +``` + +## 实例详情 + +使用以下代码可以查询指定实例的详情。 +```go +package main +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +result, err := client.GetDetail(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取实例详情信息 +fmt.Println("ddc instanceId: ", result.InstanceId) +fmt.Println("ddc instanceName: ", result.InstanceName) +fmt.Println("ddc engine: ", result.Engine) +fmt.Println("ddc engineVersion: ", result.EngineVersion) +fmt.Println("ddc instanceStatus: ", result.InstanceStatus) +fmt.Println("ddc cpuCount: ", result.CpuCount) +fmt.Println("ddc memoryCapacity: ", result.MemoryCapacity) +fmt.Println("ddc volumeCapacity: ", result.VolumeCapacity) +fmt.Println("ddc usedStorage: ", result.UsedStorage) +fmt.Println("ddc paymentTiming: ", result.PaymentTiming) +fmt.Println("ddc instanceType: ", result.InstanceType) +fmt.Println("ddc instanceCreateTime: ", result.InstanceCreateTime) +fmt.Println("ddc instanceExpireTime: ", result.InstanceExpireTime) +fmt.Println("ddc publicAccessStatus: ", result.PublicAccessStatus) +fmt.Println("ddc vpcId: ", result.VpcId) +fmt.Println("ddc Subnets: ", result.Subnets) +fmt.Println("ddc BackupPolicy: ", result.BackupPolicy) +fmt.Println("ddc RoGroupList: ", result.RoGroupList) +fmt.Println("ddc NodeMaster: ", result.NodeMaster) +// 主角色所在物理机主机名 +fmt.Println("master BBC hostname: ", result.NodeMaster.HostName) +fmt.Println("ddc NodeSlave: ", result.NodeSlave) +// 备角色所在物理机主机名 +fmt.Println("slave BBC hostname: ", result.NodeSlave.HostName) +fmt.Println("ddc NodeReadReplica: ", result.NodeReadReplica) +fmt.Println("ddc DeployId: ", result.DeployId) +fmt.Println("ddc SyncMode: ", result.SyncMode) +fmt.Println("ddc Category: ", result.Category) +fmt.Println("ddc ZoneNames: ", result.ZoneNames) +fmt.Println("ddc Endpoint: ", result.Endpoint) +fmt.Println("ddc vnetIp: ", result.Endpoint.VnetIp) +// 备库访问Ip +fmt.Println("ddc vnetIpBackup: ", result.Endpoint.VnetIpBackup) +// 拓扑信息 +fmt.Println("ddc topo: ", result.InstanceTopoForReadonly) + +// RDS +result, err := client.GetDetail(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取实例详情信息 +fmt.Println("rds instanceId: ", result.InstanceId) +fmt.Println("rds instanceName: ", result.InstanceName) +fmt.Println("rds engine: ", result.Engine) +fmt.Println("rds engineVersion: ", result.EngineVersion) +fmt.Println("rds instanceStatus: ", result.InstanceStatus) +fmt.Println("rds cpuCount: ", result.CpuCount) +fmt.Println("rds memoryCapacity: ", result.MemoryCapacity) +fmt.Println("rds volumeCapacity: ", result.VolumeCapacity) +fmt.Println("rds usedStorage: ", result.UsedStorage) +fmt.Println("rds paymentTiming: ", result.PaymentTiming) +fmt.Println("rds instanceType: ", result.InstanceType) +fmt.Println("rds instanceCreateTime: ", result.InstanceCreateTime) +fmt.Println("rds instanceExpireTime: ", result.InstanceExpireTime) +fmt.Println("rds publicAccessStatus: ", result.PublicAccessStatus) +fmt.Println("rds vpcId: ", result.VpcId) +fmt.Println("rds Subnets: ", result.Subnets) +fmt.Println("rds BackupPolicy: ", result.BackupPolicy) +fmt.Println("rds RoGroupList: ", result.RoGroupList) +fmt.Println("rds NodeMaster: ", result.NodeMaster) +fmt.Println("rds NodeSlave: ", result.NodeSlave) +fmt.Println("rds NodeReadReplica: ", result.NodeReadReplica) +fmt.Println("rds DeployId: ", result.DeployId) +fmt.Println("rds SyncMode: ", result.SyncMode) +fmt.Println("rds Category: ", result.Category) +fmt.Println("rds ZoneNames: ", result.ZoneNames) +fmt.Println("rds Endpoint: ", result.Endpoint) +// 自动续费规则 +if result.AutoRenewRule != nil { + fmt.Println("ddc renewTime: ", result.AutoRenewRule.RenewTime) + fmt.Println("ddc renewTimeUnit: ", result.AutoRenewRule.RenewTimeUnit) +} +``` + +## 实例列表 +使用以下代码可以查询实例列表信息,优先获取DDC实例列表,获取完成后再获取RDS实例列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC&RDS +args := &ddcrds.ListRdsArgs{ + // 批量获取列表的查询的起始位置,实例列表中Marker需要指定实例Id,可选 + // Marker: "marker", + // 指定每页包含的最大数量(主实例),最大数量不超过1000,缺省值为1000,可选 + MaxKeys: 1, +} +resp, err := client.ListRds(args) + +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("list marker: ", resp.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("list isTruncated: ", resp.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("list nextMarker: ", resp.NextMarker) +// 每页包含的最大数量 +fmt.Println("list maxKeys: ", resp.MaxKeys) + +// 获取instance的列表信息 +for _, e := range resp.Instances { + fmt.Println("instance productType: ", e.ProductType()) + fmt.Println("instanceId: ", e.InstanceId) + fmt.Println("instanceName: ", e.InstanceName) + fmt.Println("engine: ", e.Engine) + fmt.Println("engineVersion: ", e.EngineVersion) + fmt.Println("instanceStatus: ", e.InstanceStatus) + fmt.Println("cpuCount: ", e.CpuCount) + fmt.Println("memoryCapacity: ", e.MemoryCapacity) + fmt.Println("volumeCapacity: ", e.VolumeCapacity) + fmt.Println("usedStorage: ", e.UsedStorage) + fmt.Println("paymentTiming: ", e.PaymentTiming) + fmt.Println("instanceType: ", e.InstanceType) + fmt.Println("instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("publicAccessStatus: ", e.PublicAccessStatus) + fmt.Println("vpcId: ", e.VpcId) + fmt.Println("endpoint: ", e.Endpoint) + fmt.Println("vnetIp: ", e.Endpoint.VnetIp) + fmt.Println("vnetIpBackup: ", e.Endpoint.VnetIpBackup) + // 物理机信息 + fmt.Println("long BBC Id: ", e.LongBBCId) + fmt.Println("BBC hostname: ", e.HostName) + // 自动续费规则 + if e.AutoRenewRule != nil { + fmt.Println("renewTime: ", e.AutoRenewRule.RenewTime) + fmt.Println("renewTimeUnit: ", e.AutoRenewRule.RenewTimeUnit) + } +} +``` + +## 实例分页列表 +使用以下代码可以分页查询实例列表信息,支持添加筛选条件。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +args := &ddcrds.ListPageArgs{ + // 页码 + PageNo: 1, + // 页大小 + PageSize: 5, + // 筛选条件 + // 筛选字段类型,各筛选条件只能单独筛选 + // 当KeywordType取值为type、status、dbType、zone时可在Filters数组中追加筛选项 + // all:匹配全部 + // instanceName:匹配实例名称 + // instanceId:匹配实例id; + // vnetIpBackup:备库ip; + // vnetIp:主库ip + Filters: []ddcrds.Filter{ + {KeywordType: "all", Keyword: "mysql"}, + {KeywordType: "zone", Keyword: "cn-bj-a"}, + }, +} +resp, err := DDCRDS_CLIENT.ListPage(args) + +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} + +// 返回分页页码 +fmt.Println("list pageNo: ", resp.Page.PageNo) +// 返回页大小 +fmt.Println("list pageSize: ", resp.Page.PageSize) +// 返回总数量 +fmt.Println("list totalCount: ", resp.Page.TotalCount) + +// 获取instance的列表信息 +for _, e := range resp.Page.Result { + fmt.Println("instanceId: ", e.InstanceId) + fmt.Println("instanceName: ", e.InstanceName) + fmt.Println("engine: ", e.Engine) + fmt.Println("engineVersion: ", e.EngineVersion) + fmt.Println("instanceStatus: ", e.InstanceStatus) + fmt.Println("cpuCount: ", e.CpuCount) + fmt.Println("memoryCapacity: ", e.MemoryCapacity) + fmt.Println("volumeCapacity: ", e.VolumeCapacity) + fmt.Println("usedStorage: ", e.UsedStorage) + fmt.Println("paymentTiming: ", e.PaymentTiming) + fmt.Println("instanceType: ", e.InstanceType) + fmt.Println("instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("publiclyAccessible: ", e.PubliclyAccessible) + fmt.Println("backup expireInDays: ", e.BackupPolicy.ExpireInDays) + fmt.Println("vpcId: ", e.VpcId) + fmt.Println("endpoint: ", e.Endpoint) + fmt.Println("vnetIp: ", e.Endpoint.VnetIp) + fmt.Println("vnetIpBackup: ", e.Endpoint.VnetIpBackup) + fmt.Println("long BBC Id: ", e.LongBBCId) + fmt.Println("bbc hostname: ", e.HostName) + // 自动续费规则 + if e.AutoRenewRule != nil { + fmt.Println("renewTime: ", e.AutoRenewRule.RenewTime) + fmt.Println("renewTimeUnit: ", e.AutoRenewRule.RenewTimeUnit) + } +} +``` + +## 获取磁盘信息 +使用以下代码可以获取指定实例下磁盘的详细信息。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +disk, err := client.GetDisk(instanceId) +if err != nil { + fmt.Printf("get disk of instance error: %+v\n", err) + return +} +fmt.Println("get disk of instance success.") +for _, diskItem := range disk.Response.Items { + fmt.Println("instance id: ", diskItem.InstanceID) + fmt.Println("instance role: ", diskItem.InstanceRole) + fmt.Println("disk disk partition: ", diskItem.DiskPartition) + fmt.Println("disk totle size in bytes: ", diskItem.TotalSize) + fmt.Println("disk used size in bytes: ", diskItem.UsedSize) + fmt.Println("disk report time: ", diskItem.ReportTime) +} +``` + +## 获取物理机资源信息 +使用以下代码可以获取指定实例所在物理机资源信息。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +machine, err := client.GetMachineInfo(instanceId) +if err != nil { + fmt.Printf("get machine info error: %+v\n", err) + return +} +fmt.Println("get machine info success.") +for _, machine := range machine.Response.Items { + fmt.Println("instance id: ", machine.InstanceID) + fmt.Println("instance role: ", machine.Role) + fmt.Println("cpu(core): ", machine.CPUInCore) + fmt.Println("cpu(core) free: ", machine.FreeCPUInCore) + fmt.Println("memory(MB): ", machine.MemSizeInMB) + fmt.Println("memory(MB) free: ", machine.FreeMemSizeInMB) + fmt.Println("disk info: ", machine.SizeInGB) + fmt.Println("----------------------") +} +``` + +## 删除实例 +使用以下代码可以批量删除实例,RDS产品将删除实例,DDC产品会将实例放入回收站。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// 多个实例间用英文半角逗号","隔开,最多可输入10个 +// DDC +err := client.DeleteRds(instanceIds) +if err != nil { + fmt.Printf("delete instance error: %+v\n", err) + return +} +fmt.Printf("delete instance success\n") + +// RDS +err := client.DeleteRds(instanceIds) +if err != nil { + fmt.Printf("delete instance error: %+v\n", err) + return +} +fmt.Printf("delete instance success\n") + +``` + +## 修改实例名称 +使用以下代码可以修改实例名称。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.UpdateInstanceNameArgs{ + // DDC实例名称,允许小写字母、数字,中文,长度限制为1~64 + InstanceName: "instanceName", +} +// DDC +err := client.UpdateInstanceName(instanceId, args) +if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return +} +fmt.Printf("update instance name success\n") + +// RDS +err := client.UpdateInstanceName(instanceId, args) +if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return +} +fmt.Printf("update instance name success\n") +``` + +## 主备切换 +使用以下代码可以进行主备切换,支持立即切换或者下一个操作窗口内切换(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.SwitchArgs{ + // 立即切换 + IsSwitchNow: true, +} +result, err := client.SwitchInstance(instanceId, args) +if err != nil { + fmt.Printf(" main standby switching of the instance error: %+v\n", err) + return +} +if result != nil { + fmt.Printf(" main standby switching of the instance success, taskId: %v\n", result.Result.TaskID) +} else { + fmt.Printf(" main standby switching of the instance success\n") +} +``` + +## 只读组列表 +使用以下代码可以查询只读组列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +resp, err := client.ListRoGroup(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取只读组信息 +for _, e := range resp.RoGroups { + fmt.Println("ddc roGroupId: ", e.RoGroupId) + fmt.Println("ddc vnetIp: ", e.VnetIp) +} +``` +> 注意: +> - 实例状态为Available,实例必须是主实例。 + + +## 更新只读组并分配权重 +用于更新只读组的信息,包括设置实例延迟剔除,设置只读实例权重等(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC +replicaWeight := ddcrds.ReplicaWeight{ + // 只读实例ID + InstanceId: replicaId, + // 新权重 + Weight: 20, +} +args := &ddcrds.UpdateRoGroupWeightArgs{ + // 只读实例组名称 + RoGroupName: "testRo", + // RO组是否启用延迟剔除。需传入数字,取值为0或1,0代表不开启,可选 + EnableDelayOff: "0", + // 延迟阈值,单位为秒。需传入数字,可选,启用延迟剔除时必选 + DelayThreshold: "0", + // RO组最少保留实例数目。需传入数字,可选,启用延迟剔除时必选 + LeastInstanceAmount: "1", + // 是否重新进行负载均衡,需传入数字,取值为0或1,可选 + IsBalanceRoLoad: "0", + // 设置只读组的延迟参数,需传入数字,取值范围0-259200秒,开启延迟只读时可修改,可选 + MasterDelay: "0", + // 只读副本新权重数组 + ReplicaList: []ddcrds.ReplicaWeight{replicaWeight}, +} +err := client.UpdateRoGroupReplicaWeight(roGroupId, args, "ddc") +if err != nil { + fmt.Printf("update ddc roGroup replica weight error: %+v\n", err) + return +} +fmt.Println("update ddc roGroup replica weight success") +``` + +## 只读组发起重新负载均衡 +使用以下代码可以对只读组发起一次重新负载均衡(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC +err := client.ReBalanceRoGroup(roGroupId, "ddc") +if err != nil { + fmt.Printf("reBalance ddc roGroup error: %+v\n", err) + return +} +fmt.Println("reBalance ddc roGroup success") +``` + +## 创建RDS代理实例 + +使用以下代码可以创建一个RDS代理实例(仅支持RDS) +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.CreateRdsProxyArgs{ + //主实例ID,必选 + SourceInstanceId: "sourceInstanceId", + // 计费相关参数,代理实例只支持后付费Postpaid,必选 + Billing: ddcrds.Billing{ + PaymentTiming: "Postpaid", + }, + // 代理实例节点数。取值范围2,4,6,8,16,必选 + NodeAmount: 2, + //实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a",建议与主实例的可用区保持一致 + ZoneNames: []string{"cn-bj-a"}, + //与主实例 vpcId 相同,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []ddcrds.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []ddcrds.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +result, err := client.CreateRdsProxy(args) +if err != nil { + fmt.Printf("create rds proxy error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create rds proxy success, instanceId: ", e) +} +``` + +> 注意: +> - 需要在云数据库 RDS 主实例的基础上进行创建 +> - 仅数据库类型为 MySQL 的主实例支持创建只读实例 +> - 代理实例套餐和主实例套餐绑定,主实例版本最低是MySQL 5.6 +> - 每个主实例最多可以创建1个代理实例 +> - 需与主实例在同一vpc中 +> - 代理实例只支持后付费方式购买 + +## RDS实例扩缩容 + +使用以下代码可以对RDS实例扩缩容操作。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.ResizeRdsArgs{ + // cpu核数 + CpuCount: 2, + // 内存大小,单位GB + MemoryCapacity: 8, + // 磁盘大小,单位GB,每5G递增 + VolumeCapacity: 20, + // 代理实例节点数,代理实例变配时此项必填 + NodeAmount: 2, + // 是否进行直接支付,默认true,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + // 是否立即变配 RDS只支持立即变配 + IsResizeNow: true, +} +orderIdResponse, err = client.ResizeRds(instanceId, args) +if err != nil { + fmt.Printf("resize ddc error: %+v\n", err) + return +} +fmt.Println("resize ddc success, orderId: ", orderIdResponse.OrderId) +``` + +> 注意: +> - 实例可选套餐详见(https://cloud.baidu.com/doc/RDS/s/9jwvz0wd3) +> - 主实例或只读实例变配时至少填写cpuCount、memoryCapacity、volumeCapacity其中的一个。 +> - 实例计费方式采用后付费时,可弹性扩缩容;采用预付费方式,不能进行缩容操作。 +> - 只有实例available状态时才可以进行扩缩容操作。 +> - 实例扩缩容之后会重启一次。 +> - 为异步接口,可通过查询实例详情接口查看instanceStatus是否恢复。 + +## 重启实例 + +使用以下代码可以重启实例。 +DDC实例支持用户决定是否延迟重启(下一个操作窗口重启) + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// 立即重启:实例ID为RDS实例ID或DDC实例ID +err := client.RebootInstance(instanceId) +if err != nil { + fmt.Printf("reboot error: %+v\n", err) + return +} + +// 延迟重启(仅支持DDC) +args := &ddcrds.RebootArgs{ + IsRebootNow: false, +} +result, err := client.RebootInstanceWithArgs(instanceId, args) +if err != nil { + fmt.Printf("reboot ddc error: %+v\n", err) + return +} +if result != nil { + fmt.Printf("reboot ddc success, taskId: %+v\n", result.TaskID) +} +``` + +## 修改同步模式 + +使用以下代码可以修改实例同步模式。 + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.ModifySyncModeArgs{ + //"Async"异步复制 + //"Semi_sync"半同步复制。 + SyncMode: "Async", +} +// instanceId为DDC实例ID或RDS实例ID +err := client.ModifySyncMode(instanceId, args) +if err != nil { + fmt.Printf("modify syncMode error: %+v\n", err) + return +} +fmt.Printf("modify syncMode success\n") +``` + +## 修改连接信息 + +使用以下代码可以修改RDS域名前缀(仅支持RDS)。 + +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.ModifyEndpointArgs{ + Address: "newAddress", +} +err := client.ModifyEndpoint(instanceId, args) +if err != nil { + fmt.Printf("modify endpoint error: %+v\n", err) + return +} +fmt.Printf("modify endpoint success\n") +``` + +> 注意: +> +> - 只传输域名前缀即可。域名前缀由小写字母和数字组成,以小写字母开头,长度在3-30之间。 + +## 开关公网访问 +使用以下代码可以修改RDS公网访问状态(仅支持RDS)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.ModifyPublicAccessArgs{ + // true or false + PublicAccess: true, +} +err := client.ModifyPublicAccess(instanceId, args) +if err != nil { + fmt.Printf("modify public access error: %+v\n", err) + return +} +fmt.Printf("modify public access success\n") +``` + +> 注意: +> +> - true:开启公网访问; false:关闭公网访问。 + +## 已创建实例自动续费(仅支持RDS) + +使用以下代码可以为已创建的预付费实例创建自动续费 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.AutoRenewArgs{ + // 自动续费时长(续费单位为year 不大于3,续费单位为month 不大于9)必选 + AutoRenewTime: 1, + // 自动续费单位("year";"month")必选 + AutoRenewTimeUnit: "month", + // 实例id集合,必须为预付费实例的Id列表 必选 + InstanceIds: []string{ + "rds-y9dJu77d", + "rds-aQFOoncr", + }, +} +err := client.AutoRenew(args, "rds") +if err != nil { + fmt.Printf("create auto renew error: %+v\n", err) + return +} +``` +> 注意: +> +> - 用于已创建的实例开启自动续费。 +> - 可以传入多个实例id,多个实例需保证在同一地域。 + +## 查询实例的维护时间窗口 +使用以下代码可以查询实例的维护时间窗口(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +maintainTime,err := client.GetMaintainTime(instanceId) +if err != nil { + fmt.Printf("get maintain time error: %+v\n", err) + return +} +fmt.Println("maintainTime duration", maintainTime.Duration) +fmt.Println("maintainTime period", maintainTime.Period) +fmt.Println("maintainTime startTime", maintainTime.StartTime) +fmt.Printf("get maintain time success\n") +``` + +> 注意: +> +> - startTime 为北京时间24小时制,例如14:00。 + +## 修改实例的维护时间窗口 +使用以下代码可以修改实例的维护时间窗口(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.MaintainTime{ + // 时长间隔,单位为小时 + Duration: 3, + // 1-0分别代表周一到周日 + Period: "1,2,3,4,5,6,0", + // 所有涉及的时间皆为北京时间24小时制 + StartTime: "14:00", +} +err := client.UpdateMaintainTime(instanceId, args) +if err != nil { + fmt.Printf("update maintain time error: %+v\n", err) +} +``` + +> 注意: +> +> - startTime 为北京时间24小时制,例如14:00。 + + +## 查询任务列表 +通过此接口可以获取到任务列表,管理已经执行过的任务,或者时间窗口内即将执行的任务(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.GetMaintainTaskListArgs{ + Marker: ddcrds.Marker{ + MaxKeys: 10, + }, + // 任务起始时间 必选 + StartTime: "2021-07-31 00:00:00", + // 结束时间 可选 + EndTime: "2021-08-10 00:00:00", + } +result, err := client.GetMaintainTaskList(args) +if err != nil { + fmt.Printf("get tasks error: %+v\n", err) + return +} +fmt.Println("get tasks success.") + +// 返回标记查询的起始位置 +fmt.Println("list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("list maxKeys: ", result.MaxKeys) +for _, task := range result.Result { + fmt.Println("task id: ", task.TaskID) + fmt.Println("task name: ", task.TaskName) + fmt.Println("task status: ", task.TaskStatus) + fmt.Println("instance id: ", task.InstanceID) + fmt.Println("instance name: ", task.InstanceName) + fmt.Println("instance region: ", task.Region) + fmt.Println("start time: ", task.StartTime) + fmt.Println("end time: ", task.EndTime) +} +``` + +> 注意: +> +> - StartTime 和 EndTime 格式为yyyy-MM-dd HH:mm:ss,例如2021-07-31 00:00:00。 + +## 查询任务详情 +通过此接口可以查询任务详情,可查询已经执行过的任务,或者时间窗口内即将执行的任务(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +result, err := client.GetMaintainTaskDetail(taskId) +if err != nil { + fmt.Printf("get task detail error: %+v\n", err) + return +} +fmt.Println("get task detail success.") +for _, task := range result.Tasks { + fmt.Println("task id: ", task.TaskID) + fmt.Println("task name: ", task.TaskName) + fmt.Println("instance instanceId: ", task.InstanceID) + fmt.Println("instance instanceName: ", task.InstanceName) + fmt.Println("instance task type: ", task.TaskType) + fmt.Println("task status: ", task.TaskStatus) + fmt.Println("instance create time: ", task.CreateTime) +} +``` + +## 立即执行任务 +通过此接口对维护时间窗口内的任务发起立即执行的命令(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +err := client.ExecuteMaintainTaskImmediately(taskId) +if err != nil { + fmt.Printf("execute task invoke error: %+v\n", err) + return +} +fmt.Println("execute task invoke success.") +``` + +> 常见错误: +> +> - task not found:任务列表中无此任务 +> - not in running status:任务已执行结束 +> - it had been updated before:任务已触发立即执行或取消 +> - in maintentime or not set maintentime yet:已处于维护时间窗口或者未设置维护时间窗口 + +## 撤销任务 +通过此接口对维护时间窗口内的任务发起撤销命令(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +err := client.CancelMaintainTask(taskId) +if err != nil { + fmt.Printf("cancel task invoke error: %+v\n", err) + return +} +fmt.Println("cancel task invoke success.") +``` + +> 常见错误: +> +> - task not found:任务列表中无此任务 +> - not in running status:任务已执行结束 +> - it had been updated before:任务已触发立即执行或取消 +> - in maintentime or not set maintentime yet:已处于维护时间窗口或者未设置维护时间窗口 + +## 获取回收站中的实例列表 +使用以下代码可以获取回收站中的实例列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// marker分页参数 +marker := &ddcrds.Marker{MaxKeys: 10} +instances, err := client.ListRecycleInstances(marker, "ddc") +if err != nil { + fmt.Printf("list recycler instances error: %+v\n", err) + return +} +for _, instance := range instances.Result { + fmt.Println("instanceId: ", instance.InstanceId) + fmt.Println("instanceName: ", instance.InstanceName) + fmt.Println("engine: ", instance.Engine) + fmt.Println("engineVersion: ", instance.EngineVersion) + fmt.Println("instanceStatus: ", instance.InstanceStatus) + fmt.Println("cpuCount: ", instance.CpuCount) + fmt.Println("memoryCapacity: ", instance.MemoryCapacity) + fmt.Println("volumeCapacity: ", instance.VolumeCapacity) + fmt.Println("usedStorage: ", instance.UsedStorage) + fmt.Println("instanceType: ", instance.InstanceType) + fmt.Println("instanceCreateTime: ", instance.InstanceCreateTime) + fmt.Println("instanceExpireTime: ", instance.InstanceExpireTime) + fmt.Println("publicAccessStatus: ", instance.PublicAccessStatus) + fmt.Println("vpcId: ", instance.VpcId) +} +``` + +## 从回收站中批量恢复实例 +使用以下代码可以从回收站中批量恢复实例(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// 要恢复的实例Id列表 +instanceIds := []string{ + instanceId_1, + instanceId_2, +} +orderIdResponse, err := client.RecoverRecyclerInstances(instanceIds) +if err != nil { + fmt.Printf("recover recycler instances error: %+v\n", err) + return +} +fmt.Println("recover recycler instances success, orderId: ", orderIdResponse.OrderId) +``` + +## 从回收站中批量删除实例 +使用以下代码可以从回收站中批量删除实例,实例将被彻底删除(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// 要删除的实例Id列表 +instanceIds := []string{ + instanceId_1, + instanceId_2, +} +err := client.DeleteRecyclerInstances(instanceIds) +if err != nil { + fmt.Printf("delete recycler instances error: %+v\n", err) + return +} +fmt.Println("delete recycler instances success.") +``` + + +# 数据库管理 + +## 创建数据库 + +使用以下代码可以在某个主实例下创建一个新的数据库(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +args := &ddcrds.CreateDatabaseArgs{ + // 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 + ClientToken: "xxxyyyzzz", + // 数据库名称(由大小写字母、数字、下划线组成、字母开头,字母或数字结尾,最长64个字符) + DbName: "dbName", + // 数据库字符集(取值范围:utf8、gbk、latin1、utf8mb4) + CharacterSetName: "utf8", + // 数据库备注,最多256个字符(一个汉字等于三个字符) + Remark: "remark", +} +err := client.CreateDatabase(instanceId, args) +if err != nil { + fmt.Printf("create database error: %+v\n", err) + return +} + +fmt.Println("create database success.") +``` + +> 注意: +> - 实例状态为Available,实例必须是主实例。 + +## 更新数据库备注 + +使用以下代码可以更新数据库的备注(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +args := &ddcrds.UpdateDatabaseRemarkArgs{ + // 数据库备注,最多256个字符(一个汉字等于三个字符) + Remark: "remark", +} +err = client.UpdateDatabaseRemark(instanceId, dbName, args) +if err != nil { + fmt.Printf("update database remark error: %+v\n", err) + return +} + +fmt.Println("update database remark success.") +``` + +## 查询特定数据库信息 + +使用以下代码可以查询特定数据库信息。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +result, err := client.GetDatabase(instanceId,dbName) +if err != nil { + fmt.Printf("get database error: %+v\n", err) + return +} + +// 获取account的列表信息 +fmt.Println("ddc dbName: ", result.DbName) +fmt.Println("ddc characterSetName: ", result.CharacterSetName) +// 数据库状态(创建中:Creating;可用中:Available;删除中:Deleting;已删除:Deleted) +fmt.Println("ddc dbStatus: ", result.DbStatus) +fmt.Println("ddc remark: ", result.Remark) +fmt.Println("ddc accountPrivileges: ", result.AccountPrivileges) +``` + +## 查询数据库列表 + +使用以下代码可以查询指定实例的数据库列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +result, err := client.ListDatabase(instanceId) +if err != nil { + fmt.Printf("list database error: %+v\n", err) + return +} + +// 获取account的列表信息 +for _, database := range result.Databases { + fmt.Println("ddc dbName: ", database.DbName) + fmt.Println("ddc characterSetName: ", database.CharacterSetName) + // 数据库状态(创建中:Creating;可用中:Available;删除中:Deleting;已删除:Deleted) + fmt.Println("ddc dbStatus: ", database.DbStatus) + fmt.Println("ddc remark: ", database.Remark) + fmt.Println("ddc accountPrivileges: ", database.AccountPrivileges) +} +``` + +## 获取数据表大小 + +使用以下代码可以获取指定库下满足条件的数据表的大小。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.GetTableAmountArgs{ + // 实例ID + InstanceId: instanceId, + // 指定数据库名称 + DbName: dbName, + // 模糊搜索值, 可选 + Pattern: search, +} +result, err := DDCRDS_CLIENT.GetTableAmount(args) +if err != nil { + fmt.Printf("get table amount error: %+v\n", err) + return +} +fmt.Printf("get table amount success.\n") +fmt.Println("ddc return amount ", result.ReturnAmount) +fmt.Println("ddc total amount ", result.TotalAmount) +for k, v := range result.Tables { + fmt.Println("ddc table ", k, " size: ", v) +} +``` + +## 获取数据库占用磁盘空间 + +使用以下代码可以获取指定实例下的数据库占用的磁盘空间大小以及剩余磁盘空间。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// dbName可选,不指定数据库时传入空字符串即可 +result, err := DDCRDS_CLIENT.GetDatabaseDiskUsage(instanceId, dbName) +if err != nil { + fmt.Printf("get database disk usage error: %+v\n", err) + return +} +fmt.Printf("get database disk usage success.\n") +fmt.Println("ddc rest disk size(byte) ", result.RestDisk) +fmt.Println("ddc used disk size(byte) ", result.UsedDisk) +for k, v := range result.Databases { + fmt.Println("ddc database ", k, " size(byte): ", v) +} +``` + +## 获取实例数据可恢复时间 + +使用以下代码可以获取实例数据所有的可恢复时间段。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +result, err := DDCRDS_CLIENT.GetRecoverableDateTime(instanceId) +if err != nil { + fmt.Printf("get recoverable datetimes error: %+v\n", err) + return +} +fmt.Printf("get recoverable datetimes success.\n") +for _, e := range result.RecoverableDateTimes { + fmt.Println("recover startTime: ", e.StartDateTime, " endTime: ", e.EndDateTime) +} +``` + +## 恢复数据库 + +使用以下代码可以按时间点恢复指定数据库或数据表到原有实例。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.RecoverInstanceArgs{ + // 可恢复时间点,从GetRecoverableDateTime()获取 + Datetime: "2021-05-25T03:28:30Z", + // RestoreMode 为database或table + RecoverData: []ddcrds.RecoverData{ + { + // 数据库名称 + DbName: dbName, + // 新库名 + NewDbName: newDbName, + RestoreMode: "database", + }, + { + DbName: dbName, + NewDbName: newDbName, + RestoreMode: "table", + // RestoreMode为table时RecoverTables为必选 + RecoverTables: []ddcrds.RecoverTable{ + { + // 表名 + TableName: tableName, + // 新表名 + NewTableName: newTableName, + }, + }, + }, + }, +} +taskResult, err := DDCRDS_CLIENT.RecoverToSourceInstanceByDatetime(instanceId, args) +if err != nil { + fmt.Printf("recover instance database error: %+v\n", err) + return +} +fmt.Printf("recover instance database success. taskId:%s\n", taskResult.TaskID) +``` + +## 删除特定数据库 + +使用以下代码可以删除特定数据库信息。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +err := client.DeleteDatabase(instanceId,dbName) +if err != nil { + fmt.Printf("delete database error: %+v\n", err) + return +} +fmt.Printf("delete database success\n") +``` + +## 延迟删除数据表:创建硬链接 + +使用以下代码可以为数据库下的指定数据表创建硬链接(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +err := client.LazyDropCreateHardLink(instanceId, dbName, tableName) +if err != nil { + fmt.Printf("[lazy drop] create hard link error: %+v\n", err) + return +} +fmt.Println("[lazy drop] create hard link success.") +``` + + +## 延迟删除数据表:删除硬链接 + +使用以下代码可以删除数据库下特定数据表创建的硬链接(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +result, err := client.LazyDropDeleteHardLink(instanceId, dbName, tableName) +if err != nil { + fmt.Printf("[lazy drop] delete hard link error: %+v\n", err) + return +} +fmt.Println("[lazy drop] delete hard link success.taskId:", result.TaskID) +``` +# 会话管理 + +## 执行KillSession任务 + +使用以下代码可以对指定数据库执行KillSession任务。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.KillSessionArgs{ + // 实例角色 + Role: "master", + // Session ID + SessionIds: []int{8661, 8662}, +} +result, err := client.KillSession(instanceId, args) +if err != nil { + fmt.Printf("start kill session task error: %+v\n", err) + return +} +fmt.Println("start kill session task success. TaskID:", result.TaskID) +``` + + +## 查看KillSession任务进度 + +使用以下代码可以查看指定数据库下已执行的KillSession任务的进度。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// taskId 为执行KillSession任务时返回的任务Id +result, err := client.GetKillSessionTask(instanceId, taskId) +if err != nil { + fmt.Printf("get kill session task error: %+v\n", err) + return +} +fmt.Println("get kill session task success.") +for _, task := range result.Tasks { + fmt.Println("sessionId: ", task.SessionID) + fmt.Println("task status: ", task.Status) +} +``` + +# 账号管理 + +## 创建账号 + +使用以下代码可以在某个主实例下创建一个新的账号。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.CreateAccountArgs{ + // 幂等性Token,使用 uuid 生成一个长度不超过64位的ASCII字符串,可选参数 + ClientToken: "xxxyyyzzz", + // 账号名称,由小写字母、数字、下划线组成、字母开头,字母或数字结尾,最长16个字符,不能为保留关键字,必选 + AccountName: "accountName", + // 账号的密码,由字母、数字和特殊字符(!@#%^_)中的至少两种组成,长度8-32位,必选 + Password: "password", + // 账号权限类型,Common:普通帐号,Super:super账号。可选,默认为 Common + AccountType: "Common", + // 权限设置,可选 + DatabasePrivileges: []ddcrds.DatabasePrivilege{ + { + // 数据库名称 + DbName: "user_photo_001", + // 授权类型。ReadOnly:只读,ReadWrite:读写 + AuthType: "ReadOnly", + }, + }, + // 帐号备注,最多256个字符(一个汉字等于三个字符),可选 + Desc: "账号user1", +} +// DDC产品 +err := client.CreateAccount(instanceId, args) +if err != nil { + fmt.Printf("create account error: %+v\n", err) + return +} +// RDS产品 +err = client.CreateAccount(instanceId, args) +if err != nil { + fmt.Printf("create account error: %+v\n", err) + return +} + +fmt.Println("create account success.") +``` +## 更新账号密码 + +使用以下代码可以更新账号的密码(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.UpdateAccountPasswordArgs{ + // 密码,由字母、数字和特殊字符(!@#%^_)中的至少两种组成,长度8-32位,必选 + Password: "password", +} +// DDC +err := client.UpdateAccountPassword(instanceId, accountName, args) +if err != nil { + fmt.Printf("update account password error: %+v\n", err) + return +} + +fmt.Println("update account password success.") +``` + +## 更新账号备注 + +使用以下代码可以更新账号的备注(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.UpdateAccountDescArgs{ + // 帐号备注,最多256个字符(一个汉字等于三个字符),可选 + Desc: "desc", +} +err := client.UpdateAccountDesc(instanceId, accountName, args) +if err != nil { + fmt.Printf("update account desc error: %+v\n", err) + return +} + +fmt.Println("update account desc success.") +``` + +## 更新账号权限 + +使用以下代码可以更新账号的权限(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +databasePrivileges := []ddcrds.DatabasePrivilege{ + { + DbName: "hello", + // 授权类型。ReadOnly:只读,ReadWrite:读写 + AuthType: "ReadOnly", + }, +} + +args := &ddcrds.UpdateAccountPrivilegesArgs{ + DatabasePrivileges: databasePrivileges, +} +// DDC +err = client.UpdateAccountPrivileges(instanceId, accountName, args) +if err != nil { + fmt.Printf("update account privileges error: %+v\n", err) + return +} + +fmt.Println("update account privileges success.") +``` + +## 查询特定账号信息 + +使用以下代码可以查询特定账号信息。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC产品 +result, err := client.GetAccount(instanceId,accountName) +if err != nil { + fmt.Printf("get account error: %+v\n", err) + return +} + +// 获取account的信息 +fmt.Println("ddc accountName: ", result.AccountName) +fmt.Println("ddc desc: ", result.Desc) +// 账号状态(创建中:Creating;可用中:Available;更新中:Updating;删除中:Deleting;已删除:Deleted) +fmt.Println("ddc accountStatus: ", result.Status) +// 账号类型(super账号:Super;普通账号:Common) +fmt.Println("ddc accountType: ", result.AccountType) +fmt.Println("ddc databasePrivileges: ", result.DatabasePrivileges) + +// RDS产品 +result, err = client.GetAccount(instanceId,accountName) + if err != nil { + fmt.Printf("get account error: %+v\n", err) + return +} + +// 获取account的信息 +fmt.Println("ddc accountName: ", result.AccountName) +fmt.Println("ddc desc: ", result.Desc) +// 账号状态(创建中:Creating;可用中:Available;更新中:Updating;删除中:Deleting;已删除:Deleted) +fmt.Println("ddc accountStatus: ", result.Status) +// 账号类型(super账号:Super;普通账号:Common) +fmt.Println("ddc accountType: ", result.AccountType) +fmt.Println("ddc databasePrivileges: ", result.DatabasePrivileges) +``` + +## 查询账号列表 + +使用以下代码可以查询指定实例的账号列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +result, err := client.ListAccount(instanceId) + if err != nil { + fmt.Printf("list account error: %+v\n", err) + return +} + +// 获取account的列表信息 +for _, account := range result.Accounts { + fmt.Println("ddc accountName: ", account.AccountName) + fmt.Println("ddc desc: ", account.Desc) + // 账号状态(创建中:Creating;可用中:Available;更新中:Updating;删除中:Deleting;已删除:Deleted) + fmt.Println("ddc accountStatus: ", account.Status) + // 账号类型(super账号:Super;普通账号:Common) + fmt.Println("ddc accountType: ", account.AccountType) + fmt.Println("ddc databasePrivileges: ", account.DatabasePrivileges) +} + +// RDS +result, err = client.ListAccount(instanceId) + if err != nil { + fmt.Printf("list account error: %+v\n", err) + return +} + +// 获取account的列表信息 +for _, account := range result.Accounts { + fmt.Println("ddc accountName: ", account.AccountName) + fmt.Println("ddc desc: ", account.Desc) + // 账号状态(创建中:Creating;可用中:Available;更新中:Updating;删除中:Deleting;已删除:Deleted) + fmt.Println("ddc accountStatus: ", account.Status) + // 账号类型(super账号:Super;普通账号:Common) + fmt.Println("ddc accountType: ", account.AccountType) + fmt.Println("ddc databasePrivileges: ", account.DatabasePrivileges) +} +``` + +## 删除特定账号信息 + +使用以下代码可以删除特定账号信息。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +err := client.DeleteAccount(instanceId,accountName) + if err != nil { + fmt.Printf("delete account error: %+v\n", err) + return +} +fmt.Printf("delete account success\n") + +// RDS +err = client.DeleteAccount(instanceId,accountName) + if err != nil { + fmt.Printf("delete account error: %+v\n", err) + return +} +fmt.Printf("delete account success\n") +``` + +# 参数管理 + +## 实例参数列表 +使用以下代码可以查询实例参数列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +resp, err := client.ListParameters(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取参数列表信息 +for _, e := range resp.Parameters { + fmt.Println("ddc name: ", e.Name) + fmt.Println("ddc defaultValue: ", e.DefaultValue) + fmt.Println("ddc value: ", e.Value) + fmt.Println("ddc pendingValue: ", e.PendingValue) + fmt.Println("ddc type: ", e.Type) + fmt.Println("ddc dynamic: ", e.Dynamic) + fmt.Println("ddc modifiable: ", e.Modifiable) + fmt.Println("ddc allowedValues: ", e.AllowedValues) + fmt.Println("ddc desc: ", e.Desc) +} + +// RDS +resp, err := client.ListParameters(instanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取参数列表信息 +for _, e := range resp.Parameters { + fmt.Println("rds name: ", e.Name) + fmt.Println("rds defaultValue: ", e.DefaultValue) + fmt.Println("rds value: ", e.Value) + fmt.Println("rds pendingValue: ", e.PendingValue) + fmt.Println("rds type: ", e.Type) + fmt.Println("rds dynamic: ", e.Dynamic) + fmt.Println("rds modifiable: ", e.Modifiable) + fmt.Println("rds allowedValues: ", e.AllowedValues) + fmt.Println("rds desc: ", e.Desc) +} +``` + +## 修改实例参数 +使用以下代码可以修改云数据库 DDC 的参数配置。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.UpdateParameterArgs{ + Parameters: []ddcrds.KVParameter{ + { + Name: "connect_timeout", + Value: "15", + }, + }, + // 执行参数修改任务的方式,默认为0; 0 为立刻执行,1 为时间窗口执行 + WaitSwitch: 1, +} +// DDC +// Etag传入空字符串即可 +result, er := DDCRDS_CLIENT.UpdateParameter(instanceId, etag, args) +ExpectEqual(t.Errorf, nil, er) +if result != nil { + fmt.Println("update parameter task success: ", result.Result.TaskID) +} else { + fmt.Println("update parameter task success.") +} + +// RDS +// RDS修改参数时需要匹配Etag +res, err := client.ListParameters(e.InstanceId) +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +_, err := client.UpdateParameter(instanceId, res.Etag, args) +if err != nil { + fmt.Printf("update parameter: %+v\n", err) + return +} +fmt.Println("update parameter success.") +``` + +# 安全管理 + +## 白名单列表 +使用以下代码可以查询实例白名单列表。 +```go +import ( + "encoding/json" + ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +) + +// DDC +result, err := client.GetSecurityIps(instanceId) +if err != nil { + fmt.Printf("get securityIp list error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Printf("get securityIp list success\n") + +// RDS +result, err := client.GetSecurityIps(instanceId) +if err != nil { + fmt.Printf("get securityIp list error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Printf("get securityIp list success\n") +``` + +## 更新白名单 +使用以下代码可以更新一个实例下的白名单列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.UpdateSecurityIpsArgs{ +SecurityIps: []string{ + "%", + "192.0.0.1", + "192.0.0.2", + }, +} +// DDC +// Etag传入空字符串即可 +er := client.UpdateSecurityIps(instanceId, "",args) +if er != nil { + fmt.Printf("update securityIp list error: %+v\n", er) + return +} +fmt.Printf("update securityIp list success\n") + +// RDS +// Etag传入v0 +er = client.UpdateSecurityIps(instanceId, "v0",args) +if er != nil { + fmt.Printf("update securityIp list error: %+v\n", er) + return +} +fmt.Printf("update securityIp list success\n") +``` + +## 获取VPC下的安全组 +使用以下代码可以获取指定VPC下的安全组列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// vpcId := "vpc-j1vaxw1cx2mw" +securityGroups, err := client.ListSecurityGroupByVpcId(vpcId) +if err != nil { + fmt.Printf("list security group by vpcId error: %+v\n", err) + return +} +for _, group := range *securityGroups { + fmt.Println("securityGroup id: ", group.SecurityGroupID) + fmt.Println("name: ", group.Name) + fmt.Println("description: ", group.Description) + fmt.Println("associateNum: ", group.AssociateNum) + fmt.Println("createdTime: ", group.CreatedTime) + fmt.Println("version: ", group.Version) + fmt.Println("defaultSecurityGroup: ", group.DefaultSecurityGroup) + fmt.Println("vpc name: ", group.VpcName) + fmt.Println("vpc id: ", group.VpcShortID) + fmt.Println("tenantId: ", group.TenantID) +} +fmt.Println("list security group by vpcId success.") +``` + +## 获取实例已绑定安全组 +使用以下代码可以获取指定实例已绑定的安全组列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// instanceId := "ddc-m1h4mma5" +result, err := client.ListSecurityGroupByInstanceId(instanceId) +if err != nil { + fmt.Printf("list security group by instanceId error: %+v\n", err) + return +} +for _, group := range result.Groups { + fmt.Println("securityGroupId: ", group.SecurityGroupID) + fmt.Println("securityGroupName: ", group.SecurityGroupName) + fmt.Println("securityGroupRemark: ", group.SecurityGroupRemark) + fmt.Println("projectId: ", group.ProjectID) + fmt.Println("vpcId: ", group.VpcID) + fmt.Println("vpcName: ", group.VpcName) + fmt.Println("inbound: ", group.Inbound) + fmt.Println("outbound: ", group.Outbound) +} +fmt.Println("list security group by instanceId success.") +``` + +## 绑定安全组 +使用以下代码可以批量将指定的安全组绑定到实例上(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// instanceIds := []string{ +// "ddc-mjafcdu0", +// } +// securityGroupIds := []string{ +// "g-iutg5rtcydsk", +// } +args := &ddcrds.SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, +} + +err := client.BindSecurityGroups(args) +if err != nil { + fmt.Printf("bind security groups to instances error: %+v\n", err) + return +} +fmt.Println("bind security groups to instances success.") +``` +> 注意: +> - 实例状态必须为Available。 +> - 实例ID最多可以传入10个。 +> - 安全组ID最多可以传入10个。 +> - 每个实例最多可以绑定10个安全组。 + +## 解绑安全组 +使用以下代码可以从实例上批量解绑指定的安全组(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// instanceIds := []string{ +// "ddc-mjafcdu0", +// } +// securityGroupIds := []string{ +// "g-iutg5rtcydsk", +// } +args := &ddcrds.SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, +} + +err := client.UnBindSecurityGroups(args) +if err != nil { + fmt.Printf("unbind security groups to instances error: %+v\n", err) + return +} +fmt.Println("unbind security groups to instances success.") +``` +> 注意: +> - 实例状态必须为Available。 +> - 当前版本实例ID最多可以传入1个。 +> - 安全组ID最多可以传入10个。 + +# 备份管理 +## 获取备份列表 +使用以下代码可以获取一个实例下的备份列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC +args := &ddcrds.GetBackupListArgs{} +resp, err := client.GetBackupList(instanceId, args) +if err != nil { + fmt.Printf("get backup list error: %+v\n", err) + return +} +// 返回标记查询的起始位置 +fmt.Println("ddc usedSpaceInMB: ", resp.UsedSpaceInMB) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("ddc freeSpaceInMB: ", resp.FreeSpaceInMB) +// 获取参数列表信息 +for _, e := range resp.Backups { + fmt.Println("ddc snapshotId: ", e.SnapshotId) + fmt.Println("ddc snapshotSizeInBytes: ", e.SnapshotSizeInBytes) + fmt.Println("ddc snapshotType: ", e.SnapshotType) + fmt.Println("ddc snapshotStatus: ", e.SnapshotStatus) + fmt.Println("ddc snapshotStartTime: ", e.SnapshotStartTime) + fmt.Println("ddc snapshotEndTime: ", e.SnapshotEndTime) +} + +// RDS +resp, err = client.GetBackupList(instanceId, args) +if err != nil { + fmt.Printf("get backup list error: %+v\n", err) + return +} +// 返回标记查询的起始位置 +fmt.Println("rds usedSpaceInMB: ", resp.UsedSpaceInMB) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("rds freeSpaceInMB: ", resp.FreeSpaceInMB) +// 获取参数列表信息 +for _, e := range resp.Backups { + fmt.Println("rds snapshotId: ", e.SnapshotId) + fmt.Println("rds snapshotSizeInBytes: ", e.SnapshotSizeInBytes) + fmt.Println("rds snapshotType: ", e.SnapshotType) + fmt.Println("rds snapshotStatus: ", e.SnapshotStatus) + fmt.Println("rds snapshotStartTime: ", e.SnapshotStartTime) + fmt.Println("rds snapshotEndTime: ", e.SnapshotEndTime) +} +``` + +## 创建备份 +使用以下代码创建实例备份(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +err := client.CreateBackup(instanceId) +if err != nil { + fmt.Printf("create backup error: %+v\n", err) + return +} +fmt.Printf("create backup success\n") +``` + +## 查询实例备份状态 +使用以下代码可以查询当前实例是否正在备份以及备份开始的时间(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +backupStatusResult, err := client.GetInstanceBackupStatus(instanceId) +if err != nil { + fmt.Printf("get backup status error: %+v\n", err) + return +} +fmt.Println("get backup status success.") +fmt.Println("instance is backuping: ", backupStatusResult.IsBackuping) +if backupStatusResult.IsBackuping { + fmt.Println("instance backup start time: ", backupStatusResult.SnapshotStartTime) +} +``` + +## 备份详情 +使用以下代码可以查询一个备份的详情(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +resp, err := client.GetBackupDetail(instanceId, snapshotId) +if err != nil { + fmt.Printf("get backup detail error: %+v\n", err) + return +} + +fmt.Println("ddc snapshotId: ", resp.Snapshot.SnapshotId) +fmt.Println("ddc snapshotSizeInBytes: ", resp.Snapshot.SnapshotSizeInBytes) +fmt.Println("ddc snapshotType: ", resp.Snapshot.SnapshotType) +fmt.Println("ddc snapshotStatus: ", resp.Snapshot.SnapshotStatus) +fmt.Println("ddc snapshotStartTime: ", resp.Snapshot.SnapshotStartTime) +fmt.Println("ddc snapshotEndTime: ", resp.Snapshot.SnapshotEndTime) +fmt.Println("ddc downloadUrl: ", resp.Snapshot.DownloadUrl) +fmt.Println("ddc downloadExpires: ", resp.Snapshot.DownloadExpires) +``` + +## 设置备份策略 +使用以下代码设置实例的备份策略(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC +args := &ddcrds.BackupPolicy{ + // 以英文半角逗号分隔的备份时日间,周日为第一天,取值0 + BackupDays: "0,1,2,3,5,6", + // 备份开始时间,使用UTC时间 + BackupTime: "17:00:00Z", + // 是否启用备份数据持久化 + Persistent: true, + // 持久化天数,范围7-730天;未启用则为0或不填 + ExpireInDays: 7, +} +err := client.ModifyBackupPolicy(instanceId, args) +if err != nil { + fmt.Printf("modify instance's backupPolicy error: %+v\n", err) + return +} +fmt.Printf("modify instance's backupPolicy success\n") +``` + +## binlog列表 +使用以下代码可以获取一个实例下的binlog列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// DDC +// datetime UTC时间 +// 获取了两天前的日志备份 +datetime := time.Now(). + AddDate(0, 0, -2). + Format("2006-01-02T15:04:05Z") +resp, err := client.GetBinlogList(instanceId, datetime) +if err != nil { + fmt.Printf("get binlog list error: %+v\n", err) + return +} +// 获取binlog列表信息 +for _, e := range resp.Binlogs { + fmt.Println("ddc binlogId: ", e.BinlogId) + fmt.Println("ddc binlogSizeInBytes: ", e.BinlogSizeInBytes) + fmt.Println("ddc binlogStatus: ", e.BinlogStatus) + fmt.Println("ddc binlogStartTime: ", e.BinlogStartTime) + fmt.Println("ddc binlogEndTime: ", e.BinlogEndTime) +} +``` + +## binlog 详情 +使用以下代码可以查询一个binlog详情(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +resp, err := client.GetBinlogDetail(instanceId, binlogId) +if err != nil { + fmt.Printf("get binlog detail error: %+v\n", err) + return +} + +fmt.Println("ddc binlogId: ", resp.Binlog.BinlogId) +fmt.Println("ddc binlogSizeInBytes: ", resp.Binlog.BinlogSizeInBytes) +fmt.Println("ddc binlogStatus: ", resp.Binlog.BinlogStatus) +fmt.Println("ddc binlogStartTime: ", resp.Binlog.BinlogStartTime) +fmt.Println("ddc binlogEndTime: ", resp.Binlog.BinlogEndTime) +fmt.Println("ddc downloadUrl: ", resp.Binlog.DownloadUrl) +fmt.Println("ddc downloadExpires: ", resp.Binlog.DownloadExpires) +``` + +# 日志管理 + +## 日志列表 +使用以下代码可以获取一个实例下的错误日志或者慢日志列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// import "time" + +// datetime UTC时间 +// 获取两天前的错误日志,传入日期即可 +date := time.Now(). +AddDate(0, 0, -2). +Format("2006-01-02") +args := &ddcrds.ListLogArgs{ + // 日志类型 错误日志为error 慢日志为slow + LogType: "error", + Datetime: date, +} +logs, err := client.ListLogByInstanceId(instanceId, args) +if err != nil { + fmt.Printf("list logs of instance error: %+v\n", err) + return +} +fmt.Println("list logs of instance success.") +for _, log := range *logs { + fmt.Println("id: ", log.LogID) + fmt.Println("size: ", log.LogSizeInBytes) + fmt.Println("start time: ", log.LogStartTime) + fmt.Println("end time: ", log.LogEndTime) +} +``` + +## 日志详情 +使用以下代码可以查询日志的详细信息,包括该日志文件有效的下载链接(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +args := &ddcrds.GetLogArgs{ + // 下载链接有效时间,单位为秒 + ValidSeconds: 20, +} +logId := "errlog.202103091300" +log, err := client.GetLogById(instanceId, logId, args) +if err != nil { + fmt.Printf("get log detail of instance error: %+v\n", err) + return +} +fmt.Println("list logs of instances success.") +fmt.Println("id: ", log.LogID) +fmt.Println("size: ", log.LogSizeInBytes) +fmt.Println("start time: ", log.LogStartTime) +fmt.Println("end time: ", log.LogEndTime) +// 日志文件下载链接 +fmt.Println("download url: ", log.DownloadURL) +// 下载链接截止该时间有效 +fmt.Println("download url expires: ", log.DownloadExpires) +``` + +## 访问日志 +通过此接口可以获取访问日志的下载链接,应获取昨天或者更早的⽇期的访问日志,当⽇的⽇志在第⼆天凌晨打包(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// import "time" + +downloadInfo, err := client.GetAccessLog(date) +if err != nil { + fmt.Printf("get access logs error: %+v\n", err) + return +} +fmt.Println("get access logs success.") +fmt.Println("mysql access logs link: ", downloadInfo.Downloadurl.Mysql) +fmt.Println("bbc access logs link: ", downloadInfo.Downloadurl.Bbc) +fmt.Println("bos access logs link: ", downloadInfo.Downloadurl.Bos) +``` +## 访问快照日志详情 +通过此接口可以获取访问快照日志的详情列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// import "time" + +args := &AccessDetailArgs{ + StartDateTime: "2023-02-02T01:00:00Z", + EndDateTime: "2023-02-02T10:00:00Z", + Marker: "0", + MaxKeys: 100, +} +result, err := client.SnapshotAccessDetail(args) +if err != nil { + fmt.Printf("get snapshot access detail error: %+v\n", err) + return +} +fmt.Printf("get snapshot access detail success\n %+v", result) +``` + +## 访问binlog日志详情 +通过此接口可以获取访问binlog日志的详情列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +// import "time" + +args := &AccessDetailArgs{ + StartDateTime: "2023-02-02T01:00:00Z", + EndDateTime: "2023-02-02T10:00:00Z", + Marker: "0", + MaxKeys: 100, +} +result, err := client.BinlogAccessDetail(args) +if err != nil { + fmt.Printf("get binlog access detail error: %+v\n", err) + return +} +fmt.Printf("get binlog access detail success\n %+v", result) +``` + +## 错误日志 +通过此接口可以获取错误日志(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.GetErrorLogsArgs{ + // 实例ID,必填参数 + InstanceId: "ddc-mp8lme9w", + // 开始时间,UTC 格式,必填参数 + StartTime: "2021-08-16T02:28:51Z", + // 结束时间,UTC 格式,必填参数 + EndTime: "2021-08-17T02:28:51Z", + // 分页页码,必填参数 + PageNo: 1, + // 分页大小,取值范围:[1-2000],必填参数 + PageSize: 10, + // 实例角色,取值:master(主实例-主节点)、backup(主实例-备节点)、slave(只读实例),必填参数 + Role: "master", + // 搜索关键词,选填参数 + KeyWord: "Aborted", +} + +errorLogsResponse, err := client.GetErrorLogs(args) +if err != nil { + fmt.Printf("get error logs error: %+v\n", err) + return +} +fmt.Println("get error logs success.") +fmt.Println("error logs count: ", errorLogsResponse.Count) +for _, errorLog := range errorLogsResponse.ErrorLogs { + fmt.Println("=================================================") + fmt.Println("error log instanceId: ", errorLog.InstanceId) + // 采集时间,本地时间 + fmt.Println("error log executeTime: ", errorLog.ExecuteTime) + fmt.Println("error log logLevel: ", errorLog.LogLevel) + // 日志内容 + fmt.Println("error log logText: ", errorLog.LogText) +} +``` + +## 慢日志 +通过此接口可以获取慢日志(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.GetSlowLogsArgs{ + // 实例ID,必填参数 + InstanceId: "ddc-mp8lme9w", + // 开始时间,UTC 格式,必填参数 + StartTime: "2021-08-16T02:28:51Z", + // 结束时间,UTC 格式,必填参数 + EndTime: "2021-08-17T02:28:51Z", + // 分页页码,必填参数 + PageNo: 1, + // 分页大小,取值范围:[1-2000],必填参数 + PageSize: 10, + // 实例角色,取值:master(主实例-主节点)、backup(主实例-备节点)、slave(只读实例),必填参数 + Role: "master", + // 数据库名列表,选填参数 + DbName: []string{"baidu_dba"}, + // 用户名列表,选填参数 + UserName: []string{"_root"}, + // 客户端IP列表,选填参数 + HostIp: []string{"localhost"}, + // SQL 语句,选填参数 + Sql: "update heartbeat set id=?, value=?", +} + +slowLogsResponse, err := client.GetSlowLogs(args) +if err != nil { + fmt.Printf("get slow logs error: %+v\n", err) + return +} +fmt.Println("get slow logs success.") +fmt.Println("slow logs count: ", slowLogsResponse.Count) +for _, slowLog := range slowLogsResponse.SlowLogs { + fmt.Println("=================================================") + fmt.Println("slow log instanceId: ", slowLog.InstanceId) + fmt.Println("slow log userName: ", slowLog.UserName) + fmt.Println("slow log dbName: ", slowLog.DbName) + fmt.Println("slow log hostIp: ", slowLog.HostIp) + // 执行时长,单位:秒 + fmt.Println("slow log queryTime: ", slowLog.QueryTime) + // 加锁时长,单位:秒 + fmt.Println("slow log lockTime: ", slowLog.LockTime) + // 解析行数 + fmt.Println("slow log rowsExamined: ", slowLog.RowsExamined) + // 返回行数 + fmt.Println("slow log rowsSent: ", slowLog.RowsSent) + fmt.Println("slow log sql: ", slowLog.Sql) + // 执行时间 + fmt.Println("slow log executeTime: ", slowLog.ExecuteTime) +} +``` + +# 其他 +## VPC列表 +使用以下代码可以查询vpc列表(仅支持DDC)。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +resp, err := client.ListVpc("ddc") +if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return +} +// 获取vpc列表信息 +for _, e := range* resp { + fmt.Println("ddc vpcId: ", e.VpcId) + fmt.Println("ddc shortId: ", e.ShortId) + fmt.Println("ddc name: ", e.Name) + fmt.Println("ddc cidr: ", e.Cidr) + fmt.Println("ddc status: ", e.Status) + fmt.Println("ddc createTime: ", e.CreateTime) + fmt.Println("ddc description: ", e.Description) + fmt.Println("ddc defaultVpc: ", e.DefaultVpc) + fmt.Println("ddc ipv6Cidr: ", e.Ipv6Cidr) + fmt.Println("ddc auxiliaryCidr: ", e.AuxiliaryCidr) + fmt.Println("ddc relay: ", e.Relay) +} +``` + +## 可用区列表 +使用以下代码可以获取可用区列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" +resp, err := client.GetZoneList("ddc") +if err != nil { + fmt.Printf("get zone list error: %+v\n", err) + return +} +for _, e := range resp.Zones { + fmt.Println("ddc zoneNames: ", e.ZoneNames) + fmt.Println("ddc apiZoneNames: ", e.ApiZoneNames) + fmt.Println("ddc available: ", e.Available) + fmt.Println("ddc defaultSubnetId: ", e.DefaultSubnetId) +} + +// RDS +resp, err = client.GetZoneList("rds") +if err != nil { + fmt.Printf("get zone list error: %+v\n", err) + return +} +for _, e := range resp.Zones { + fmt.Println("rds zoneNames: ", e.ZoneNames) + fmt.Println("rds apiZoneNames: ", e.ApiZoneNames) + fmt.Println("rds available: ", e.Available) + fmt.Println("rds defaultSubnetId: ", e.DefaultSubnetId) +} +``` + +## 子网列表 +使用以下代码可以获取一个实例下的子网列表。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +args := &ddcrds.ListSubnetsArgs{} +resp, err := client.ListSubnets(args, "ddc") +if err != nil { + fmt.Printf("get subnet list error: %+v\n", err) + return +} +for _, e := range resp.Subnets { + fmt.Println("ddc name: ", e.Name) + fmt.Println("ddc longId: ", e.LongId) + fmt.Println("ddc zoneName: ", e.ZoneName) + fmt.Println("ddc shortId: ", e.ShortId) + fmt.Println("ddc vpcId: ", e.VpcId) + fmt.Println("ddc vpcShortId: ", e.VpcShortId) + fmt.Println("ddc az: ", e.Az) + fmt.Println("ddc cidr: ", e.Cidr) + fmt.Println("ddc createdTime: ", e.CreatedTime) + fmt.Println("ddc updatedTime: ", e.UpdatedTime) +} + +// RDS +args = &ddcrds.ListSubnetsArgs{} +resp, err := client.ListSubnets(args, "rds") +if err != nil { + fmt.Printf("get subnet list error: %+v\n", err) + return +} +for _, e := range resp.Subnets { + fmt.Println("rds name: ", e.Name) + fmt.Println("rds longId: ", e.LongId) + fmt.Println("rds zoneName: ", e.ZoneName) + fmt.Println("rds shortId: ", e.ShortId) + fmt.Println("rds vpcId: ", e.VpcId) + fmt.Println("rds vpcShortId: ", e.VpcShortId) + fmt.Println("rds az: ", e.Az) + fmt.Println("rds cidr: ", e.Cidr) + fmt.Println("rds createdTime: ", e.CreatedTime) + fmt.Println("rds updatedTime: ", e.UpdatedTime) +} +``` + +## 实例版本回滚 +使用以下代码可以回滚实例版本。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.InstanceVersionRollBackArg{ + // 是否维护时间窗口执行 + WaitSwitch: true, +} +// DDC +result, err := client.InstanceVersionRollBack(instanceId, args) +if err != nil { + fmt.Printf("rollback instance version faild: %+v\n", err) + return +} +fmt.Printf("rollback instance version success. taskId:%s\n", result.TaskID) +``` + + +## 实例版本升级 +使用以下代码可以升级实例版本。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.InstanceVersionUpgradeArg{ + // 是否立即升级 + IsUpgradeNow: false, +} +// DDC +result, err := client.InstanceVersionUpgrade(instanceId, args) +if err != nil { + fmt.Printf("upgrade instance version faild: %+v\n", err) + return +} +fmt.Printf("upgrade instance version success. taskId:%s\n", result.TaskID) +``` + +## 获取只读实例的主从同步延迟 +使用以下代码可以获取只读实例的主从同步延迟。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +// DDC +result, err := client.GetInstanceSyncDelay(instanceId) +if err != nil { +fmt.Printf("get readonly instance syncDelay and syncStatus faild: %+v\n", err) + return +} +fmt.Println("get readonly instance syncDelay and syncStatus success.") +if result.Success { +fmt.Println("instance is SyncDelay: ", result.Result.SyncDelay) +fmt.Println("instance is SyncStatus: ", result.Result.SyncStatus) +} +``` + +## 开关只读实例主从同步延迟 +使用以下代码可以开关只读实例主从同步延迟。 +```go +// import ddcrds "github.com/baidubce/bce-sdk-go/services/ddc/v2" + +args := &ddcrds.InstanceSyncDelayReplicationArg{ + // 开启只读实例主从同步延迟,开启start,关闭stop + Action: "start", +} +// DDC +result, err := client.InstanceSyncDelayReplication(instanceId, args) +if err != nil { +fmt.Printf("instance syncDelay replication faild: %+v\n", err) +return +} +fmt.Printf("instance syncDelay replication success. success:%s\n", result.Success) +``` + + +# 错误处理 + +GO语言以error类型标识错误,DDC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | DDC服务返回的错误 + +用户使用SDK调用DDC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// ddcClient 为已创建的DDC Client对象 +result, err := client.ListDdcInstance() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向DDC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当DDC服务端出现异常时,DDC服务端会返回给用户相应的错误信息,以便定位问题。 + +## SDK日志 + +DDC GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +DDC GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the DDC go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the DDC go sdk") +``` + +首次发布: + +- 支持创建账号、更新账号密码、更新账号备注、更新账号权限、查询账号列表、查询特定账号信息、删除特定账号信息 +- 支持创建数据库、更新数据库备注、查询数据库列表、查询特定数据库信息、删除特定数据库信息 +- 兼容RDS SDK中现有功能 \ No newline at end of file diff --git a/bce-sdk-go/doc/DNS.md b/bce-sdk-go/doc/DNS.md new file mode 100644 index 0000000..c42b891 --- /dev/null +++ b/bce-sdk-go/doc/DNS.md @@ -0,0 +1,463 @@ +# 公网DNS服务 + +# 概述 + +本文档主要介绍公网DNS GO SDK的使用。在使用本文档前,您需要先了解公网DNS的一些基本知识,并已开通了公网DNS服务。若您还不了解公网DNS,可以参考[产品描述](https://cloud.baidu.com/doc/DNS/s/Ajwvywvx3 )和[操作指南](https://cloud.baidu.com/doc/DNS/s/yjxkakdj4) 。 + +# 初始化 + +## 确认Endpoint + +内网DNS API 的服务域名为:dns.baidubce.com + +API支持HTTP和HTTPS两种调用方式。为了提升数据的安全性,建议通过HTTPS调用。 + + +## 获取密钥 + +要使用百度云公网DNS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问DNS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建DNS Client + +DNS Client是公网DNS服务的客户端,为开发者与公网DNS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建DNS Client + +通过AK/SK方式访问DNS,用户可以参考如下代码新建一个DNS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/dns" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个DNSClient + DNSClient, err := DNS.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为公网DNS的服务地址。 + +### 使用STS创建DNS Client + +**申请STS token** + +DNS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问DNS,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建DNS Client** + +申请好STS后,可将STS Token配置到DNS Client中,从而实现通过STS Token创建DNS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建DNS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/dns" //导入DNS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建DNS服务的Client对象,Endpoint使用默认值 + DNSClient, err := DNS.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "dns.baidubce.com") + if err != nil { + fmt.Println("create dns client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + DNSClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置DNS Client时,STS的Endpoint需配置为http://sts.bj.baidubce.com。 + +# 配置HTTPS协议访问DNS + +DNS支持HTTPS传输协议,您可以通过在创建DNS Client对象时指定的Endpoint中指明HTTPS的方式,在DNS GO SDK中使用HTTPS访问DNS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/dns" + +ENDPOINT := "https://dns.baidubce.com " //指明使用HTTPS协议 +AK, SK := , +DNSClient, _ := DNS.NewClient(AK, SK, ENDPOINT) +``` + +## 配置DNS Client + +如果用户需要配置DNS Client的一些细节的参数,可以在创建DNS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问DNS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/dns" + +//创建DNS Client对象 +AK, SK := , +ENDPOINT := "dns.baidubce.com" +client, _ := DNS.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/dns" + +AK, SK := , +ENDPOINT := "dns.baidubce.com" +client, _ := DNS.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/dns" + +AK, SK := , +ENDPOINT := "dns.baidubce.com" +client, _ := DNS.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问DNS时,创建的DNS Client对象的`Config`字段支持的所有参数如下表所示: + +| 配置项名称 | 类型 | 含义 | +|---------------------------|-----------------------|-------------------------| +| Endpoint | string | 请求服务的域名 | +| ProxyUrl | string | 客户端请求的代理地址 | +| Region | string | 请求资源的区域 | +| UserAgent | string | 用户名称,HTTP请求的User-Agent头 | +| Credentials | \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 | +| SignOption | \*auth.SignOptions | 认证字符串签名选项 | +| Retry | RetryPolicy | 连接重试策略 | +| ConnectionTimeoutInMillis | int | 连接超时时间,单位毫秒,默认20分钟 | + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建DNS Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +| 名称 | 类型 | 含义 | +|---------------|---------------------|-----------------------------| +| HeadersToSign | map[string]struct{} | 生成签名字符串时使用的HTTP头 | +| Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 | +| ExpireSeconds | int | 签名字符串的有效期 | + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 添加域名 + +```go +args := &CreateZoneRequest{ + Name: "sdkDNS.com", +} +err := DNSClient.CreateZone(args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询域名列表 + +```go +args := &ListZoneRequest{ + Marker: "123", +} +result, err := DNSClient.ListZone(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 删除域名 + +```go +err := DNSClient.DeleteZone("sdkDNS.com", "") +ExpectEqual(t.Errorf, nil, err) +``` + + +## 购买付费版域名 + +```go +args := &CreatePaidZoneRequest{ + Name: []string{"sdkDNS.com"}, + ProductVersion: "discount", + Billing: Billing{ + PaymentTiming: "Prepaid", + Reservation: Reservation{ + ReservationLength: 1, + }, + }, +} +err := DNSClient.CreatePaidZone(args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 免费版域名升级成普惠版 + +```go +args := &UpgradeZoneRequest{ + Name: []string{"sdkDNS.com"}, + Billing: Billing{ + PaymentTiming: "Prepaid", + Reservation: Reservation{ + ReservationLength: 1, + }, + }, +} +err := DNSClient.UpgradeZone(args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 域名续费 + +```go +args := &RenewZoneRequest{ + Billing: Billing{ + PaymentTiming: "Prepaid", + Reservation: Reservation{ + ReservationLength: 1, + }, + }, +} +err := DNSClient.RenewZone("sdkDNS.com", args, "") +ExpectEqual(t.Errorf, nil, err) +``` + + + +## 添加解析记录 + +```go +args := &CreateRecordRequest{ + Rr: "www", + Type: "A", + Value: "192.168.1.1", + } +err := DNSClient.CreateRecord("sdkDNS.com", args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询解析记录列表 + +```go +args := &ListRecordRequest{} +result, err := DNSClient.ListRecord("sdkDNS.com", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 修改解析记录 + +```go +args := &UpdateRecordRequest{ + Rr: "www", + Type: "A", + Value: "192.168.1.2", +} +err := DNSClient.UpdateRecord("sdkDNS.com", "1234", args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 开启解析记录 + +```go +err := DNSClient.UpdateRecordEnable("sdkDNS.com", "1234", "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 暂停解析记录 + +```go +err := DNSClient.UpdateRecordDisable("sdkDNS.com", "1234", "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 删除解析记录 + +```go +err := DNSClient.DeleteRecord("sdkDNS.com", "123", "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 添加线路组 + +```go +args := &AddLineGroupRequest{ + Name: "lineGroupName", + Lines: []string{"yunnan.ct"}, +} +err := DNSClient.AddLineGroup(args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 更新线路组 + +```go +args := &UpdateLineGroupRequest{ + Name: "lineGroupName", + Lines: []string{"yunnan.ct"}, +} +err := DNSClient.UpdateLineGroup("lineId", args, "") +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询线路组列表 + +```go +args := &ListLineGroupRequest{ + Marker: "123", +} +result, err := DNSClient.ListLineGroup(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 删除线路组 + +```go +err := DNSClient.DeleteLineGroup("lineId", "") +ExpectEqual(t.Errorf, nil, err) +``` + + + +# 错误处理 + +GO语言以error类型标识错误,DNS支持两种错误见下表: + +| 错误类型 | 说明 | +|-----------------|------------| +| BceClientError | 用户操作产生的错误 | +| BceServiceError | DNS服务返回的错误 | + +用户使用SDK调用DNS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + + +## 客户端异常 + +客户端异常表示客户端尝试向DNS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当DNS服务端出现异常时,DNS服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[DNS错误码](https://cloud.baidu.com/doc/DNS/s/lkk5elv58) + +## SDK日志 + +DNS GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +DNS GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the DNS go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the DNS go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/DOC.md b/bce-sdk-go/doc/DOC.md new file mode 100644 index 0000000..932d91e --- /dev/null +++ b/bce-sdk-go/doc/DOC.md @@ -0,0 +1,205 @@ +# DOC 服务 + +# 概述 + +本文档主要介绍 DOC GO SDK 的使用。在使用本文档前,您需要先了解 DOC 的一些基本知识,并已开通了 DOC 服务。若您还不了解 DOC,可以参考[产品描述](https://cloud.baidu.com/doc/DOC/s/Djwvypqoi)和 [API 参考](https://cloud.baidu.com/doc/DOC/s/Cjwvypy6e)。 + +# 初始化 + +## 确认Endpoint + +DOC 为全局服务,服务域名是 `doc.bj.baidubce.com`。 DOC API 支持 HTTP 和 HTTPS 两种协议。为了提升数据的安全性,建议使用HTTPS协议。SDK 默认使用 HTTPS 协议。 + +## 获取密钥 + +要使用百度云 DOC,您需要拥有一个有效的 AK(Access Key ID) 和 SK(Secret Access Key) 用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问 DOC 做签名验证。 + +可以通过如下步骤获得并了解您的 AK/SK 信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建DOC Client + +DOC Client 是 DOC 服务的客户端,为开发者与 DOC 服务进行交互提供了一系列的方法。 + +### 使用 AK/SK 新建 DOC Client + +通过 AK/SK 方式访问 DOC,用户可以参考如下代码新建一个 DOC Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/doc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 初始化一个DocClient + docClient, err := doc.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《[如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb)》。 + +## 配置 DOC Client + +如果用户需要配置 DOC Client 的一些细节的参数,可以在创建 DOC Client 对象之后,使用该对象的导出字段 `Config` 进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问 DOC 服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/doc" + +//创建 DOC Client对象 +AK, SK := , +client, _ := doc.NewClient(AK, SK) + +//代理使用本地的 8080 端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/doc" + +AK, SK := , +client, _ := doc.NewClient(AK, SK) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/doc" + +AK, SK := , +client, _ := doc.NewClient(AK, SK) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用 GO SDK 访问 DOC 时,创建的 DOC Client 对象的 `Config` 字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials` 字段使用 `auth.NewBceCredentials` 与 `auth.NewSessionBceCredentials` 函数创建,默认使用前者。 + 2. `SignOption` 字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry` 字段指定重试策略,目前支持两种:`NoRetryPolicy` 和 `BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 文档服务 +文档接口流程如下 +![百度云文档接口](https://doc.bce.baidu.com/bce-documentation/DOC/wendangjiekou_1.png) + +## 注册文档 +注册文档接口用于生成文档的唯一标识documentId、用于存储源文档文件的 BOS Bucket 相关信息。注册成功后,对应文档状态为 `UPLOADING`,对应 Bucket 对用户开放写权限,对于用户的 BOS 空间不可见。 + +注册文档是文档三步创建法(注册文档、上传BOS、发布文档)的第一步。 + +如下代码可以注册一个文档: + +```go +regParam := &api.RegDocumentParam{ + Title: , + Format: , +} + +if res, err := docClient.RegisterDocument(regParam); err != nil { + fmt.Println("failed to register document:", err) +} else { + fmt.Println("register document success, id:", res.DocumentId) +} +``` + +## 发布文档 +用于对已完成注册和 BOS 上传的文档进行发布处理。仅对状态为 `UPLOADING` 的文档有效。处理过程中,文档状态为 `PROCESSING`;处理完成后,状态转为 `PUBLISHED`。 + +发布文档是文档三步创建法(注册文档、上传BOS、发布文档)的第三步。 + +```go +err = docClient.PublishDocument() +``` + +## 查询文档 +通过文档的唯一标识 documentId 查询指定文档的详细信息。 + +```go +qRes, err := docClient.QueryDocument(, &api.QueryDocumentParam{Https: false}) +``` + +## 文档列表 +查询所有文档,以列表形式返回,支持用文档状态作为筛选条件进行筛选。 + +```go +listParam := &api.ListDocumentsParam{ + Status: api.DOC_STATUS_PUBLISHED, + MaxSize: 2, + } +res, err := docClient.ListDocuments(listParam) +``` + +## 阅读文档 +通过文档的唯一标识 documentId 获取指定文档的阅读信息,以便在 PC/Android/iOS 设备上阅读。仅对状态为 `PUBLISHED` 的文档有效。 +```go +rRes, err := docClient.ReadDocument(, &api.ReadDocumentParam{ExpireInSeconds: 3600}) +``` + +## 查询文档转码结果图片列表 +对于转码结果类型为图片的文档,通过本接口可以在文档转码完成后,获取转码结果图片的URL列表。 + +```go +if res, err := docClient.GetImages(); err != nil { + fmt.Println("failed to get images list:", err) +} else { + fmt.Println("get images list success, images count:", len(res.Images)) +} +``` + +## 删除文档 +删除文档,仅对状态 status 不是 `PROCESSING` 时的文档有效,清除文档占用的存储空间。 + +```go +err = docClient.DeleteDocument() +``` + +> **注意:** +> 文档一经删除,无法通过查询文档/文档列表等接口获取,并且无法阅读、下载,请谨慎操作。 \ No newline at end of file diff --git a/bce-sdk-go/doc/DTS.md b/bce-sdk-go/doc/DTS.md new file mode 100644 index 0000000..b70d49b --- /dev/null +++ b/bce-sdk-go/doc/DTS.md @@ -0,0 +1,684 @@ +# DTS服务 + +# 概述 + +本文档主要介绍DTS GO SDK的使用。在使用本文档前,您需要先了解DTS的一些基本知识,并已开通了DTS服务。若您还不了解DTS,可以参考[产品描述](https://cloud.baidu.com/doc/DTS/s/ujwvyzdzg)和[操作指南](https://cloud.baidu.com/doc/DTS/s/Qjwvz0ikk)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +DTS 是全局产品,不需要区分多地域,仅有一个 Endpoint。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +所有区域 | dts.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云DTS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问DTS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建DTS Client + +DTS Client是DTS服务的客户端,为开发者与DTS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建DTS Client + +通过AK/SK方式访问DTS,用户可以参考如下代码新建一个DTS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/dts" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个DTSClient + dtsClient, err := dts.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。 +第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + + +### 使用STS创建DTS Client + +**申请STS token** + +DTS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问DTS,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建DTS Client** + +申请好STS后,可将STS Token配置到DTS Client中,从而实现通过STS Token创建DTS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建DTS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/dts" //导入DTS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建DTS服务的Client对象,Endpoint使用默认值 + dtsClient, err := dts.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "dts.baidubce.com") + if err != nil { + fmt.Println("create dts client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + dtsClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置DTS Client时,无论对应DTS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问DTS + +DTS支持HTTPS传输协议,您可以通过在创建DTS Client对象时指定的Endpoint中指明HTTPS的方式,在DTS GO SDK中使用HTTPS访问DTS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +ENDPOINT := "https://dts.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +dtsClient, _ := dts.NewClient(AK, SK, ENDPOINT) +``` + +## 配置DTS Client + +如果用户需要配置DTS Client的一些细节的参数,可以在创建DTS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问DTS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +//创建DTS Client对象 +AK, SK := , +ENDPOINT := "dts.baidubce.com" +client, _ := dts.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +AK, SK := , +ENDPOINT := "dts.baidubce.com" +client, _ := dts.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +AK, SK := , +ENDPOINT := "dts.baidubce.com" +client, _ := dts.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问DTS时,创建的DTS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建DTS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# DTS管理 + +DTS(Data Transmission Service)提供数据迁移、数据同步、数据订阅于一体的数据库数据传输服务,帮助您在业务不停服的前提下轻松完成数据库迁移,利用实时同步通道轻松构建异地容灾的高可用数据库架构。 + +## 创建DTS任务 + +使用以下代码可以创建一个DTS任务 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +args := &dts.CreateDtsArgs{ + // 幂等性Token,是一个长度不超过64位的ASCII字符串,选填参数(关于幂等性,可以参考下面专门介绍幂等性的章节内容) + ClientToken: "aff0ea1548d30a5c711382b0cca7b45faff0ea1548d30a5c711382b0cca7b45f", + // 付费类型(后付费:postpay;),目前仅支持后付费 + ProductType: "postpay", + // 任务类型(数据传输任务:migration;),目前仅支持数据传输任务 + Type: "migration", + // 链路规格,取值:Samll、Medium、Large、Xlarge + Standard: "Large", + // 源端类型(百度智能云数据库:bcerds;自建数据存储:public;) + SourceInstanceType: "bcerds", + // 目标端类型(百度智能云数据库:bcerds;自建数据存储:public;) + TargetInstanceType: "bcerds", + // 跨地域标识(当源端、目标端类型均为百度智能云数据库且跨地域时:1;其他情况:0) + CrossRegionTag: 1, + // 同步方向(单向同步:single;双向同步:bidirect),目前仅支持单向同步 + DirectionType: "single", +} +result, err := client.CreateDts(args) +if err != nil { + fmt.Printf("create dts error: %+v\n", err) + return +} + +for _, e := range result.DtsTasks { + fmt.Println("create dts success, task id: ", e.DtsId) +} +``` + +## 删除DTS任务 + +使用以下代码可以删除一个DTS任务 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +err := client.DeleteDts(dtsId) +if err != nil { + fmt.Printf("delete dts error: %+v\n", err) + return +} + +fmt.Println("delete dts success\n") +``` + +## 查看DTS任务详情 + +使用以下代码可以查看一个DTS任务详情 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +result, err := client.GetDetail(dtsId) +if err != nil { + fmt.Printf("get dts detail error: %+v\n", err) + return +} + +fmt.Println("dts taskName: ",result.TaskName) +fmt.Println("dts status: ",result.Status) +fmt.Println("dts region: ",result.Region) +fmt.Println("dts createTime: ",result.CreateTime) +// 若 result.DtsIdPos 为空字符串,则表示该任务是单向同步任务,否则为双向同步任务 +if result.DtsIdPos != "" { + // 正向数据流 ID + fmt.Println("dts dtsIdPos: ", result.DtsIdPos) + // 反向数据流 ID + fmt.Println("dts dtsIdNeg: ", result.DtsIdNeg) + // 正向数据流状态 + fmt.Println("dts dtsTaskPos status: ", result.DtsTaskPos.Status) + // 反向数据流状态 + fmt.Println("dts dtsTaskNeg status: ", result.DtsTaskNeg.Status) +} +``` + +## 查询DTS任务列表 + +使用以下代码可以查看DTS任务列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +args := &dts.ListDtsArgs{ + // 任务类型(单向同步类型:migration;双向同步类型:bidirect) + Type: "migration", + // 分页参数,初次请求无需设置,后续请求使用上次请求响应中的nextMarker + Marker: "dtsmb0p9j8hcb7as36gx", + // 分页参数,每页数据条数,默认为 10 + MaxKeys: 10, +} +result, err := client.ListDts(args) +if err != nil { + fmt.Printf("get dts list error: %+v\n", err) + return +} +// 是否截断(true:截断,表示还有下一页数据;false:最后一页数据;) +fmt.Println("isTruncated: ", result.IsTruncated) +// 分页参数,下一页标记 +fmt.Println("nextMarker: ", result.NextMarker) +for _, e := range result.Task { + fmt.Println("dtsId: ", e.DtsId) + fmt.Println("taskName: ", e.TaskName) + fmt.Println("status: ", e.Status) +} +``` + +## 分页查询DTS任务列表 + +使用以下代码可以查看DTS任务列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +args := &dts.ListDtsWithPageArgs{ + // 任务类型数组(单向同步类型:migration;双向同步类型:bidirect) + Types: []string{"migration"}, + // 过滤条件数组 + Filters: []dts.ListFilter{ + { + // 搜索关键字,支持前缀模糊匹配 + Keyword: "he", + // 搜索关键字类型,取值:dtsId、taskName、status、srcConnection.dbType、dtsConnection.dbType + KeywordType: "taskName", + }, + }, + // 分页页码,从 1 开始 + PageNo: 1, + // 分页大小,最大值 100 + PageSize: 10, + // 排序方式,取值:asc(升序)、desc(降序) + Order: "desc", + // 排序字段,取值:dtsId、taskName、createTime + OrderBy: "createTime", +} +result, err := client.ListDtsWithPage(args) +if err != nil { + fmt.Printf("get dts list with page error: %+v\n", err) + return +} + +for _, e := range result.Result { + fmt.Println("dtsId: ", e.DtsId) + fmt.Println("taskName: ", e.TaskName) + fmt.Println("status: ", e.Status) +} +``` + +## 配置DTS任务 + +使用以下代码可以配置一个DTS任务 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +dataType :=[]string{"schema","base"} +srcConnection := dts.Connection{ + Region: "public", + DbType: "mysql", + DbUser: "usrname", + DbPass: "password", + DbPort: 3306, + DbHost: "180.76.120.207", + InstanceId: "rds-TOzVOznv", + InstanceType: "public", +} +dstConnection := dts.Connection{ + Region: "public", + DbType: "mysql", + DbUser: "usrname", + DbPass: "password", + DbPort: 3306, + DbHost: "180.76.120.207", + InstanceId: "rds-TOzVOznv", + InstanceType: "public", +} +schema := dts.Schema{ + Type: "db", + Src: "db1", + Dst: "db2", + Where: "", +} +schemaMapping := []dts.Schema{schema} +args := &dts.ConfigArgs{ + TaskName: "test", + DataType: dataType, + Type: "migration", + SrcConnection: srcConnection, + DstConnection: dstConnection, + SchemaMapping: schemaMapping, +} +result, err := client.ConfigDts("dtsmro61533558", args) +if err != nil { + fmt.Printf("config dts error: %+v\n", err) + return +} + +fmt.Println("config dts success, dtsId: ", result.DtsId) +``` + +## 前置检查 + +使用以下代码可以对一个DTS任务前置检查 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +result, err := client.PreCheck(taskId) +if err != nil { + fmt.Printf("preCheck dts error: %+v\n", err) + return +} + +fmt.Println("result success: ",result.Success) +``` + +## 查看前置检查结果 + +使用以下代码可以查看前置检查结果 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +result, err := client.GetPreCheck(taskId) +if err != nil { + fmt.Printf("get dts preCheck result error: %+v\n", err) + return +} + +fmt.Println("result success: ", result.Success) +for _, e := range result.Result { + fmt.Println("name: ", e.Name, "status: ", e.Status, "Message: ", e.Message, "Subscription: ", e.Subscription) +} +``` + +## 强制通过预检查(即前置检查) + +使用以下代码可以尝试强制通过一个DTS任务预检查,根据响应结果可以检查强制通过预检查操作是否成功 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +response, err := client.SkipPreCheck(taskId) +if err != nil { + fmt.Printf("skip preCheck dts error: %+v\n", err) + return +} + +// 若 success 为 true,表示强制通过预检查操作成功;否则,表示强制通过预检查操作失败; +fmt.Println("response success: ",response.Success) +// 强制通过预检查操作失败时失败原因 +fmt.Println("response result: ",response.Result) +``` + +## 启动DTS任务 + +使用以下代码可以启动一个DTS任务 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +err := client.StartDts(taskId) +if err != nil { + fmt.Printf("start dts error: %+v\n", err) + return +} + +fmt.Println("start dts success\n") +``` + +## 暂停DTS任务 + +使用以下代码可以暂停一个DTS任务 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +err := client.PauseDts(taskId) +if err != nil { + fmt.Printf("pause dts error: %+v\n", err) + return +} + +fmt.Println("pause dts success\n") +``` + +## 结束DTS任务 + +使用以下代码可以结束一个DTS任务 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +err := client.ShutdownDts(taskId) +if err != nil { + fmt.Printf("shut down dts error: %+v\n", err) + return +} + +fmt.Println("shutdown dts success\n") +``` + +## 更新任务名称 + +使用以下代码可以更新任务名称 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +args := &dts.UpdateTaskNameArgs { + TaskName: "go-sdkkk", +} +err := client.UpdateTaskName(taskId, args) +if err != nil { + fmt.Printf("update task name error: %+v\n", err) + return +} + +fmt.Println("update task name success\n") +``` + +## 变更链路规格 + +使用以下代码可以变更链路规格 +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +args := &dts.ResizeTaskStandardArgs { + // 幂等性Token,是一个长度不超过64位的ASCII字符串,选填参数(关于幂等性,可以参考下面专门介绍幂等性的章节内容) + ClientToken: "aff0ea1548d30a5c711382b0cca7b45faff0ea1548d30a5c711382b0cca7b45f", + // 链路规格,取值:Samll、Medium、Large、Xlarge + Standard: "Xlarge", +} +response, err := client.ResizeTaskStandard(taskId, args) +if err != nil { + fmt.Printf("resize task standard error: %+v\n", err) + return +} + +fmt.Println("response orderId: ", response.OrderId) +``` + +## 查询数据库Schema + +使用以下代码可以查询数据库Schema +```go +// import "github.com/baidubce/bce-sdk-go/services/dts" + +args := &dts.GetSchemaArgs { + Connection: dts.Connection{ + InstanceType: "bcerds", + DbType: "mysql", + InstanceId: "rdsm97xpxxxxu", + Region: "bj", + FieldWhitelist: "", + FieldBlacklist: "", + }, +} +response, err := client.GetSchema(args) +if err != nil { + fmt.Printf("get schema error: %+v\n", err) + return +} +fmt.Println("response success: ", response.Success) +fmt.Println("response result: ", response.Result) +``` + +# 错误处理 + +GO语言以error类型标识错误,DTS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | DTS服务返回的错误 + +用户使用SDK调用DTS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// dtsClient 为已创建的DTS Client对象 +result, err := client.ListDts() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向DTS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当DTS服务端出现异常时,DTS服务端会返回给用户相应的错误信息,以便定位问题。 + +## SDK日志 + +DTS GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +DTS GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the DTS go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the DTS go sdk") +``` + +# 幂等性 + +## 幂等性概述 +Go SDK 在调用API时,很容易出现由于网络等问题导致客户端没收到响应连接就中断的情况。此时客户端无法得知服务器端是否收到了请求,重试又可能导致问题。例如一个创建实例的请求被多次发送就可能出现重复创建。对此,加入幂等性的机制来加以应对。 + +幂等性的意思是无论同一个请求被重复发送多次,其结果都和发送一次一样。 + +Go SDK 采用clientToken机制来保证API调用的幂等性,clientToken 是一个长度不超过64位的ASCII字符串,通常放在创建、删除类操作的参数中。 + + + +首次发布: + + - 支持创建DTS任务、删除DTS任务、配置DTS任务、查看DTS任务详情、查看DTS任务列表、前置检查、查看前置检查结果、启动DTS任务、暂停DTS任务、结束DTS任务 \ No newline at end of file diff --git a/bce-sdk-go/doc/ECCR.md b/bce-sdk-go/doc/ECCR.md new file mode 100644 index 0000000..8d00960 --- /dev/null +++ b/bce-sdk-go/doc/ECCR.md @@ -0,0 +1,282 @@ +# CCR服务 企业版 + +# 概述 + +本文档主要介绍CCR企业版 GO SDK的使用。在使用本文档前,您需要先了解CCR的一些基本知识,并已开通了CCR服务。若您还不了解CCR,可以参考[产品描述](https://cloud.baidu.com/doc/CCR/s/qk8gwqs4a)和[操作指南](https://cloud.baidu.com/doc/CCR/s/skw63yms7)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[CCR服务域名](https://cloud.baidu.com/doc/CCR/s/Fjwvy1fl4)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/CCR/s/Fjwvy1fl4)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|----------------------|--- +BJ | ccr.bj.baidubce.com | HTTP and HTTPS +GZ | ccr.gz.baidubce.com | HTTP and HTTPS +SU | ccr.su.baidubce.com | HTTP and HTTPS +HKG| ccr.hkg.baidubce.com | HTTP and HTTPS +FWH| ccr.fwh.baidubce.com | HTTP and HTTPS +BD | ccr.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云CCR,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问CCR做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建CCR Client + +CCR企业版 Client是CCR服务的客户端,为开发者与CCR服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建CCR Client + +通过AK/SK方式访问CCR,用户可以参考如下代码新建一个CCR Client: +```go +import ( + "github.com/baidubce/bce-sdk-go/services/eccr" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + AK, SK := , + + //用户指定的endpoint + ENDPOINT := "endpoint" + + // 初始化一个CCRClient + ccrClient, err := eccr.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`AK`对应控制台中的“Access Key ID”,`SK`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为CCR的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`ccr.bj.baidubce.com`。 + +### 使用STS创建CCR Client + +**申请STS token** + +CCR可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问CCR,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建CCR Client** + +申请好STS后,可将STS Token配置到CCR Client中,从而实现通过STS Token创建CCR Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建CCR Client对象: +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/eccr" //导入CCR服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建CCR服务的Client对象,Endpoint使用默认值 + ccrClient, err := eccr.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "ccr.bj.baidubce.com") + if err != nil { + fmt.Println("create ccr client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + ccrClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置CCR Client时,无论对应CCR服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问CCR + +CCR支持HTTPS传输协议,您可以通过在创建CCR Client对象时指定的Endpoint中指明HTTPS的方式,在CCR GO SDK中使用HTTPS访问CCR企业版服务: +```go +// import "github.com/baidubce/bce-sdk-go/services/ccr" +AK, SK := , +ENDPOINT := "https://ccr.bj.baidubce.com" //指明使用HTTPS协议 + +ccrClient, _ := eccr.NewClient(AK, SK, ENDPOINT) +``` + +## 配置CCR Client + +如果用户需要配置CCR Client的一些细节的参数,可以在创建CCR Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问CCR服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/ccr" + +//创建CCR Client对象 +AK, SK := , +ENDPOINT := "ccr.bj.baidubce.com" + +ccrClient, _ := eccr.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +ccrClient.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/ccr" + +AK, SK := , +ENDPOINT := "ccr.bj.baidubce.com" + +ccrClient, _ := eccr.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +ccrClient.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +ccrClient.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/ccr" + +AK, SK := , +ENDPOINT := "ccr.bj.baidubce.com" + +ccrClient, _ := eccr.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +ccrClient.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +ccrClient.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问CCR时,创建的CCR Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建CCR Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# CCR管理 + +百度智能云容器镜像服务(Cloud Container Registry,简称CCR)是面向容器镜像、Helm Chart等符合OCI规范的云原生制品安全托管以及高效分发平台。CCR支持在多个地域创建独享托管服务,具备多种安全保障;支持同步容器镜像等云原生制品,与容器引擎CCE等服务无缝集成,助力企业提升云原生容器应用交付效率。 + +> 注意: +> - 企业版实例托管的云原生应用制品(如容器镜像、Helm Chart)存储在您的 BOS Bucket 中,根据实际使用情况将产生存储和流量费用。 + +## 列举CCR实例 +使用以下代码可以列举CCR实例列表。 +```go +args := &ListInstancesArgs{ + KeywordType: "clusterName", + Keyword: "", + PageNo: 1, + PageSize: 10, + } + +resp, err := ccrClient.ListInstances(args) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:"+ string(s)) +``` + +## 查询单个CCR实例详情 +列举CCR实例列表。 +```go +instanceID := "instance-id" +resp, err := ccrClient.GetInstanceDetail(instanceID) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` + +## 获取私有网络列表 +查询私有网络列表。 +```go +instanceID := "instance-id" +resp, err := ccrClient.ListPrivateNetworks(instanceID) +if err != nil { + fmt.Println(err.Error()) + return +} + +s, _ := json.MarshalIndent(resp, "", "\t") +fmt.Println("Response:" + string(s)) +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/EIP.md b/bce-sdk-go/doc/EIP.md new file mode 100644 index 0000000..e03607d --- /dev/null +++ b/bce-sdk-go/doc/EIP.md @@ -0,0 +1,579 @@ +# EIP服务 + +# 概述 + +本文档主要介绍EIP GO SDK的使用。在使用本文档前,您需要先了解EIP的一些基本知识,并已开通了EIP服务。若您还不了解EIP,可以参考[产品描述](https://cloud.baidu.com/doc/EIP/s/fjwvz2pyz)和[操作指南](https://cloud.baidu.com/doc/EIP/s/Sjwvz2scd)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[EIP服务域名](https://cloud.baidu.com/doc/EIP/s/Djwvz32x7)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | eip.bj.baidubce.com | HTTP and HTTPS +GZ | eip.gz.baidubce.com | HTTP and HTTPS +SU | eip.su.baidubce.com | HTTP and HTTPS +HKG| eip.hkg.baidubce.com| HTTP and HTTPS +FWH| eip.fwh.baidubce.com| HTTP and HTTPS +BD | eip.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云EIP,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问EIP做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建EIP Client + +EIP Client是EIP服务的客户端,为开发者与EIP服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建EIP Client + +通过AK/SK方式访问EIP,用户可以参考如下代码新建一个EIP Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/eip" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个EIPClient + eipClient, err := eip.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为EIP的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`eip.bj.baidubce.com`。 + +### 使用STS创建EIP Client + +**申请STS token** + +EIP可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问EIP,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建EIP Client** + +申请好STS后,可将STS Token配置到EIP Client中,从而实现通过STS Token创建EIP Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建EIP Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/eip" //导入EIP服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建EIP服务的Client对象,Endpoint使用默认值 + eipClient, err := eip.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "eip.bj.baidubce.com") + if err != nil { + fmt.Println("create eip client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + eipClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置EIP Client时,无论对应EIP服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问EIP + +EIP支持HTTPS传输协议,您可以通过在创建EIP Client对象时指定的Endpoint中指明HTTPS的方式,在EIP GO SDK中使用HTTPS访问EIP服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +ENDPOINT := "https://eip.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +eipClient, _ := eip.NewClient(AK, SK, ENDPOINT) +``` + +## 配置EIP Client + +如果用户需要配置EIP Client的一些细节的参数,可以在创建EIP Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问EIP服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +//创建EIP Client对象 +AK, SK := , +ENDPOINT := "eip.bj.baidubce.com" +client, _ := eip.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +AK, SK := , +ENDPOINT := "eip.bj.baidubce.com" +client, _ := eip.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +AK, SK := , +ENDPOINT := "eip.bj.baidubce.com" +client, _ := eip.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问EIP时,创建的EIP Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建EIP Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# EIP管理 + +弹性公网IP EIP (Elastic IP) 作为一个独立的商品为用户提供公网带宽服务。 + +EIP的主要用途包括: + +- 通过EIP实例,用户可以获取公网带宽服务。 +- 用户可灵活配置EIP实例的计费模式,包括按需按带宽付费、按需按流量付费和包年包月按带宽付费三种。 +- 用户可将EIP实例与任意BCC或BLB实例绑定或解绑,匹配用户的不同业务场景。 + +> 注意: +> - 申请的EIP可用于绑定到任意BLB实例或BCC实例。 +> - 创建EIP需要实名认证,若未通过实名认证可以前往[百度智能云官网控制台](https://console.bce.baidu.com/qualify/#/qualify/result)中的安全认证下的实名认证中进行认证。 + +## 申请EIP + +使用以下代码可以申请一个EIP。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +args := &eip.CreateEipArgs{ + // 指定eip的名称 + Name: "sdk-eip", + // 指定eip的公网带宽 + BandWidthInMbps: 10, + // 指定eip的付费信息 + Billing: &eip.Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByTraffic", + }, + // 预付费资源可以设置是否自动续费 + AutoRenewTimeUnit: "month", + AutoRenewTime: 1, + // 指定eip的标签键值对列表 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +result, err := client.CreateEip(args) +if err != nil { + fmt.Printf("create eip error: %+v\n", err) + return +} + +fmt.Println("create eip success, eip: ", result.Eip) +``` + +> 注意: +> - 公网带宽,单位为Mbps。对于prepay以及bandwidth类型的EIP,限制为为1~200之间的整数,对于traffic类型的EIP,限制为1~1000之前的整数。 +> - EIP的名称要求长度1~65个字节,字母开头,可包含字母数字-_/.字符。若不传该参数,服务会自动生成name。 + +## EIP带宽扩缩容 + +使用以下代码可以对指定EIP的带宽进行扩缩容操作。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +args := &eip.ResizeEipArgs{ + // 指定eip的最新公网带宽 + NewBandWidthInMbps: 20, +} +err = client.ResizeEip(eip, args) +if err != nil { + fmt.Printf("resize eip error: %+v\n", err) + return +} + +fmt.Println("resize eip success.") +``` + +> 注意: +> - 扩缩容是一个异步过程,可以通过查询EIP列表查看EIP扩缩容状态是否完成 +> - 变更后的公网带宽,单位为Mbps。对于预付费(prepay)以及按带宽(bandwidth)类型的EIP,限制为1~200之间的整数,对于按流量(traffic)类型的EIP,限制为1~1000之间的整数。 + +## 绑定EIP + +使用以下代码可以实现EIP的绑定。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +args := &eip.BindEipArgs{ + // 指定eip被绑定的实例类型 + InstanceType: "BCC", + // 指定eip被绑定的实例id + InstanceId: instanceId, +} +if err := client.BindEip(eip, args); err != nil { + fmt.Printf("eip bind bcc error: %+v\n", err) + return +} + +fmt.Printf("eip bind bcc success\n") +``` + +> 注意: +> - 可用于绑定EIP到任意BLB实例或BCC实例。 +> - 只有available状态的EIP支持绑定操作。 +> - 被绑定的实例不能存在任何已有EIP绑定关系。 +> - 被绑定的实例不能处于欠费状态。 + +## 解绑EIP + +使用以下代码可以实现EIP的解绑。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +if err := client.UnBindEip(eip, clientToken); err != nil { + fmt.Printf("eip unbind error: %+v\n", err) + return +} + +fmt.Printf("eip unbind success\n") +``` + +> 注意: +> - 解除指定EIP的绑定关系。 +> - 被解绑的EIP必须已经绑定到某个实例。 + +## 释放EIP + +使用以下代码可以释放指定的EIP。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +err = client.DeleteEip(eip, clientToken) +if err != nil { + fmt.Printf("delete eip error: %+v\n", err) + return +} + +fmt.Printf("delete eip success\n") +``` + +> 注意: +> - 释放指定EIP,被释放的EIP无法找回 +> - 如果EIP被绑定到任意实例,需要先解绑才能释放 +> - 预付费购买的EIP如需提前释放,请通过工单进行 + +## 查询EIP列表 + +使用以下代码可以查询EIP列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +args := &eip.ListEipArgs{ + // 指定要查询的eip + Eip: eip, + // 指定eip绑定的实例类型 + InstanceType: "BCC", + // 指定批量获取列表的查询的起始位置 + Marker: marker, + // 指定每页包含的最大数量,最大数量不超过1000。缺省值为1000 + MaxKeys: maxKeys, + // 指定实例状态,仅支持AVAILABLE, BINDED, PAUSED三种状态的查询 + Status: status, +} +result, err := client.ListEip(args) +if err != nil { + fmt.Printf("list eip error: %+v\n", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("eip list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("eip list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("eip list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("eip list maxKeys: ", result.MaxKeys) +// 获取eip的列表信息 +for _, e := range result.EipList { + fmt.Println("eip name: ", e.Name) + fmt.Println("eip value: ", e.Eip) + fmt.Println("eip status: ", e.Status) + fmt.Println("eip eipInstanceType: ", e.EipInstanceType) + fmt.Println("eip instanceType: ", e.InstanceType) + fmt.Println("eip instanceId: ", e.InstanceId) + fmt.Println("eip shareGroupId: ", e.ShareGroupId) + fmt.Println("eip bandWidthInMbps: ", e.BandWidthInMbps) + fmt.Println("eip paymentTiming: ", e.PaymentTiming) + fmt.Println("eip billingMethod: ", e.BillingMethod) + fmt.Println("eip createTime: ", e.CreateTime) + fmt.Println("eip expireTime: ", e.ExpireTime) +} +``` + +> 注意: +> - 可根据多重条件查询EIP列表。 +> - 如只需查询单个EIP的详情,只需提供eip参数即可。 +> - 如只需查询绑定到指定类型实例上的EIP,提供instanceType参数即可。 +> - 如只需查询指定实例上绑定的EIP的详情,提供instanceType及instanceId参数即可。 +> - 若不提供查询条件,则默认查询覆盖所有EIP。 +> - 返回结果为多重条件交集的查询结果,即提供多重条件的情况下,返回同时满足所有条件的EIP。 +> - 以上查询结果支持marker分页,分页大小默认为1000,可通过maxKeys参数指定。 + +## EIP续费 + +使用以下代码可以为指定的EIP进行续费操作,延长过期时间。 +```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +args := &eip.PurchaseReservedEipArgs{ + // 设置eip的续费信息 + Billing: &eip.Billing{ + Reservation: &eip.Reservation{ + ReservationTimeUnit: "Month", + ReservationLength: 1, + }, + }, +} +if err := client.PurchaseReservedEip(eip, args); err != nil { + fmt.Printf("renew eip error: %+v\n", err) + return +} + +fmt.Printf("renew eip success.") +``` + +> 注意: EIP扩缩容期间不能进行续费操作。 + +## EIP自动续费 +使用以下代码可以为指定的EIP开启自动续费操作 + ```go +// import "github.com/baidubce/bce-sdk-go/services/eip" + +args := &eip.StartAutoRenewArgs{ + // 预付费资源可以设置是否自动续费 + AutoRenewTimeUnit: "month", + AutoRenewTime: 1, +} +if err := client.StartAutoRenew(eip, args); err != nil { + fmt.Printf("start auto renew eip error: %+v\n", err) + return +} + +fmt.Printf("start auto renew eip success.") +``` + +> 注意: +> - 仅预付费资源可以开通自动续费操作。 +> - 设置续费单位若AutoRenewTimeUnit可以为"month"和"year"。 +> - 若AutoRenewTimeUnit设置为month,AutoRenewTime支持1-9;若AutoRenewTimeUnit设置为year,AutoRenewTime支持1-3 + +## EIP停止自动续费 +使用以下代码可以为指定的EIP停止自动续费操作 + ```go + // import "github.com/baidubce/bce-sdk-go/services/eip" + if err := client.StopAutoRenew(eip, ""); err != nil { + fmt.Printf("stop auto renew eip error: %+v\n", err) + return + } + + fmt.Printf("stop auto renew eip success.") + ``` + +# 错误处理 + +GO语言以error类型标识错误,EIP支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | EIP服务返回的错误 + +用户使用SDK调用EIP相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// eipClient 为已创建的EIP Client对象 +args := &eip.ListEipArgs{} +result, err := client.ListEip(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向EIP发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当EIP服务端出现异常时,EIP服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[EIP错误码](https://cloud.baidu.com/doc/EIP/s/Ljwvz33m6) + +## SDK日志 + +EIP GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +EIP GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the EIP go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the EIP go sdk") +``` + + +# 版本变更记录 + +## v0.9.5 [2019-09-24] + +首次发布: + + - 支持申请EIP、EIP带宽扩缩容、绑定EIP、解绑EIP、释放EIP、查询EIP列表、EIP续费接口。 \ No newline at end of file diff --git a/bce-sdk-go/doc/ENIC.md b/bce-sdk-go/doc/ENIC.md new file mode 100644 index 0000000..e322360 --- /dev/null +++ b/bce-sdk-go/doc/ENIC.md @@ -0,0 +1,631 @@ +# ENIC服务 + +# 概述 + +本文档主要介绍ENIC GO SDK的使用。在使用本文档前,您需要先了解ENIC的一些基本知识,并已开通了ENIC服务。若您还不了解ENIC,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/sjwvytvh0 )和[操作指南](https://cloud.baidu.com/doc/VPC/s/0jwvytzll) 。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[ENDPOINT服务域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw )的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/ )。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云ENIC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问ENIC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建ENIC Client + +ENIC Client是ENIC服务的客户端,为开发者与ENIC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建ENIC Client + +通过AK/SK方式访问ENI,用户可以参考如下代码新建一个ENIC Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/eni" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个ENICClient + enicClient, err := eni.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为ENIC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建ENIC Client + +**申请STS token** + +ENIC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问ENIC,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建ENIC Client** + +申请好STS后,可将STS Token配置到ENIC Client中,从而实现通过STS Token创建ENIC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建ENIC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/eni" //导入ENIC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建ENIC服务的Client对象,Endpoint使用默认值 + enicClient, err := eni.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create enic client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + enicClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置ENIC Client时,无论对应ENIC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问ENIC + +ENIC支持HTTPS传输协议,您可以通过在创建ENIC Client对象时指定的Endpoint中指明HTTPS的方式,在ENIC GO SDK中使用HTTPS访问ENIC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/eni" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +enicClient, _ := eni.NewClient(AK, SK, ENDPOINT) +``` + +## 配置ENIC Client + +如果用户需要配置ENIC Client的一些细节的参数,可以在创建ENIC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问ENIC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/eni" + +//创建ENIC Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := eni.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/eni" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := eni.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/eni" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := eni.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问ENIC时,创建的ENIC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建ENIC Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 获取公共服务 + +使用以下代码获取公共服务 +```go +// import "github.com/baidubce/bce-sdk-go/services/eni" + +result, err := client.GetServices() + if err != nil { + fmt.Printf("list public services error: %+v\n", err) + return + } +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 创建ENIC + +```go +args := &eni.CreateEniArgs{ + Name: "name", + SubnetId: "SUBNET_ID", + SecurityGroupIds: []string{ + "g-eqhqsbs84yww", + }, + PrivateIpSet: []PrivateIp{ + { + Primary: true, + PrivateIpAddress: "192.168.0.54", + }, + }, + Ipv6PrivateIpSet: []PrivateIp{ + { + Primary: false, + PrivateIpAddress: "2400:da00:e003:0:1d2:100:0:1", + }, + }, + Description: "go sdk test", + ClientToken: getClientToken(), +} +result, err := client.CreateEni(args) +if err != nil { + fmt.Printf("create enic error: %+v\n", err) + return +} +fmt.Println("create enic success, enic: ", result.EniId) +``` + + +## 更新ENIC + +```go +args := &eni.UpdateEniArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + Name: "name", + Description: "description", + } +res, err := client.UpdateEni(args) +if err != nil { + fmt.Printf("update enic error: %+v\n", err) + return +} +fmt.Printf("update enic success\n") +``` + +## 查询ENIC列表 + +```go +args := &eni.ListEniArgs{ + VpcId: "VPC_ID", +} +res, err := client.ListEni(args) +if err != nil { + fmt.Printf("list enic error: %+v\n", err) + return +} +r, err := json.Marshal(res) +fmt.Println("list eni success: ", string(r)) +} +``` + +## 删除指定ENIC + +```go +args := &eni.DeleteEniArgs{ + EniId: "eniId", + ClientToken: getClientToken(), +} +err := client.DeleteEni(args) +if err != nil { + fmt.Printf("delete enic error: %+v\n", err) + return +} +fmt.Printf("delete enic success\n") +} +``` + +## 查询ENIC详情 + +```go +result, err := client.GetEniDetail("eniId") +if err != nil { + fmt.Printf("select enic error: %+v\n", err) + return +} +r, err := json.Marshal(result) +fmt.Println("select enic success", string(r)) +``` + +## 增加ENIC内网IP + +```go +args := &client.EniPrivateIpArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + PrivateIpAddress: "192.168.0.53", +} +result, err := client.AddPrivateIp(args) +if err != nil { + fmt.Printf("add enic private ip error: %+v\n", err) + return +} +r, err := json.Marshal(result) +fmt.Println("add private ip success", string(r)) +``` + +## 批量增加ENIC内网IP + +```go +args := &client.EniBatchPrivateIpArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + PrivateIpAddresses: []string{ + "192.168.0.28", + "192.168.0.29", + }, +} +result, err := client.BatchAddPrivateIp(args) +if err != nil { + fmt.Printf("batch add enic private ip error: %+v\n", err) + return +} +r, err := json.Marshal(result) +fmt.Println("batch add private ip success", string(r)) +``` + +## 跨子网批量增加ENIC内网IP + +```go +args := &client.EniBatchAddPrivateIpCrossSubnetArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + SubnetId: "subnetId", + PrivateIpAddressCount: 2 +} +result, err := client.BatchAddPrivateIpCrossSubnet(args) +if err != nil { + fmt.Printf("cross subnet and batch add enic private ip error: %+v\n", err) + return +} +r, err := json.Marshal(result) +fmt.Println("cross subnet and batch add private ip success", string(r)) +``` + +## 删除ENIC内网IP + +```go +args := &client.EniPrivateIpArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + PrivateIpAddress: "192.168.0.53", +} +err := client.DeletePrivateIp(args) +if err != nil { + fmt.Printf("delete enic private ip error: %+v\n", err) + return +} +fmt.Println("delete private ip success") +``` + +## 批量删除ENIC内网IP + +```go +args := &client.EniBatchPrivateIpArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + PrivateIpAddresses: []string{ + "192.168.0.34", + "192.168.0.35", + }, +} +err := client.BatchDeletePrivateIp(args) +if err != nil { + fmt.Printf("batch delete enic private ip error: %+v\n", err) + return +} +fmt.Println("batch delete private ip success") +``` + +## ENIC挂载云主机 + +```go +args := &client.EniInstance{ + EniId: "eniId", + ClientToken: getClientToken(), + InstanceId: "192.168.0.55", +} +err := client.AttachEniInstance(args) +if err != nil { + fmt.Printf("enic attach instance error: %+v\n", err) + return +} +fmt.Println("attach instance success") +``` + +## ENIC卸载云主机 + +```go +args := &EniInstance{ + EniId: "eniId", + ClientToken: getClientToken(), + InstanceId: "192.168.0.55", +} +err := client.DetachEniInstance(args) +if err != nil { + fmt.Printf("enic detach instance error: %+v\n", err) + return +} +fmt.Println("detach instance success") +``` + +## ENIC绑定EIP + +```go +args := &client.BindEniPublicIpArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + PrivateIpAddress:"192.168.0.54", + PublicIpAddress:"ip", +} +err := client.BindEniPublicIp(args) +if err != nil { + fmt.Printf("enic bind public ip error: %+v\n", err) + return +} +fmt.Println("enic bind public ip success") +``` + +## ENIC解绑EIP + +```go +args := &client.UnBindEniPublicIpArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + PublicIpAddress:"ip", +} +err := client.UnBindEniPublicIp(args) +if err != nil { + fmt.Printf("enic unbind public ip error: %+v\n", err) + return +} +fmt.Println("enic unbind public ip success") +``` + +## ENIC更新普通安全组 + +```go +args := &client.UpdateEniSecurityGroupArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + SecurityGroupIds: []string{ + "sgId1", + "sgId2", + }, +} +err := client.UpdateEniSecurityGroup(args) +if err != nil { + fmt.Printf("enic update security group error: %+v\n", err) + return +} +fmt.Println("enic update security group success") +``` + +## ENIC更新企业安全组 + +```go +args := &client.UpdateEniEnterpriseSecurityGroupArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + EnterpriseSecurityGroupIds: []string{ + "esgId1", + "esgId2", + }, +} +err := client.UpdateEniEnterpriseSecurityGroup(args) +if err != nil { + fmt.Printf("enic update enterprise security group error: %+v\n", err) + return +} +fmt.Println("enic update enterprise security group success") +``` + +## ENIC查询配额 + +```go +args := &client.EniQuoteArgs{ + EniId: "eniId", + ClientToken: getClientToken(), + InstanceId: "instanceId" +} +err := client.GetEniQuota(args) +if err != nil { + fmt.Printf("enic get quota info error: %+v\n", err) + return +} +fmt.Println("enic get quota info success") +``` + + +# 错误处理 + +GO语言以error类型标识错误,ENIC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | ENIC服务返回的错误 + +用户使用SDK调用ENIC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// enicClient 为已创建的ENIC Client对象 +args := &eni.ListEniArgs{ + VpcId: "VPC_ID", +} +res, err := client.ListEni(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向ENIC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当ENIC服务端出现异常时,ENIC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[ENIC错误码](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +ENIC GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +ENIC GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the ENIC go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the ENIC go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/ESG.md b/bce-sdk-go/doc/ESG.md new file mode 100644 index 0000000..20ace6f --- /dev/null +++ b/bce-sdk-go/doc/ESG.md @@ -0,0 +1,498 @@ +# ESG服务 + +# 概述 + +本文档主要介绍ESG GO SDK的使用。在使用本文档前,您需要先了解ESG的一些基本知识,并已开通了ESG服务。若您还不了解ESG,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/sjwvytvh0 )和[操作指南](https://cloud.baidu.com/doc/VPC/s/Vjwvyu1sh) 。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[ENDPOINT服务域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw )的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/ )。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云ESG,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问ESG做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建ESG Client + +ESG Client是ESG服务的客户端,为开发者与ESG服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建ESG Client + +通过AK/SK方式访问ESG,用户可以参考如下代码新建一个ESG Client: + +```go +import ( +"github.com/baidubce/bce-sdk-go/services/esg" +) + +func main() { +// 用户的Access Key ID和Secret Access Key +ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + +// 用户指定的Endpoint +ENDPOINT := + +// 初始化一个ESGClient +esgClient, err := esg.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为ESG的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建ESG Client + +**申请STS token** + +ESG可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问ESG,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建ESG Client** + +申请好STS后,可将STS Token配置到ESG Client中,从而实现通过STS Token创建ESG Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建ESG Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/esg" //导入ESG服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建ESG服务的Client对象,Endpoint使用默认值 + esgClient, err := esg.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create esg client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + esgClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置ESG Client时,无论对应ESG服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问ESG + +ESG支持HTTPS传输协议,您可以通过在创建ESG Client对象时指定的Endpoint中指明HTTPS的方式,在ESG GO SDK中使用HTTPS访问ESG服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +esgClient, _ := esg.NewClient(AK, SK, ENDPOINT) +``` + +## 配置ESG Client + +如果用户需要配置ESG Client的一些细节的参数,可以在创建ESG Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问ESG服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +//创建ESG Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := esg.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := esg.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := esg.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问ESG时,创建的ESG Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建ESG Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 获取公共服务 + +使用以下代码获取公共服务 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +result, err := client.GetServices() + if err != nil { + fmt.Printf("list public services error: %+v\n", err) + return + } +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 创建ESG + +使用以下代码可以申请一个ESG。 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +args := &esg.CreateEsgArgs{ + Name: "esgGoSdkTest", + Rules: []EnterpriseSecurityGroupRule{ + { + Action: "deny", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "udp", + Remark: "go sdk test", + SourceIp: "all", + }, + { + Action: "allow", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "icmp", + Remark: "go sdk test", + SourceIp: "all", + }, + }, + Desc: "go sdk test", + Tags: []model.TagModel{ + { + TagKey: "test", + TagValue: "", + }, + }, + } +result, err := client.CreateEsg(args) +if err != nil { + fmt.Printf("create esg error: %+v\n", err) + return +} + +fmt.Println("create esg success, esg: ", result.EnterpriseSecurityGroupId) +``` + + +## 查询ESG 列表 + +使用以下代码可以查询ESG列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +args := &esg.ListEsgArgs{ + InstanceId: "instanceId", + MaxKeys: 1000, + } +res, err := client.ListEsg(args) + if err != nil { + fmt.Printf("list esg error: %+v\n", err) + return + } + // 返回标记查询的起始位置 + fmt.Println("esg list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("esg list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("esg list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("esg list maxKeys: ", result.MaxKeys) + // 获取esg的列表信息 + for _, e := range res.EnterpriseSecurityGroups { + fmt.Println("esg id: ", e.Id) + fmt.Println("esg name: ", e.Name) + fmt.Println("esg description: ", e.Desc) + fmt.Println("esg createTime: ", e.CreateTime) + } +``` + +## 删除ESG + +使用以下代码可以释放指定的ESG。 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +args := &esg.DeleteEsgArgs{ + EnterpriseSecurityGroupId: "esgId", +} +err := client.DeleteEsg(args) +if err != nil { + fmt.Printf("delete esg error: %+v\n", err) + return +} + +fmt.Printf("delete esg success\n") +``` + +> 注意: +> - 删除指定ESG,被释放的ESG无法找回 + +## 创建ESG规则 + +使用以下代码可以为ESG创建规则。 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +args := &esg.CreateEsgRuleArgs{ + Rules: []EnterpriseSecurityGroupRule{ + { + Action: "deny", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "udp", + Remark: "go sdk test", + SourceIp: "all", + }, + }, + EnterpriseSecurityGroupId: "esg-id", + } +err := client.CreateEsgRules(args) +if err != nil { + fmt.Printf("create esg rules error: %+v\n", err) + return +} +fmt.Printf("create esg rules success\n") + +``` + +## 删除ESG规则 + +使用以下代码可以释放指定的ESG规则。 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +args := &esg.DeleteEsgRuleArgs{ + EnterpriseSecurityGroupRuleId: "esgRuleId", +} +err := client.DeleteEsgRule(args) +if err != nil { + fmt.Printf("delete esg rule error: %+v\n", err) + return +} + +fmt.Printf("delete esg rule success\n") +``` + +> 注意: +> - 删除指定ESG规则,被释放的ESG规则无法找回 + +## 更新ESG规则 + +使用以下代码可以为ESG更新规则。 +```go +// import "github.com/baidubce/bce-sdk-go/services/esg" + +args := &esg.UpdateEsgRuleArgs{ + Priority: 900, + Remark: "go sdk test update", + EnterpriseSecurityGroupRuleId: "esgRuleId", +} +err := client.UpdateEsgRule(args) +if err != nil { + fmt.Printf("upda esg rule error: %+v\n", err) + return +} +fmt.Printf("update esg rule success\n") + +``` + + +# 错误处理 + +GO语言以error类型标识错误,ESG支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | ESG服务返回的错误 + +用户使用SDK调用ESG相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// esgClient 为已创建的ESG Client对象 +args := &esg.ListEsgArgs{} +result, err := client.ListEsg(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向ESG发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当ESG服务端出现异常时,ESG服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[ESG错误码](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +ESG GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +ESG GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the ESG go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the ESG go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/ETGateway.md b/bce-sdk-go/doc/ETGateway.md new file mode 100644 index 0000000..1b945aa --- /dev/null +++ b/bce-sdk-go/doc/ETGateway.md @@ -0,0 +1,473 @@ +# 专线网关服务 + +# 概述 + +本文档主要介绍EtGateway GO SDK的使用。在使用本文档前,您需要先了解专线网关的一些基本知识,并已开通了专线网关服务。若您还不了解专线网关,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/Jjwvytz9j)和[操作指南](https://cloud.baidu.com/doc/VPC/s/Jjwvytz9j)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[专线网关服务域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云专线网关,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问专线网关做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建EtGateway Client + +EtGateway Client是专线网关服务的客户端,为开发者与专线网关服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建EtGateway Client + +通过AK/SK方式访问专线网关,用户可以参考如下代码新建一个EtGateway Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/etGateway" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个etGatewayClient + etGatewayClient, err := etGateway.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建EtGateway Client + +**申请STS token** + +EtGateway可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问专线网关,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建专线网关 Client** + +申请好STS后,可将STS Token配置到EtGateway Client中,从而实现通过STS Token创建EtGateway Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建专线网关 Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/etGateway" //导入专线网关服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建专线网关服务的Client对象,Endpoint使用默认值 + etGatewayClient, err := etGateway.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create etGateway client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + etGatewayClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置EtGatewayClient Client时,无论对应专线网关服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问专线网关 + +专线网关支持HTTPS传输协议,您可以通过在创建EtGateway Client对象时指定的Endpoint中指明HTTPS的方式,在EtGateway GO SDK中使用HTTPS访问专线网关服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +etGatewayClient, _ := etGateway.NewClient(AK, SK, ENDPOINT) +``` + +## 配置EtGateway Client + +如果用户需要配置EtGateway Client的一些细节的参数,可以在创建EtGateway Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问专线网关服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + +//创建EtGateway Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := etGateway.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := bcc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := etGateway.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问专线网关时,创建的EtGateway Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建EtGateway Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + + +## 创建专线网关 + +使用以下代码可以申请一个专线网关。 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" +args := &etGateway.CreateEtGatewayArgs{ + Name: "TestSDK", + Description: " test", + VpcId: "vpc-2pa2x0bjt26i", + Speed: 100, + ClientToken: getClientToken(), + } + result, err := client.CreateEtGateway(args) +if err != nil { + fmt.Printf("create etGateway error: %+v\n", err) + return +} + +fmt.Println("create etGateway success, etGateway: ", result.EtGatewayId) +``` + + +## 查询专线网关列表 + +使用以下代码可以查询专线网关列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + +args := &etGateway.ListEtGatewayArgs{ + VpcId: "vpc-xsd65rcsp5ue", + } + result := &ListEtGatewayResult{} + result, err := client.ListEtGateway(args) + if err != nil { + fmt.Printf("list etGateway error: %+v\n", err) + return + } + // 返回标记查询的起始位置 + fmt.Println("etGateway list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("etGateway list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("etGateway list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("etGateway list maxKeys: ", result.MaxKeys) +``` + +## 查询专线网关详情 + +使用以下代码可以实现查询专线网关的详情信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + res := &etGateway.EtGatewayDetail{} + res, err := client.GetEtGatewayDetail("dcgw-vs1rvp9qy79f") + if err != nil { + fmt.Printf("get dcGateway detail error: %+v\n", err) + return + } + fmt.Println("etGatewayId id: ", result.EtGatewayId) +} +``` + +## 更新专线网关 + +使用以下代码可以实现专线网关的更新。 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" +args := &etGateway.UpdateEtGatewayArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-mx3annmentbu", + Name: "aaa", + Description: "test", + } + err := client.UpdateEtGateway(args) +if err != nil { + fmt.Printf("update etgateway error: %+v\n", err) + return +} +fmt.Printf("update etgateway success\n") +``` + +## 绑定专线 + +使用以下代码可以将专线网关绑定到专线上。 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + +args := &etGateway.BindEtArgs{ + ClientToken: clientToken, + EtGatewayId: "dcgw-iiyc0ers2qx4", + EtId: "et-aaccd", + ChannelId: "sdxs", + LocalCidrs: []string{"192.168.0.1"}, + } + err := client.BindEt(args) +if err != nil { + fmt.Printf("bind etGateway error: %+v\n", err) + return +} +``` + + +## 解绑专线 + +使用以下代码可以将专线与专线网关进行解绑。 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" +if err := client.UnBindEt("dcgw-iiyc0ers2qx4", clientToken); err != nil { + fmt.Printf("unbind dc error: %+v\n", err) + return +} + +fmt.Printf("unbind dc success.") +``` + + +## 删除专线网关 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" +err := client.DeleteEtGateway("dcgw-iiyc0ers2qx4", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +if err != nil { + fmt.Printf("delete etGateway error: %+v\n", err) + return +} + +fmt.Printf("delete etGateway success\n") +``` +## 创建专线网关健康检查 +```go +// import "github.com/baidubce/bce-sdk-go/services/etGateway" + auto := true + args := &CreateHealthCheckArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-iiyc0ers2qx4", + HealthCheckSourceIp: "1.2.3.4", + HealthCheckType: HEALTH_CHECK_ICMP, + HealthCheckPort: 80, + HealthCheckInterval: 60, + HealthThreshold: 3, + UnhealthThreshold: 4, + AutoGenerateRouteRule: &auto, + } + err := client.CreateHealthCheck(args) + if err != nil { + fmt.Printf("create etGateway healthcheck error: %+v\n", err) + return + } + fmt.Printf("create etGateway healthcheck success\n") +``` + + +# 错误处理 + +GO语言以error类型标识错误,专线网关支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | 专线网关服务返回的错误 + +用户使用SDK调用专线网关相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// etGatewayClient 为已创建的专线网关 Client对象 +args := &etGateway.ListEtGatewayArgs{} +result, err := client.ListEtGatewayArgs(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向专线网关发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当专线网关服务端出现异常时,专线网关服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[专线网关错误码](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +EtGateway GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +EtGateway GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the etGateway go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the etGateway go sdk") +``` + + +# 版本变更记录 + +## v0.9.5 [2020-05-29] + +首次发布: + + - 支持创建专线网关、查询专线网关列表、查询专线网关详情、更新专线网关、释放专线网关、绑定/解绑专线、创建专线网关健康检查。 \ No newline at end of file diff --git a/bce-sdk-go/doc/GAIADB.md b/bce-sdk-go/doc/GAIADB.md new file mode 100644 index 0000000..55bb1bd --- /dev/null +++ b/bce-sdk-go/doc/GAIADB.md @@ -0,0 +1,1225 @@ +# GAIADB服务 + +# 概述 + +本文档主要介绍GAIADB GO SDK的使用。在使用本文档前,您需要先了解GAIADB的一些基本知识。若您还不了解GAIADB,可以参考[产品描述](https://cloud.baidu.com/doc/GaiaDB/s/mkd45c3ap)和[入门指南](https://cloud.baidu.com/doc/GaiaDB/s/vkgkfur5q)。 + +相关参数说明可参考官方API文档[API参考](https://cloud.baidu.com/doc/GaiaDB/s/Zl82ton8n) + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[GAIADB访问域名](https://cloud.baidu.com/doc/GaiaDB/s/al84889rz)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/vkgkfur5q/)。 + +## 获取密钥 + +要使用百度云SCS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问SCS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建GAIADB Client + +GAIADB Client是GAIADB服务的客户端,为开发者与GAIADB服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建GAIADB Client + +通过AK/SK方式访问GAIADB,用户可以参考如下代码新建一个GAIADB Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/gaiadb" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个GAIADBClient + gaiadbClient, err := scs.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”。第三个参数`ENDPOINT`支持用户自己指定域名. + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`gaiadb.bj.baidubce.com`。 + +### 使用STS创建GAIADB Client + +**申请STS token** + +GAIADB可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问GAIADB,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建GAIADB Client** + +申请好STS后,可将STS Token配置到GAIADB Client中,从而实现通过STS Token创建GAIADB Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建GAIADB Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/gaiadb" //导入GAIADB服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建GAIADB服务的Client对象,Endpoint使用默认值 + gaiadbClient, err := gaiadb.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create GAIADB client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + gaiadbClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置GAIADB Client时,无论对应GAIADB服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问GAIADB + +GAIADB支持HTTPS传输协议,您可以通过在创建GAIADB Client对象时指定的Endpoint中指明HTTPS的方式,在GAIADB GO SDK中使用HTTPS访问SCS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/gaiadb" + +ENDPOINT := "https://gaiadb.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +gaiadbClient, _ := gaiadb.NewClient(AK, SK, ENDPOINT) +``` + +## 配置GAIADB Client + +如果用户需要配置GAIADB Client的一些细节的参数,可以在创建GAIADB Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问SCS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/gaiadb" + +//创建GAIADB Client对象 +AK, SK := , +ENDPOINT := "gaiadb.bj.baidubce.com" +client, _ := gaiadb.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/gaiadb" + +AK, SK := , +ENDPOINT := "gaiadb.bj.baidubce.com" +client, _ := gaiadb.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/gaiadb" + +AK, SK := , +ENDPOINT := "gaiadb.bj.baidubce.com" +client, _ := gaiadb.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问GAIADB时,创建的GAIADB Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建GAIADB Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + + +## 集群管理 + +### 创建集群 +使用以下代码可以创建Gaiadb集群 +```go +args := &gaiadb.CreateClusterArgs{ + ClientToken: getClientToken(), + Number: 1, + ProductType: "postpay", + InstanceParam: InstanceParam{ + EngineVersion: "8.0", + SubnetId: "sbn-na4tmg4v11hs", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, + AllocatedStorageInGB: 5120, + Engine: "MySQL", + VpcId: "vpc-it3v6qt3jhvj", + InstanceAmount: 2, + ProxyAmount: 2, + }, +} +result, err := GAIADB_CLIENT.CreateCluster(args) + +if err != nil { + fmt.Println("create cluster failed:", err) +} else { + fmt.Println("create cluster success: ", result) +} +``` +### 删除集群 +使用以下代码可以删除Gaiadb集群 +```go +err := GAIADB_CLIENT.DeleteCluster(clusterId) + +if err != nil { + fmt.Println("delete cluster failed:", err) +} else { + fmt.Println("delete cluster success") +} +``` +### 修改集群名称 +使用以下代码可以修改集群名称 +```go +args := &gaiadb.ClusterName{ + ClusterName: "cluster_test", +} +err := GAIADB_CLIENT.RenameCluster(clusterId, args) + +if err != nil { + fmt.Println("rename cluster failed:", err) +} else { + fmt.Println("rename cluster success") +} +``` + +### 变配集群 +使用以下代码可以变配Gaiadb集群 +```go +args := &gaiadb.ResizeClusterArgs{ + ResizeType: "resizeSlave", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, +} +result, err := GAIADB_CLIENT.ResizeCluster(clusterId, args) + +if err != nil { + fmt.Println("resize cluster failed:", err) +} else { + fmt.Println("resize cluster success: ", result) +} +``` + +### 获取集群列表 +使用以下代码可以获取集群列表 +```go +args := &gaiadb.Marker{ + Marker: "-1", + MaxKeys: 1000, +} +result, err := GAIADB_CLIENT.GetClusterList(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) + +if err != nil { + fmt.Println("get cluster list failed:", err) +} else { + fmt.Println("get cluster list success: ", result) +} +``` +### 获取集群详情 +使用以下代码可以获取集群详情 +```go +result, err := GAIADB_CLIENT.GetClusterDetail(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) + +if err != nil { + fmt.Println("get cluster detail failed:", err) +} else { + fmt.Println("get cluster detail success: ", result) +} +``` +### 查询集群存储容量 +使用以下代码可以查询集群存储容量 +```go +result, err := GAIADB_CLIENT.GetClusterCapacity(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) + +if err != nil { + fmt.Println("get cluster capacity failed:", err) +} else { + fmt.Println("get cluster capacity success: ", result) +} +``` + +### 查询新购集群价格 +使用以下代码可以查询新购集群价格 +```go +args := &gaiadb.QueryPriceArgs{ + Number: 1, + InstanceParam: InstanceInfo{ + ReleaseVersion: "5.7", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, + AllocatedStorageInGB: 5120, + InstanceAmount: 2, + ProxyAmount: 2, + }, + ProductType: "postpay", +} +result, err := GAIADB_CLIENT.QueryClusterPrice(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get cluster price failed:", err) +} else { + fmt.Println("get cluster price success: ", result) +} +``` + +### 查询变配集群价格 +使用以下代码可以查询变配集群价格 +```go +args := &gaiadb.QueryResizePriceArgs{ + ClusterId: clusterId, + ResizeType: "resizeSlave", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, +} +result, err := GAIADB_CLIENT.QueryResizeClusterPrice(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get resize cluster price failed:", err) +} else { + fmt.Println("get resize cluster price success: ", result) +} +``` + +### 重启计算节点 +使用以下代码可以重启计算节点 +```go +args := &gaiadb.RebootInstanceArgs{ + ExecuteAction: "executeNow", +} +err := GAIADB_CLIENT.RebootInstance(clusterId, instanceId, args) +if err != nil { + fmt.Println("reboot instance failed:", err) +} else { + fmt.Println("reboot instance success ") +} +``` +### 绑定标签 +使用以下代码可以绑定标签 +```go +args := &gaiadb.BindTagsArgs{ + Resources: []Resource{ + { + ResourceId: clusterId, + Tags: []Tag{ + { + TagKey: "testTagKey", + TagValue: "testTagValue", + }, + }, + }, + }, +} +err := GAIADB_CLIENT.BindTags(args) +if err != nil { + fmt.Println("bind tag failed:", err) +} else { + fmt.Println("bind tag success ") +} +``` + +### 主从切换 +使用以下代码可以主从切换 +```go +args := &gaiadb.ClusterSwitchArgs{ + ExecuteAction: "executeNow", + SecondaryInstanceId: instanceId, +} +result, err := GAIADB_CLIENT.ClusterSwitch(clusterId, args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("cluster switch failed:", err) +} else { + fmt.Println("cluster switch success: ", result) +} +``` +## 入口管理 +### 查询入口列表 +使用以下代码查询入口列表 +```go +result, err := GAIADB_CLIENT.GetInterfaceList(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get interface list failed:", err) +} else { + fmt.Println("get interface list success: ", result) +} +``` +### 更新入口域名 +使用以下代码更新入口域名 +```go +args := &gaiadb.UpdateDnsNameArgs{ + InterfaceId: "gaiadbm5h6ys_interface0000", + DnsName: "my.gaiadb.bj.baidubce.com", +} +err := GAIADB_CLIENT.UpdateDnsName(clusterId, args) +if err != nil { + fmt.Println("update dns name failed:", err) +} else { + fmt.Println("update dns name success") +} +``` +### 更新入口配置 +使用以下代码更新入口配置 +```go +args := &gaiadb.UpdateInterfaceArgs{ + InterfaceId: "gaiadbm5h6ys_interface0000", + Interface: InterfaceInfo{ + MasterReadable: 1, + AddressName: "addressname", + InstanceBinding: []string{ + "gaiadbymbrc8-primary-6f1cc3a2", + "gaiadbymbrc8-secondary-ec909467", + }, + }, +} +err := GAIADB_CLIENT.UpdateInterface(clusterId, args) +if err != nil { + fmt.Println("update interface failed:", err) +} else { + fmt.Println("update interface success") +} +``` +### 更新入口新节点自动加入配置 +使用以下代码更新入口新节点自动加入配置 +```go +args := &gaiadb.NewInstanceAutoJoinArgs{ + AutoJoinRequestItems: []AutoJoinRequestItem{ + { + NewInstanceAutoJoin: "off", + InterfaceId: "gaiadbymbrc8-primary-6f1cc3a2", + }, + }, +} +err := GAIADB_CLIENT.NewInstanceAutoJoin(clusterId, args) +if err != nil { + fmt.Println("new instance audo join failed:", err) +} else { + fmt.Println("new instance audo join success") +} +``` +## 账号管理 +### 创建账号 +使用以下代码创建账号 +```go +args := &gaiadb.CreateAccountArgs{ + AccountName: "testaccount", + Password: "baidu@123", + AccountType: "common", + Remark: "testRemark", +} +err := GAIADB_CLIENT.CreateAccount(clusterId, args) +if err != nil { + fmt.Println("create account failed:", err) +} else { + fmt.Println("create account success") +} +``` +### 删除账号 +使用以下代码删除账号 +```go +err := GAIADB_CLIENT.DeleteAccount(clusterId, "testaccount") +if err != nil { + fmt.Println("delete account failed:", err) +} else { + fmt.Println("delete account success") +} +``` +### 查询账号详情 +使用以下代码查询账号详情 +```go +result, err := GAIADB_CLIENT.GetAccountDetail(clusterId, "testaccount") +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get account detail failed:", err) +} else { + fmt.Println("get account detail success") +} +``` +### 查询账号列表 +使用以下代码查询账号列表 +```go +result, err := GAIADB_CLIENT.GetAccountList(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get account list failed:", err) +} else { + fmt.Println("get account list success") +} +``` + + +### 更新账号备注 +使用以下代码更新账号备注 +```go +args := &gaiadb.RemarkArgs{ + Remark: "remark", + Etag: "v0", +} +result, err := GAIADB_CLIENT.UpdateAccountRemark(clusterId, accountName, args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("update account remark failed:", err) +} else { + fmt.Println("update account remark success") +} +``` + +### 更新账号白名单 +使用以下代码更新账号白名单 +```go +args := &gaiadb.AuthIpArgs{ + Action: "ipAdd", + Value: AuthIp{ + Authip: []string{"10.10.10.10"}, + Authbns: []string{}, + }, +} +err := GAIADB_CLIENT.UpdateAccountAuthIp(clusterId, "testaccount", args) +if err != nil { + fmt.Println("update account auth ip failed:", err) +} else { + fmt.Println("update account auth ip success") +} +``` + +### 更新账号权限 +使用以下代码更新账号权限 +```go +args := &gaiadb.PrivilegesArgs{ + DatabasePrivileges: []DatabasePrivilege{ + { + DbName: "testdb", + AuthType: "definePrivilege", + Privileges: []string{"UPDATE"}, + }, + }, + Etag: "v0", +} +err := GAIADB_CLIENT.UpdateAccountPrivileges(clusterId, "testaccount", args) +if err != nil { + fmt.Println("update account privileges failed:", err) +} else { + fmt.Println("update account privileges success") +} +``` +### 更新账号密码 +使用以下代码更新账号密码 +```go +args := &gaiadb.PasswordArgs{ + Password: "testpassword", + Etag: "v0", +} +err := GAIADB_CLIENT.UpdateAccountPassword(clusterId, "testaccount", args) +if err != nil { + fmt.Println("update account password failed:", err) +} else { + fmt.Println("update account password success") +} +``` +## 数据库管理 +### 创建数据库 +使用以下代码创建数据库 +```go +args := &gaiadb.CreateDatabaseArgs{ + DbName: "test_db", + CharacterSetName: "utf8", + Remark: "sdk test", +} +err := GAIADB_CLIENT.CreateDatabase(clusterId, args) +if err != nil { + fmt.Println("create database failed:", err) +} else { + fmt.Println("create database success") +} +``` +### 删除数据库 +使用以下代码删除数据库 +```go +err := GAIADB_CLIENT.DeleteDatabase(clusterId, "test_db") +if err != nil { + fmt.Println("delete database failed:", err) +} else { + fmt.Println("delete database success") +} +``` +### 查看数据库列表 +使用以下代码查看数据库列表 +```go +result, err := GAIADB_CLIENT.ListDatabase(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("list database failed:", err) +} else { + fmt.Println("list database success") +} +``` +## 备份管理 +### 创建备份 +使用以下代码创建备份 +```go +err := GAIADB_CLIENT.CreateSnapshot(clusterId) +if err != nil { + fmt.Println("create snapshot failed:", err) +} else { + fmt.Println("create snapshot success") +} +``` + +### 查询备份列表 +使用以下代码查询备份列表 +```go +result, err := GAIADB_CLIENT.ListSnapshot(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get snapshot list failed:", err) +} else { + fmt.Println("get snapshot list success") +} +``` +### 更新备份策略 +使用以下代码更新备份策略 +```go +args := &gaiadb.UpdateSnapshotPolicyArgs{ + DataBackupWeekDay: []string{"Monday"}, + DataBackupRetainStrategys: []DataBackupRetainStrategy{{ + StartSeconds: 0, + RetainCount: "8", + Precision: 86400, + EndSeconds: -691200, + }}, + DataBackupTime: "02:00:00Z", +} +err := GAIADB_CLIENT.UpdateSnapshotPolicy(clusterId, args) +if err != nil { + fmt.Println("update snapshot policy failed:", err) +} else { + fmt.Println("update snapshot policy success") +} +``` +## 安全管理 +### 更新 IP 白名单 +使用以下代码更新 IP 白名单 +```go +args := &gaiadb.UpdateWhiteListArgs{ + AuthIps: []string{"192.168.1.2"}, + Etag: "v0", +} +err := GAIADB_CLIENT.UpdateWhiteList(clusterId, args) +if err != nil { + fmt.Println("update white list failed:", err) +} else { + fmt.Println("update white list success") +} +``` +### 查询 IP 白名单 +使用以下代码查询 IP 白名单 +```go +result, err := GAIADB_CLIENT.GetWhiteList(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get white list failed:", err) +} else { + fmt.Println("get white list success: ", result) +} +``` +## 热活集群组管理 +### 创建热活集群组 +使用以下代码创建热活集群组 +```go +args := &gaiadb.CreateMultiactiveGroupArgs{ + LeaderClusterId: clusterId, + MultiActiveGroupName: "test_multiactive_group", +} +result, err := GAIADB_CLIENT.CreateMultiactiveGroup(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("create multiactive group failed:", err) +} else { + fmt.Println("create multiactive group success: ", result) +} +``` +### 删除热活集群组 +使用以下代码删除热活集群组 +```go +err := GAIADB_CLIENT.DeleteMultiactiveGroup(groupId) +if err != nil { + fmt.Println("delete multiactive group failed:", err) +} else { + fmt.Println("delete multiactive group success: ", result) +} +``` +### 更新热活集群组名称 +使用以下代码更新热活集群组名称 +```go +args := &gaiadb.RenameMultiactiveGroupArgs{ + MultiActiveGroupName: "test_multiactive_group", +} +err := GAIADB_CLIENT.RenameMultiactiveGroup(groupId, args) +if err != nil { + fmt.Println("rename multiactive group failed:", err) +} else { + fmt.Println("rename multiactive group success: ", result) +} +``` +### 查询热活集群组列表 +使用以下代码查询热活集群组列表 +```go +result, err := GAIADB_CLIENT.MultiactiveGroupList() +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("list multiactive group failed:", err) +} else { + fmt.Println("list multiactive group success: ", result) +} +``` +### 查询热活集群组详情 +使用以下代码查询热活集群组详情 +```go +result, err := GAIADB_CLIENT.MultiactiveGroupDetail("gaiagroup-0luzwo") +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get multiactive group detail failed:", err) +} else { + fmt.Println("get multiactive group detail success: ", result) +} +``` +### 查询从集群延迟信息 +使用以下代码查询从集群延迟信息 +```go +result, err := GAIADB_CLIENT.GetSyncStatus("gaiagroup-0luzwo", clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get sync status failed:", err) +} else { + fmt.Println("get sync status success: ", result) +} +``` +### 主从切换 +使用以下代码主从切换 +```go +args := &gaiadb.ExchangeArgs{ + ExecuteAction: "executeNow", + NewLeaderClusterId: clusterId, +} +err := GAIADB_CLIENT.GroupExchange("gaiagroup-0luzwo", args) +if err != nil { + fmt.Println("exchange failed:", err) +} else { + fmt.Println("exchange success: ", result) +} +``` +## 参数模板管理 +### 查询参数列表 +使用以下代码查询参数列表 +```go +result, err := GAIADB_CLIENT.GetParamsList(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get params list failed:", err) +} else { + fmt.Println("get params list success: ", result) +} +``` +### 查询参数更新历史 +使用以下代码查询参数更新历史 +```go +result, err := GAIADB_CLIENT.GetParamsHistory(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get params history failed:", err) +} else { + fmt.Println("get params history success: ", result) +} +``` +### 更新参数 +使用以下代码更新参数 +```go +args := &gaiadb.UpdateParamsArgs{ + Params: map[string]interface{}{ + "auto_increment_increment": "5", + }, + Timing: "now", +} +err := GAIADB_CLIENT.UpdateParams(clusterId, args) +if err != nil { + fmt.Println("update params failed:", err) +} else { + fmt.Println("update params success: ", result) +} +``` +## 参数模板管理 +### 查询参数模板列表 +使用以下代码查询参数模板列表 +```go +args := &gaiadb.ListParamTempArgs{ + Detail: 0, + Type: "mysql", + PageNo: 1, + PageSize: 10, +} +result, err := GAIADB_CLIENT.ListParamTemplate(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("list param template failed:", err) +} else { + fmt.Println("list param template success: ", result) +} +``` +### 保存为参数模板 +使用以下代码保存为参数模板 +```go +args := &gaiadb.ParamTempArgs{ + Type: "mysql", + Version: "8.0", + Description: "create by sdk", + Name: "sdk_test", + Source: clusterId, +} +err := GAIADB_CLIENT.SaveAsParamTemplate(args) +if err != nil { + fmt.Println("save as template failed:", err) +} else { + fmt.Println("save as template success: ", result) +} +``` +### 查询参数模板应用记录 +使用以下代码查询参数模板应用记录 +```go +result, err := GAIADB_CLIENT.GetTemplateApplyRecords(templateId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get apply record failed:", err) +} else { + fmt.Println("get apply record success: ", result) +} +``` +### 删除参数模板中的参数 +使用以下代码删除参数模板中的参数 +```go +args := &gaiadb.Params{ + Params: []string{"long_query_time"}, +} +err := GAIADB_CLIENT.DeleteParamsFromTemp(templateId, args) +if err != nil { + fmt.Println("delete params from template failed:", err) +} else { + fmt.Println("delete params from template success: ", result) +} +``` +### 更新参数模板 +使用以下代码更新参数模板 +```go +args := &gaiadb.UpdateParamTplArgs{ + Name: "test_template", + Description: "test_template_description", +} +err := GAIADB_CLIENT.UpdateParamTemplate(templateId, args) + +if err != nil { + fmt.Println("update params template failed:", err) +} else { + fmt.Println("update params template success: ", result) +} +``` +### 修改参数模板中的参数 +使用以下代码修改参数模板中的参数 +```go +args := &ModifyParamsArgs{ + Params: map[string]interface{}{ + "auto_increment_increment": "5", + "long_query_time": "6.6", + }, +} +err := GAIADB_CLIENT.ModifyParams(templateId, args) + +if err != nil { + fmt.Println("modify params failed:", err) +} else { + fmt.Println("modify params success: ", result) +} +``` +### 删除参数模板 +使用以下代码删除参数模板 +```go +err := GAIADB_CLIENT.DeleteParamTemplate(templateId) +if err != nil { + fmt.Println("delete param template failed:", err) +} else { + fmt.Println("delete param template success: ", result) +} +``` +### 创建参数模板 +使用以下代码创建参数模板 +```go +args := &gaiadb.CreateParamTemplateArgs{ + Name: "test_template", + Type: "mysql", + Version: "8.0", + Description: "test_template_description", +} +err := GAIADB_CLIENT.CreateParamTemplate(args) +if err != nil { + fmt.Println("create param template failed:", err) +} else { + fmt.Println("create param template success: ", result) +} +``` +### 查询参数模板详情 +使用以下代码查询参数模板详情 +```go +result, err := GAIADB_CLIENT.GetParamTemplateDetail(templateId, "0") +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get param template detail failed:", err) +} else { + fmt.Println("get param template detail success: ", result) +} +``` +### 查询参数模板更新历史 +使用以下代码查询参数模板更新历史 +```go +result, err := GAIADB_CLIENT.GetParamTemplateHistory(templateId, "addParam") +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get param template records failed:", err) +} else { + fmt.Println("get param template records success: ", result) +} +``` +### 应用参数模板 +使用以下代码应用参数模板 +```go +args := &gaiadb.ApplyParamTemplateArgs{ + Timing: "now", + Clusters: map[string]interface{}{ + "gaiadbk3pyxv": []interface{}{}, + }, +} +err := GAIADB_CLIENT.ApplyParamTemplate(templateId, args) +if err != nil { + fmt.Println("apply param template failed:", err) +} else { + fmt.Println("apply param template success: ", result) +} +``` +## 维护时间窗口管理 +### 更新时间窗口 +使用以下代码更新时间窗口 +```go +args := &gaiadb.UpdateMaintenTimeArgs{ + Period: "1,2,3", + StartTime: "03:00", + Duration: 1, +} +err := GAIADB_CLIENT.UpdateMaintenTime(clusterId, args) +if err != nil { + fmt.Println("update mainten time failed:", err) +} else { + fmt.Println("update mainten time success: ", result) +} +``` +### 查询时间窗口详情 +使用以下代码查询时间窗口详情 +```go +result, err := GAIADB_CLIENT.GetMaintenTime(clusterId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get mainten time detail failed:", err) +} else { + fmt.Println("get mainten time detail success: ", result) +} +``` +## 慢日志管理 +### 查询慢sql详情 +使用以下代码查询慢sql详情 +```go +args := &gaiadb.GetSlowSqlArgs{ + Page: "1", + PageSize: "10", +} +result, err := GAIADB_CLIENT.GetSlowSqlDetail(clusterId, args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get slow sql detail failed:", err) +} else { + fmt.Println("get slow sql detail success: ", result) +} +``` +### 查询慢sql优化建议 +使用以下代码查询慢sql优化建议 +```go +result, err := GAIADB_CLIENT.SlowSqlAdvice(clusterId, sqlId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get slow sql advice failed:", err) +} else { + fmt.Println("get slow sql advice success: ", result) +} +``` +## Binlog管理 +### 查询 binlog 备份详情 +使用以下代码查询 binlog 备份详情 +```go +args := &gaiadb.GetBinlogArgs{ + AppId: clusterId, + LogBackupType: "logical", +} +result, err := GAIADB_CLIENT.GetBinlogDetail(logId, args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get binlog detail failed:", err) +} else { + fmt.Println("get binlog detail success: ", result) +} +``` +### 查询 binlog 备份列表 +使用以下代码查询 binlog 备份列表 +```go +args := &gaiadb.GetBinlogListArgs{ + AppID: clusterId, + LogBackupType: "logical", + PageNo: 1, + PageSize: 10, +} +result, err := GAIADB_CLIENT.GetBinlogList(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get binlog list failed:", err) +} else { + fmt.Println("get binlog list success: ", result) +} +``` +## 任务管理 +### 立即执行任务 +使用以下代码立即执行任务 +```go +err := GAIADB_CLIENT.ExecuteTaskNow(taskId) +if err != nil { + fmt.Println("execute task now failed:", err) +} else { + fmt.Println("execute task now success: ", result) +} +``` +### 取消任务 +使用以下代码取消任务 +```go +err := GAIADB_CLIENT.CancelTask(taskId) +if err != nil { + fmt.Println("cancel task failed:", err) +} else { + fmt.Println("cancel task success: ", result) +} +``` +### 查询任务列表 +使用以下代码查询任务列表 +```go +args := &gaiadb.TaskListArgs{ + Region: "bj", + StartTime: "2023-09-11 16:00:00", +} +result, err := GAIADB_CLIENT.GetTaskList(args) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get task list failed:", err) +} else { + fmt.Println("get task list success: ", result) +} +``` +## 安全组管理 +### 通过VPC ID查询GaiaDB集群 +使用以下代码通过VPC ID查询GaiaDB集群 +```go +result, err := GAIADB_CLIENT.GetClusterByVpcId(vpcId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get cluster by vpcid failed:", err) +} else { + fmt.Println("get cluster by vpcid success: ", result) +} +``` +### 通过Lb ID查询GaiaDB集群 +使用以下代码通过Lb ID查询GaiaDB集群 +```go +result, err := GAIADB_CLIENT.GetClusterByLbId(lbIds) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get cluster by lbids failed:", err) +} else { + fmt.Println("get cluster by lbids success: ", result) +} +``` +## 其他 +### 查询订单信息 +使用以下代码查询订单信息 +```go +result, err := GAIADB_CLIENT.GetOrderInfo(orderId) +re, _ := json.Marshal(result) +fmt.Println(string(re)) +if err != nil { + fmt.Println("get order info failed:", err) +} else { + fmt.Println("get order info success: ", result) +} +``` +# 错误处理 + +GO语言以error类型标识错误,SCS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | GAIADB服务返回的错误 + +用户使用SDK调用GAIADB相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// gaiadbClient 为已创建的GAIADB Client对象 +clusterDetail, err := gaiadbClient.GetClusterDetail(clusterId) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get instance detail success: ", clusterDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向GAIADB发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当GAIADB服务端出现异常时,GAIADB服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[GAIADB错误返回](https://cloud.baidu.com/doc/GaiaDB/s/al84889rz) + diff --git a/bce-sdk-go/doc/HAVIP.md b/bce-sdk-go/doc/HAVIP.md new file mode 100644 index 0000000..085aae9 --- /dev/null +++ b/bce-sdk-go/doc/HAVIP.md @@ -0,0 +1,511 @@ +# HAVIP服务 + +# 概述 + +本文档主要介绍HAVIP GO SDK的使用。在使用本文档前,您需要先了解HAVIP的一些基本知识,并已开通了HAVIP服务。若您还不了解HAVIP,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/sjwvytvh0 )和[操作指南](https://cloud.baidu.com/doc/VPC/s/dlcj263th) 。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[ENDPOINT服务域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw )的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/ )。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云HAVIP,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问HAVIP做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建HAVIP Client + +HAVIP Client是HAVIP服务的客户端,为开发者与HAVIP服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建HAVIP Client + +通过AK/SK方式访问HAVIP,用户可以参考如下代码新建一个HAVIP Client: + +```go +import ( +"github.com/baidubce/bce-sdk-go/services/havip" +) + +func main() { +// 用户的Access Key ID和Secret Access Key +ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + +// 用户指定的Endpoint +ENDPOINT := + +// 初始化一个HAVIPClient +havipClient, err := havip.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为HAVIP的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建HAVIP Client + +**申请STS token** + +HAVIP可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问HAVIP,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建HAVIP Client** + +申请好STS后,可将STS Token配置到HAVIP Client中,从而实现通过STS Token创建HAVIP Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建HAVIP Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/havip" //导入HAVIP服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建HAVIP服务的Client对象,Endpoint使用默认值 + havipClient, err := havip.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create havip client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + havipClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置HAVIP Client时,无论对应HAVIP服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问HAVIP + +HAVIP支持HTTPS传输协议,您可以通过在创建HAVIP Client对象时指定的Endpoint中指明HTTPS的方式,在HAVIP GO SDK中使用HTTPS访问HAVIP服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +havipClient, _ := havip.NewClient(AK, SK, ENDPOINT) +``` + +## 配置HAVIP Client + +如果用户需要配置HAVIP Client的一些细节的参数,可以在创建HAVIP Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问HAVIP服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +//创建HAVIP Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := havip.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := havip.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := havip.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问HAVIP时,创建的HAVIP Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建HAVIP Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 获取公共服务 + +使用以下代码获取公共服务 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +result, err := client.GetServices() + if err != nil { + fmt.Printf("list public services error: %+v\n", err) + return + } +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 创建HAVIP + +使用以下代码可以申请一个HAVIP。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.CreateHaVipArgs{ + Name: "havipGoSdkTest", + Description: "go sdk test", + SubnetId: "sbn-mnnhbyd2tbqr", + PrivateIpAddress: "192.168.1.3", + } +result, err := client.CreateHaVip(args) +if err != nil { + fmt.Printf("create havip error: %+v\n", err) + return +} + +fmt.Println("create havip success, havip: ", result.HaVipId) +``` + + +## 查询HAVIP 列表 + +使用以下代码可以查询HAVIP列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.ListHaVipArgs{ + vpcId: "vpc-rndav7yrmbi6", + MaxKeys: 1000, +} +res, err := client.ListHaVip(args) + if err != nil { + fmt.Printf("list havip error: %+v\n", err) + return + } + // 返回标记查询的起始位置 + fmt.Println("havip list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("havip list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("havip list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("havip list maxKeys: ", result.MaxKeys) + // 获取havip的列表信息 + for _, e := range res.HaVips { + fmt.Println("havip id: ", e.HaVipId) + fmt.Println("havip name: ", e.Name) + fmt.Println("havip description: ", e.Description) + fmt.Println("havip createTime: ", e.CreateTime) + } +``` + +## 查询HAVIP详情 + +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" +result, err := havip.GetHaVipDetail("havip-ied0wq4fs8va") +if err != nil { + fmt.Printf("select havip error: %+v\n", err) + return +} +r, err := json.Marshal(result) +fmt.Println("select havip success", string(r)) +``` + +## 更新HAVIP + +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" +args := &havip.UpdateHaVipArgs{ + HaVipId: "havip-swqx77k5f2cn", + Name: "name", + Description: "description", + } +res, err := client.UpdateHaVip(args) +if err != nil { + fmt.Printf("update havip error: %+v\n", err) + return +} +fmt.Printf("update havip success\n") +``` + +## 删除HAVIP + +使用以下代码可以释放指定的HAVIP。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.DeleteHaVipArgs{ + HaVipId: "havip-swqx77k5f2cn", +} +err := client.DeleteHaVip(args) +if err != nil { + fmt.Printf("delete havip error: %+v\n", err) + return +} + +fmt.Printf("delete havip success\n") +``` + +> 注意: +> - 删除指定HAVIP,被释放的HAVIP无法找回 + +## HAVIP绑定实例 + +使用以下代码可以为HAVIP绑定实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.HaVipInstanceArgs{ + HaVipId: "havip-swqx77k5f2cn", + InstanceIds: []string{ + "eni-xgg3pfhw384n", + }, + InstanceType: "ENI", +} +err := client.HaVipAttachInstance(args) +if err != nil { + fmt.Printf("havip attach instance error: %+v\n", err) + return +} + +fmt.Printf("havip attach instance success\n") +``` + +## HAVIP解绑实例 + +使用以下代码可以为HAVIP解绑实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.HaVipInstanceArgs{ + HaVipId: "havip-swqx77k5f2cn", + InstanceIds: []string{ + "eni-xgg3pfhw384n", + }, + InstanceType: "ENI", +} +err := client.HaVipDetachInstance(args) +if err != nil { + fmt.Printf("havip detach instance error: %+v\n", err) + return +} + +fmt.Printf("havip detach instance success\n") +``` + +## HAVIP绑定公网IP + +使用以下代码可以为HAVIP绑定公网IP。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.HaVipBindPublicIpArgs{ + HaVipId: "havip-swqx77k5f2cn", + PublicIpAddress: "110.242.73.217", +} +err := client.HaVipBindPublicIp(args) +if err != nil { + fmt.Printf("havip bind public ip error: %+v\n", err) + return +} + +fmt.Printf("havip bind public ip success\n") +``` + +## HAVIP解绑公网IP + +使用以下代码可以为HAVIP解绑公网IP。 +```go +// import "github.com/baidubce/bce-sdk-go/services/havip" + +args := &havip.HaVipUnbindPublicIpArgs{ + HaVipId: "havip-swqx77k5f2cn", +} +err := client.HaVipUnbindPublicIp(args) +if err != nil { + fmt.Printf("havip unbind public ip error: %+v\n", err) + return +} + +fmt.Printf("havip unbind public ip success\n") +``` + +# 错误处理 + +GO语言以error类型标识错误,HAVIP支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError |HAVIP服务返回的错误 + +用户使用SDK调用HAVIP相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// havipClient 为已创建的HAVIP Client对象 +args := &havip.ListHaVipArgs{} +result, err := client.ListHaVip(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向HAVIP发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当HAVIP服务端出现异常时,HAVIP服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[HAVIP错误码](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +HAVIP GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +HAVIP GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the HAVIP go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the HAVIP go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/IAM.md b/bce-sdk-go/doc/IAM.md new file mode 100644 index 0000000..0ec7dd6 --- /dev/null +++ b/bce-sdk-go/doc/IAM.md @@ -0,0 +1,941 @@ +# IAM服务 + +# 概述 + +本文档主要介绍普通型IAM GO SDK的使用。在使用本文档前,您需要先了解IAM的一些基本知识。若您还不了解IAM,可以参考[产品描述](https://cloud.baidu.com/doc/IAM/s/xjwvybxhv)和[应用场景](https://cloud.baidu.com/doc/IAM/s/Djwvybxus)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[IAM访问域名](https://cloud.baidu.com/doc/IAM/s/cjwvxnzix)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云IAM,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问IAM做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/#/iam/accesslist) + +## 新建IAM Client + +普通型IAM Client是IAM服务的客户端,为开发者与IAM服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建IAM Client + +通过AK/SK方式访问IAM,用户可以参考如下代码新建一个IAM Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/iam" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 初始化一个IAMClient + iamClient, err := iam.NewClient(AK, SK) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/IAM/s/ojwvynrqn)》。 + +### 使用STS创建IAM Client + +**申请STS token** + +IAM可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问IAM,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建IAM Client** + +申请好STS后,可将STS Token配置到IAM Client中,从而实现通过STS Token创建IAM Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建IAM Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/iam" //导入IAM服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建IAM服务的Client对象,Endpoint使用默认值 + iamClient, err := iam.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create iam client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + iamClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置IAM Client时,无论对应IAM服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问IAM + +IAM支持HTTPS传输协议,您可以通过在创建IAM Client对象时指定的Endpoint中指明HTTPS的方式,在IAM GO SDK中使用HTTPS访问IAM服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/iam" + +ENDPOINT := "https://iam.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +iamClient, _ := iam.NewClientWithEndpoint(AK, SK, ENDPOINT) +``` + +## 配置IAM Client + +如果用户需要配置IAM Client的一些细节的参数,可以在创建IAM Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问IAM服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/iam" + +//创建IAM Client对象 +AK, SK := , +ENDPOINT := "iam.bj.baidubce.com +client, _ := iam.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/iam" + +AK, SK := , +client, _ := iam.NewClient(AK, SK) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/iam" + +AK, SK := , +client, _ := iam.NewClient(AK, SK) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问IAM时,创建的IAM Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建IAM Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +# 主要接口 + +## 用户管理 + +### 创建用户 +通过以下代码可以创建子用户 + +```go + + name := "test-user-sdk-go" + args := &api.CreateUserArgs{ + Name: name, + Description: "description", + } + + result, err := client.CreateUser(args) + if err != nil { + fmt.Println("Create iam user failed", err) + } else { + fmt.Println("Create iam user success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[CreateUser创建用户](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7) + +### 查询用户 +通过以下代码可以查询单个子用户 +```go + name := "test-user-sdk-go" + result, err := client.GetUser(name) + if err != nil { + fmt.Println("Get iam user failed", err) + } else { + fmt.Println("Get iam user success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[GetUser查询用户](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E6%9F%A5%E8%AF%A2%E7%94%A8%E6%88%B7) + +### 更新用户 +通过以下代码可以更新子用户 + +```go + name := "test-user-sdk-go" + args := &api.UpdateUserArgs{ + Description: "newDescription", + } + + result, err := client.UpdateUser(name, args) + if err != nil { + fmt.Println("Update iam user failed", err) + } else { + fmt.Println("Update iam user success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[UpdateUser更新用户](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7) + +### 列举用户 +通过以下代码可以列举子用户 +```go + result, err := client.ListUser() + if err != nil { + fmt.Println("List iam user failed", err) + } else { + fmt.Println("List iam user success", result) + } +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[ListUser创建用户](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%97%E4%B8%BE%E7%94%A8%E6%88%B7) + +### 删除用户 +通过以下代码可以更新子用户 + +```go + name := "test-user-sdk-go" + err = client.DeleteUser(name) + if err != nil { + fmt.Println("Delete iam user failed", err) + } else { + fmt.Println("Delete iam user success", name) + } +``` + +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[DeleteUser删除用户](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%A0%E9%99%A4%E7%94%A8%E6%88%B7) + + +### 配置用户控制台登录 +通过以下代码可以配置用户的控制台登录,为其配置登录密码、开启登录MFA、配置第三方账号绑定等 + +```go + name := "test-user-sdk-go-login-profile" + args := &api.UpdateUserLoginProfileArgs{ + Password: "1@3Qwe4f", + EnabledLoginMfa: false, + LoginMfaType: "PHONE", + } + + result, err := client.UpdateUserLoginProfile(name, args) + if err != nil { + fmt.Println("Update iam user login profile failed", err) + } else { + fmt.Println("Update iam user login profile success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[UpdateUserLoginProfile配置用户控制台登录](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E9%85%8D%E7%BD%AE%E7%94%A8%E6%88%B7%E7%9A%84%E6%8E%A7%E5%88%B6%E5%8F%B0%E7%99%BB%E5%BD%95) + +### 查询控制台登录配置 +通过以下代码可以查询用户的控制台登录配置 +```go + name := "test-user-sdk-go-login-profile" + result, err := client.GetUserLoginProfile(name) + if err != nil { + fmt.Println("Get iam user login profile failed", err) + } else { + fmt.Println("Get iam user login profile success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[GetUserLoginProfile查询用户控制台登录](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E6%9F%A5%E8%AF%A2%E6%8E%A7%E5%88%B6%E5%8F%B0%E7%99%BB%E5%BD%95%E9%85%8D%E7%BD%AE) + +### 关闭控制台登录配置 +关闭用户的控制台登录配置,即关闭用户的控制台登录 +```go + name := "test-user-sdk-go-login-profile" + err = client.DeleteUserLoginProfile(name) + if err != nil { + fmt.Println("Delete iam user login profile failed", err) + } else { + fmt.Println("Delete iam user login profile success", name) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[DeleteUserLoginProfile关闭用户控制台登录](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%85%B3%E9%97%AD%E6%8E%A7%E5%88%B6%E5%8F%B0%E7%99%BB%E5%BD%95%E9%85%8D%E7%BD%AE) + +### 创建用户的AccessKey +通过以下代码为用户创建一组AccessKey访问密钥 + +```go + name := "test-user-sdk-go-accessKey" + result, err := client.CreateAccessKey(name) + if err != nil { + fmt.Println("Create accessKey failed", err) + } else { + fmt.Println("Create accessKey success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[创建用户的AccessKey](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7%E7%9A%84accesskey) + +### 禁用用户的AccessKey +通过以下代码为禁用用户的AccessKey +```go + name := "test-user-sdk-go-accessKey" + accessKeyId := "" + result, err := client.DisableAccessKey(name, accessKeyId) + if err != nil { + fmt.Println("Disable accessKey failed", err) + } else { + fmt.Println("Disable accessKey success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[禁用用户的AccessKey](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%9B%E5%BB%BA%E7%94%A8%E6%88%B7%E7%9A%84accesskey) + +### 启用用户的AccessKey +通过以下代码为启用用户的AccessKey +```go + name := "test-user-sdk-go-accessKey" + accessKeyId := "" + result, err := client.EnableAccessKey(name, accessKeyId) + if err != nil { + fmt.Println("Enable accessKey failed", err) + } else { + fmt.Println("Enable accessKey success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[启用用户的AccessKey](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%90%AF%E7%94%A8%E7%94%A8%E6%88%B7%E7%9A%84accesskey) + +### 删除用户的AccessKey +删除用户的指定一组AccessKey访问密钥 +```go + name := "test-user-sdk-go-accessKey" + accessKeyId := "" + err = client.DeleteAccessKey(name, accessKeyId) + if err != nil { + fmt.Println("Delete accessKey failed", err) + } else { + fmt.Println("Delete accessKey success", accessKeyId) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[删除用户的AccessKey](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%A0%E9%99%A4%E7%94%A8%E6%88%B7%E7%9A%84accesskey) + +### 列举用户的AccessKey +列举用户的全部AccessKey访问密钥 +```go + name := "test-user-sdk-go-accessKey" + result, err := client.ListAccessKey(name) + if err != nil { + fmt.Println("List accessKey failed", err) + } else { + fmt.Println("List accessKey success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举用户的AccessKey](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E5%88%97%E4%B8%BE%E7%94%A8%E6%88%B7%E7%9A%84accesskey) + + +### 创建组 +通过以下代码创建组 +```go + name := "test_group_sdk_go" + args := &api.CreateGroupArgs{ + Name: name, + Description: name, + } + + result, err := client.CreateGroup(args) + if err != nil { + fmt.Println("Create group failed", err) + } else { + fmt.Println("Create group success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[创建组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E5%88%9B%E5%BB%BA%E7%BB%84) + + +### 查询组 +通过以下代码查询组 +```go + name := "test_group_sdk_go" + result, err := client.GetGroup(name) + if err != nil { + fmt.Println("Get group failed", err) + } else { + fmt.Println("Get group success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[查询组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E6%9F%A5%E8%AF%A2%E7%BB%84) + + +### 更新组 +通过以下代码更新组 +```go + name := "test_group_sdk_go" + args := &api.UpdateGroupArgs{ + Description: "newDes", + } + result, err := client.UpdateGroup(name, args) + if err != nil { + fmt.Println("Update group failed", err) + } else { + fmt.Println("Update group success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[更新组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E6%9B%B4%E6%96%B0%E7%BB%84) + +### 删除组 +通过以下代码删除组 +```go + name := "test_group_sdk_go" + err = client.DeleteGroup(name) + if err != nil { + fmt.Println("Delete group failed", err) + } else { + fmt.Println("Delete group success", name) + } + +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[删除组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E5%88%A0%E9%99%A4%E7%BB%84) + +### 列举组 +通过以下代码删除组 +```go + result, err := client.ListGroup() + if err != nil { + fmt.Println("Delete group failed", err) + } else { + fmt.Println("Delete group success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E5%88%97%E4%B8%BE%E7%BB%84) + +### 添加用户到组 +通过以下代码添加用户到组 +```go + userName := "test_user_sdk_go" + groupName := "test_user_sdk_go" + err = client.AddUserToGroup(userName, groupName) + if err != nil { + fmt.Println("Add user to group failed", err) + } else { + fmt.Println("Add user to group success", userName) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[添加用户到组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E6%B7%BB%E5%8A%A0%E7%94%A8%E6%88%B7%E5%88%B0%E7%BB%84) + + +### 从组内移除用户 +通过以下代码从组内移除用户 +```go + userName := "test_user_sdk_go" + groupName := "test_user_sdk_go" + err = client.DeleteUserFromGroup(userName, groupName) + if err != nil { + fmt.Println("Add user to group failed", err) + } else { + fmt.Println("Add user to group success", userName) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[从组内移除用户](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E4%BB%8E%E7%BB%84%E5%86%85%E7%A7%BB%E9%99%A4%E7%94%A8%E6%88%B7) + +### 列举用户的组 +通过以下代码列举用户的组 +```go + userName := "test_user_sdk_go" + result, err := client.ListGroupsForUser(userName) + if err != nil { + fmt.Println("List groups for user failed", err) + } else { + fmt.Println("List groups for user success", result) + } + +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举用户的组](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E5%88%97%E4%B8%BE%E7%94%A8%E6%88%B7%E7%9A%84%E7%BB%84) + +### 列举组内用户 +通过以下代码列举组内用户 +```go + groupName := "test_user_sdk_go" + result, err := client.ListUsersInGroup(groupName) + if err != nil { + fmt.Println("List user in group failed", err) + } else { + fmt.Println("List user in group success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举组内用户](https://cloud.baidu.com/doc/IAM/s/ljx35h8lx#%E5%88%97%E4%B8%BE%E7%BB%84%E5%86%85%E7%94%A8%E6%88%B7) + +### 创建角色 +通过以下代码创建角色 +```go + roleName := "test_role_sdk_go" + args := &api.CreateRoleArgs{ + Name: roleName, + Description: "description", + AssumeRolePolicyDocument: "{\"version\":\"v1\",\"accessControlList\":[{\"service\":\"bce:iam\",\"permission\"" + + ":[\"AssumeRole\"],\"region\":\"*\",\"grantee\":[{\"id\":\"grantee-id\"}],\"effect\":\"Allow\"}]}", + } + + result, err := client.CreateRole(args) + if err != nil { + fmt.Println("Create role failed", err) + } else { + fmt.Println("Create role success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[创建角色](https://cloud.baidu.com/doc/IAM/s/ek5eq1zp1) + +### 查询角色 +通过以下代码查询角色 +```go + roleName := "test_role_sdk_go" + result, err := client.GetRole(roleName) + if err != nil { + fmt.Println("Get role failed", err) + } else { + fmt.Println("Get role success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[查询角色](https://cloud.baidu.com/doc/IAM/s/ek5eq1zp1#%E6%9F%A5%E8%AF%A2%E8%A7%92%E8%89%B2) + +### 更新角色 +通过以下代码查询角色 +```go + args := &api.UpdateRoleArgs{ + Description: "newDescription", + AssumeRolePolicyDocument: "{\"version\":\"v1\",\"accessControlList\":[{\"service\":\"bce:iam\",\"permission\"" + + ":[\"AssumeRole\"],\"region\":\"*\",\"grantee\":[{\"id\":\"grantee-id\"}],\"effect\":\"Allow\"}]}", + } + + roleName := "test_role_sdk_go" + result, err := client.UpdateRole(roleName, args) + if err != nil { + fmt.Println("Update role failed", err) + } else { + fmt.Println("Update role success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[更新角色](https://cloud.baidu.com/doc/IAM/s/ek5eq1zp1#%E6%9B%B4%E6%96%B0%E8%A7%92%E8%89%B2) + +### 删除角色 +通过以下代码查询角色 +```go + roleName := "test_role_sdk_go" + err = client.DeleteRole(roleName) + if err != nil { + fmt.Println("Delete role failed", err) + } else { + fmt.Println("Delete role success", roleName) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[删除角色](https://cloud.baidu.com/doc/IAM/s/ek5eq1zp1#%E5%88%A0%E9%99%A4%E8%A7%92%E8%89%B2) + +### 列举角色 +通过以下代码列举角色 +```go + result, err := client.ListRole() + if err != nil { + fmt.Println("List role failed", err) + } else { + fmt.Println("List role success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举角色](https://cloud.baidu.com/doc/IAM/s/ek5eq1zp1#%E5%88%97%E4%B8%BE%E8%A7%92%E8%89%B2) + +### 创建策略 +通过以下代码创建策略 +```go + +name := "test_sdk_go_policy" +args := &api.CreatePolicyArgs{ + Name: name, + Description: "description", + Document: "{\"accessControlList\": [{\"region\":\"bj\",\"service\":\"bcc\"," + +"\"resource\":[\"*\"],\"permission\":[\"*\"],\"effect\":\"Allow\"}]}", +} + +result, err := client.CreatePolicy(args) +if err != nil { + fmt.Println("Update policy failed", err) +} else { + fmt.Println("Update policy success", result) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[创建策略](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%9B%E5%BB%BA%E7%AD%96%E7%95%A5) + +### 查询策略 +通过以下代码查询策略 +```go + name := "test_sdk_go_policy" + policyType := "Custom" + result, err := client.GetPolicy(name, policyType) + if err != nil { + fmt.Println("Update policy failed", err) + } else { + fmt.Println("Update policy success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[创建策略](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%9B%E5%BB%BA%E7%AD%96%E7%95%A5) + +### 删除策略 +通过以下代码删除策略 +```go + name := "test_sdk_go_policy" + err = client.DeletePolicy(name) + if err != nil { + fmt.Println("List policy failed", err) + } else { + fmt.Println("List policy success", name) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[删除策略](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%A0%E9%99%A4%E7%AD%96%E7%95%A5) + + +### 列举策略 +通过以下代码列举策略 +```go + name := "test_sdk_go_policy" + policyType := "Custom" + result, err := client.ListPolicy(name, policyType) + if err != nil { + fmt.Println("List policy failed", err) + } else { + fmt.Println("List policy success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举策略](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%97%E4%B8%BE%E7%AD%96%E7%95%A5) + +### 关联用户权限 +通过以下代码关联用户权限 +```go + userName := "test_sdk_go_user" + policyName := "test_sdk_go_policy" + args := &api.AttachPolicyToUserArgs{ + UserName: userName, + PolicyName: policyName, + } + err = client.AttachPolicyToUser(args) + if err != nil { + fmt.Println("Attach policy to user failed", err) + } else { + fmt.Println("Attach policy to user success", args) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[关联用户权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%85%B3%E8%81%94%E7%94%A8%E6%88%B7%E6%9D%83%E9%99%90) + +### 解除用户权限 +通过以下代码解除用户权限 +```go + userName := "test_sdk_go_user" + policyName := "test_sdk_go_policy" + args := &api.DetachPolicyFromUserArgs{ + UserName: userName, + PolicyName: policyName, + } + err = client.DetachPolicyFromUser(args) + if err != nil { + fmt.Println("Detach policy to user failed", err) + } else { + fmt.Println("Detach policy to user success", args) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[解除用户权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E8%A7%A3%E9%99%A4%E7%94%A8%E6%88%B7%E6%9D%83%E9%99%90) + +### 列举用户的权限 +通过以下代码列举用户的权限 +```go + userName := "test_sdk_go_user" + result, err := client.ListUserAttachedPolicies(userName) + if err != nil { + fmt.Println("List user attached policy failed", err) + } else { + fmt.Println("List user attached policy success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举用户的权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%97%E4%B8%BE%E7%94%A8%E6%88%B7%E7%9A%84%E6%9D%83%E9%99%90) + +### 关联组权限 +通过以下代码关联组权限 +```go + groupName := "test_sdk_go_group" + policyName := "test_sdk_go_policy" + args := &api.AttachPolicyToGroupArgs{ + GroupName: groupName, + PolicyName: policyName, + } + err = client.AttachPolicyToGroup(args) + if err != nil { + fmt.Println("Attach policy to group failed", err) + } else { + fmt.Println("Attach policy to group success", args) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[关联组权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%85%B3%E8%81%94%E7%BB%84%E6%9D%83%E9%99%90) + +### 解除组权限 +通过以下代码解除组权限 +```go + groupName := "test_sdk_go_group" + policyName := "test_sdk_go_policy" + args := &api.DetachPolicyFromGroupArgs{ + GroupName: groupName, + PolicyName: policyName, + } + err = client.DetachPolicyFromGroup(args) + if err != nil { + fmt.Println("Detach policy to group failed", err) + } else { + fmt.Println("Detach policy to group success", args) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[解除组权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E8%A7%A3%E9%99%A4%E7%BB%84%E6%9D%83%E9%99%90) + +### 列举组权限 +通过以下代码列举组权限 +```go + groupName := "test_sdk_go_group" + result, err := client.ListGroupAttachedPolicies(groupName) + if err != nil { + fmt.Println("List group attached policy failed", err) + } else { + fmt.Println("List group attached policy success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举组权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%97%E4%B8%BE%E7%BB%84%E7%9A%84%E6%9D%83%E9%99%90) + +### 关联角色权限 +通过以下代码关联角色权限 +```go + roleName := "test_sdk_go_group" + policyName := "test_sdk_go_policy" + args := &api.AttachPolicyToRoleArgs{ + RoleName: roleName, + PolicyName: policyName, + } + err = client.AttachPolicyToRole(args) + if err != nil { + fmt.Println("Attach policy to role failed", err) + } else { + fmt.Println("Attach policy to role success", args) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[关联角色权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%85%B3%E8%81%94%E8%A7%92%E8%89%B2%E6%9D%83%E9%99%90) + +### 解除角色权限 +通过以下代码关联角色权限 +```go + roleName := "test_sdk_go_group" + policyName := "test_sdk_go_policy" + args := &api.DetachPolicyToRoleArgs{ + RoleName: roleName, + PolicyName: policyName, + } + err = client.DetachPolicyFromRole(args) + if err != nil { + fmt.Println("Detach policy to role failed", err) + } else { + fmt.Println("Detach policy to role success", args) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[解除角色权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E8%A7%A3%E9%99%A4%E8%A7%92%E8%89%B2%E6%9D%83%E9%99%90) + +### 列举角色的权限 +通过以下代码列举角色权限 +```go + roleName := "test_sdk_go_group" + result, err := client.ListRoleAttachedPolicies(roleName) + if err != nil { + fmt.Println("List role attached policy failed", err) + } else { + fmt.Println("List role attached policy success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[列举角色的权限](https://cloud.baidu.com/doc/IAM/s/Wjx35jxes#%E5%88%97%E4%B8%BE%E8%A7%92%E8%89%B2%E7%9A%84%E6%9D%83%E9%99%90) + +### 修改子用户操作保护 +通过以下代码修改子用户操作保护 +```go + userName := "test-user-sdk-go-switch-operation-mfa" + enableMfa := true + mfaType := "PHONE,TOTP" + args := &api.UserSwitchMfaArgs{ + UserName: userName, + EnabledMfa: enableMfa, + MfaType: mfaType, + } + err := IAM_CLIENT.UserOperationMfaSwitch(args) + if err != nil { + fmt.Println("switch user mfa failed", err) + } else { + fmt.Println("switch user mfa success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[UserOperationMfaSwitch修改子用户操作保护](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E4%BF%AE%E6%94%B9%E5%AD%90%E7%94%A8%E6%88%B7%E6%93%8D%E4%BD%9C%E4%BF%9D%E6%8A%A4) + + +### 修改子用户密码 +通过以下代码修改子用户密码 +```go + userName := "test-user-name-sdk-go-sub-update" + Password := "Baidu@123" + args := &api.UpdateSubUserArgs{ + Password: Password, + } + res, err := IAM_CLIENT.SubUserUpdate(userName, args) + if err != nil { + fmt.Println("update sub user failed", err) + } else { + fmt.Println("update sub user success", result) + } +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考IAM API 文档[SubUserUpdate修改子用户密码](https://cloud.baidu.com/doc/IAM/s/mjx35fixq#%E4%BF%AE%E6%94%B9%E5%AD%90%E7%94%A8%E6%88%B7%E5%AF%86%E7%A0%81) + +# 错误处理 + +GO语言以error类型标识错误,IAM支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | IAM服务返回的错误 + +## 客户端异常 + +客户端异常表示客户端尝试向IAM发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当IAM服务端出现异常时,IAM服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[IAM错误返回](https://cloud.baidu.com/doc/IAM/s/Rjx4d0rxo) + +# 版本变更记录 + +## v0.9.11 [2022-10-13] + +首次发布: + +- 创建、查看、列表、更新、删除IAM用户 +- 配置、查询、关闭用户控制台配置 +- 创建、查看、列表、删除、启用、禁用AccessKey +- 创建、查看、列表、更新、删除IAM用户组 +- 创建、列表、列表、更新、删除角色 +- 创建、查看、列表、更新、删除、关联用户权限、解除用户权限、列举用户权限、关联组权限、解除组权限、列举组权限、关联角色权限、解除角色权限、列举角色的权限 + +## v0.9.12 [2023-02-13] + +- 修改子用户的操作保护 +- 修改子用户密码 diff --git a/bce-sdk-go/doc/LBDC.md b/bce-sdk-go/doc/LBDC.md new file mode 100644 index 0000000..b514d4d --- /dev/null +++ b/bce-sdk-go/doc/LBDC.md @@ -0,0 +1,514 @@ +# LBDC服务 + +# 概述 + +本文档主要介绍负载均衡专属集群LBDC GO SDK的使用。在使用本文档前,您需要先了解BLB的一些基本知识。若您还不了解BLB,可以参考[产品描述](https://cloud.baidu.com/doc/BLB/s/Ajwvxno34)和[入门指南](https://cloud.baidu.com/doc/BLB/s/cjwvxnr91)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[BLB访问域名](https://cloud.baidu.com/doc/BLB/s/cjwvxnzix)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云LBDC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问LBDC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建负载均衡专属集群LBDC Client + +LBDC Client是负载均衡专属集群LBDC服务的客户端,为开发者与LBDC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建负载均衡专属集群LBDC Client + +通过AK/SK方式访问LBDC,用户可以参考如下代码新建一个LBDC Client: +```go +import ( + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个LBDC Client + lbdcClient, err := lbdc.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/BLB/s/ojwvynrqn)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为LBDC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`blb.bj.baidubce.com`。 + +### 使用STS创建LBDC Client + +**申请STS token** + +LBDC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问LBDC,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建LBDC Client** + +申请好STS后,可将STS Token配置到LBDC Client中,从而实现通过STS Token创建LBDC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建LBDC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/lbdc" //导入LBDC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建LBDC服务的Client对象,Endpoint使用默认值 + lbdcClient, err := lbdc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create lbdc client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + lbdcClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置LBDC Client时,无论对应LBDC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问LBDC + +LBDC支持HTTPS传输协议,您可以通过在创建LBDC Client对象时指定的Endpoint中指明HTTPS的方式,在LBDC GO SDK中使用HTTPS访问LBDC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +ENDPOINT := "https://lbdc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +lbdcClient, _ := lbdc.NewClient(AK, SK, ENDPOINT) +``` + +## 配置LBDC Client + +如果用户需要配置LBDC Client的一些细节的参数,可以在创建LBDC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问LBDC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +//创建LBDC Client对象 +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := lbdc.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := lbdc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +AK, SK := , +ENDPOINT := "blb.bj.baidubce.com" +client, _ := lbdc.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问LBDC时,创建的LBDC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建LBDC Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +负载均衡专属集群提供性能可控、资源独享、物理资源隔离的专属负载均衡服务,满足超高性能和独占资源需求。 + +## 实例管理 + +### 创建LBDC + +通过以下代码,可以创建LBDC +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +args := &CreateLbdcArgs{ + ClientToken: ClientToken(), + Name: Name, + Type: Type, + CcuCount: CcuCount, + Description: &Description, + Billing: &Billing{ + PaymentTiming: PaymentTiming, + Reservation: &Reservation{ + ReservationLength: ReservationLength, + }, + }, + RenewReservation: &Reservation{ + ReservationLength: ReservationLength, + }, +} +res, err := client.CreateLbdc(args) +ExpectEqual(t.Errorf, nil, err) +e, err := json.Marshal(res) +if err != nil { + fmt.Printf("create lbdc error: %+v\n", err) + return +} +fmt.Printf("create lbdc success,lbdcId is: %+v",res.Id) +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考LBDC API 文档[创建LBDC](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#%E5%88%9B%E5%BB%BAlbdc) + +### 升级LBDC + +通过以下代码,可以升级LBDC +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +args := &UpgradeLbdcArgs{ + ClientToken: ClientToken(), + Id: Id, + CcuCount: CcuCount, +} +err := client.UpgradeLbdc(args) +if err != nil { + fmt.Printf("upgrade lbdc error: %+v\n", err) + return +} +fmt.Printf("upgrade lbdc success") +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考LBDC API 文档[升级LBDC](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#%E5%8D%87%E7%BA%A7lbdc) + +### 续费LBDC + +通过以下代码,可以续费LBDC +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +args := &RenewLbdcArgs{ + ClientToken: ClientToken(), + Id: Id, + Billing: &BillingForRenew{ + Reservation: &Reservation{ + ReservationLength: ReservationLength, + }, + }, +} +err := client.RenewLbdc(args) +if err != nil { + fmt.Printf("renew lbdc error: %+v\n", err) + return +} +fmt.Printf("renew lbdc success") +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考LBDC API 文档[续费LBDC](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#%E7%BB%AD%E8%B4%B9lbdc) + +### 查询LBDC列表 + +通过以下代码,可以查询LBDC列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +args := &ListLbdcArgs{ + Id: Id, + Name: Name, +} +res, err := client.ListLbdc(args) +if err != nil { + fmt.Printf("get lbdc list error: %+v\n", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("lbdc list marker: ", res.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("lbdc list isTruncated: ", res.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("lbdc list nextMarker: ", res.NextMarker) +// 每页包含的最大数量 +fmt.Println("lbdc list maxKeys: ", res.MaxKeys) +// 获取lbdc的具体信息 +for _, v := range result.ClusterList { + // 集群id + fmt.Println("Cluster id: ", v.Id) + // 集群名称 + fmt.Println("Cluster name: ", v.Name) + // 集群类型 + fmt.Println("Cluster type: ", v.Type) + // 集群状态 + fmt.Println("Cluster status: ", v.Status) + // 集群性能容量 + fmt.Println("Cluster ccuCount: ", v.CcuCount) + // 集群创建时间 + fmt.Println("Cluster createTime: ", v.CreateTime) + // 集群失效时间 + fmt.Println("Cluster expireTime: ", v.ExpireTime) + // 描述 + fmt.Println("Cluster description: ", v.Description) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考LBDC API 文档[查询LBDC列表](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#lbdc%E5%88%97%E8%A1%A8) + +### 查询LBDC详情 + +通过以下代码,可以查询LBDC详情 +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +res, err := client.GetLbdcDetail(lbdcId) +if err != nil { + fmt.Printf("get lbdc detail error: %+v\n", err) + return +} + +// 集群id +fmt.Println("lbdc id: ", res.VpnId) +// 集群名称 +fmt.Println("lbdc name: ", res.Name) +// 集群类型 +fmt.Println("lbdc type: ", res.Type) +// 集群状态 +fmt.Println("lbdc status: ", res.Status) +// 集群性能容量 +fmt.Println("lbdc ccuCount: ", res.CcuCount) +// 集群创建时间 +fmt.Println("lbdc createTime: ", res.CreateTime) +// 集群失效时间 +fmt.Println("lbdc expireTime: ", res.ExpireTime) +// 集群并发连接数 +fmt.Println("lbdc totalConnectCount: ", res.TotalConnectCount) +// 集群网络输入带宽 +fmt.Println("lbdc networkInBps: ", res.NetworkInBps) +// 集群网络输出带宽 +fmt.Println("lbdc networkOutBps: ", res.NetworkOutBps) + +// if 4 layers +// 集群新建连接速度 +fmt.Println("lbdc newConnectCps: ", res.NewConnectCps) + +// if 7 layers +// 集群https的qps +fmt.Println("lbdc httpsQps: ", res.HttpsQps) +// 集群http的qps +fmt.Println("lbdc httpQps: ", res.HttpQps) +// 集群http新建速度 +fmt.Println("lbdc httpNewConnectCps: ", res.HttpNewConnectCps) +// 集群https新建速度 +fmt.Println("lbdc httpsNewConnectCps: ", res.HttpsNewConnectCps) +// 集群ssl新建速度 +fmt.Println("lbdc sslNewConnectCps: ", res.SslNewConnectCps) +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考LBDC API 文档[LBDC详情](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#lbdc%E8%AF%A6%E6%83%85) + +### 更新LBDC + +通过以下代码,可以更新LBDC名称或者描述 +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +args := &UpdateLbdcArgs{ + ClientToken: ClientToken(), + Id: Id, + UpdateLbdcBody: &UpdateLbdcBody{ + Name: &Name, + Description: &Description, + }, +} +err := client.UpdateLbdc(args) +if err != nil { + fmt.Printf("update lbdc error: %+v\n", err) + return +} +fmt.Printf("update lbdc success") +``` +> **提示:** +> 1. 名称和描述都可以为空 +> 2. 注意名称和描述是指针类型 +> 3. 详细的参数配置及限制条件,可以参考LBDC API 文档[更新LBDC](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#%E6%9B%B4%E6%96%B0lbdc) + +### 查询LBDC关联的BLB列表 + +通过以下代码,可以查询LBDC关联的BLB列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/lbdc" + +res, err := client.GetBoundBlBListOfLbdc(lbdcId) +if err != nil { + fmt.Printf("get bound blb list of lbdc error: %+v\n", err) + return +} + +// 获取lbdc关联的BLB的具体信息 +for _, v := range result.BlbList { + // 负载均衡id + fmt.Println("BLB id: ", v.BlbId) + // blb名称 + fmt.Println("BLB name: ", v.Name) + // blb状态 + fmt.Println("BLB status: ", v.Status) + // blb类型 + fmt.Println("BLB type: ", v.BlbType) + // 公网ip + fmt.Println("BLB publicIp: ", v.PublicIp) + // eip线路类型 + fmt.Println("BLB eipRouteType: ", v.EipRouteType) + // 带宽 + fmt.Println("BLB bandwidth: ", v.Bandwidth) + // 内网ip地址 + fmt.Println("BLB address: ", v.Address) + // ipv6地址 + fmt.Println("BLB ipv6: ", v.Ipv6) + // vpcId + fmt.Println("BLB vpcId: ", v.VpcId) + // 子网id + fmt.Println("BLB subnetId: ", v.SubnetId) +} +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考LBDC API 文档[查询LBDC关联的BLB列表](https://cloud.baidu.com/doc/BLB/s/6kszzygx4#lbdc%E5%85%B3%E8%81%94%E7%9A%84blb%E5%88%97%E8%A1%A8) + + +# 错误处理 + +GO语言以error类型标识错误,LBDC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | LBDC服务返回的错误 + +用户使用SDK调用LBDC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// client 为已创建的LBDC Client对象 +lbdcDetail, err := client.GetLbdcDetail(lbdcId) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get lbdc detail success: ", lbdcDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向LBDC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当LBDC服务端出现异常时,LBDC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[BLB错误返回](https://cloud.baidu.com/doc/BLB/s/Djwvxnzw6) + +# 版本变更记录 + +## v1.0.0 [2022-09-21] + +首次发布: + + - 创建、升级、续费、查看、列表、更新LBDC实例,查LBDC关联的BLB列表 + + diff --git a/bce-sdk-go/doc/LOCALDNS.md b/bce-sdk-go/doc/LOCALDNS.md new file mode 100644 index 0000000..753cda7 --- /dev/null +++ b/bce-sdk-go/doc/LOCALDNS.md @@ -0,0 +1,420 @@ +# LD服务 + +# 概述 + +本文档主要介绍LD(Local DNS) GO SDK的使用。在使用本文档前,您需要先了解LD的一些基本知识,并已开通了LD服务。若您还不了解LD,可以参考[产品描述](https://cloud.baidu.com/doc/DNS/s/Ajwvywvx3 )和[操作指南](https://cloud.baidu.com/doc/DNS/s/yjxkakdj4) 。 + +# 初始化 + +## 确认Endpoint + +内网DNS API 的服务域名为:privatezone.baidubce.com + +API支持HTTP和HTTPS两种调用方式。为了提升数据的安全性,建议通过HTTPS调用。 + + +## 获取密钥 + +要使用百度云LD,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问LD做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建LD Client + +LD Client是LD服务的客户端,为开发者与LD服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建LD Client + +通过AK/SK方式访问LD,用户可以参考如下代码新建一个LD Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/localDns" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个LDClient + ldClient, err := ld.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为LD的服务地址。 + +### 使用STS创建LD Client + +**申请STS token** + +LD可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问LD,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建LD Client** + +申请好STS后,可将STS Token配置到LD Client中,从而实现通过STS Token创建LD Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建LD Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/localDns" //导入LD服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建LD服务的Client对象,Endpoint使用默认值 + ldClient, err := ld.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "privatezone.baidubce.com") + if err != nil { + fmt.Println("create localDns client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + ldClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置LD Client时,STS的Endpoint需配置为http://sts.bj.baidubce.com。 + +# 配置HTTPS协议访问LD + +LD支持HTTPS传输协议,您可以通过在创建LD Client对象时指定的Endpoint中指明HTTPS的方式,在LD GO SDK中使用HTTPS访问LD服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/localDns" + +ENDPOINT := "https://privatezone.baidubce.com " //指明使用HTTPS协议 +AK, SK := , +ldClient, _ := ld.NewClient(AK, SK, ENDPOINT) +``` + +## 配置LD Client + +如果用户需要配置LD Client的一些细节的参数,可以在创建LD Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问LD服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/localDns" + +//创建LD Client对象 +AK, SK := , +ENDPOINT := "privatezone.baidubce.com" +client, _ := ld.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/localDns" + +AK, SK := , +ENDPOINT := "privatezone.baidubce.com" +client, _ := ld.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/localDns" + +AK, SK := , +ENDPOINT := "privatezone.baidubce.com" +client, _ := ld.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问LD时,创建的LD Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建LD Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 创建PrivateZone + +```go +args := &CreatePrivateZoneRequest{ + ZoneName: "sdkLd.com", + } +result, err := LdClient.CreatePrivateZone(args) +ExpectEqual(t.Errorf, nil, err) +ZoneId := result.ZoneId +log.Debug(ZoneId) +``` + +## 删除PrivateZone + +```go +err := LdClient.DeletePrivateZone("zone-mk2guy4qxd7c") +ExpectEqual(t.Errorf, nil, err) +``` + + +## 查询PrivateZone列表 + +```go +args := &ListPrivateZoneRequest{ + Marker: "zone-mk2guy4qxd7c", +} +result, err := LdClient.ListPrivateZone(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 查询PrivateZone详情 + +```go +result, err := LdClient.GetPrivateZone("zone-mk2guy4qxd7c") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 关联VPC + +```go +args := &BindVpcRequest{ + Region: "bj", + VpcIds: []string{"vpc-cxvqgxipk36r", "vpc-0n1hhh8759b0"}, +} +err := LdClient.BindVpc("zone-mk2guy4qxd7c", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 解关联VPC + +```go +args := &UnbindVpcRequest{ + Region: "bj", + VpcIds: []string{"vpc-cxvqgxipk36r", "vpc-0n1hhh8759b0"}, +} +err := LdClient.UnbindVpc("zone-mk2guy4qxd7c", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 添加解析记录 + +```go +args := &AddRecordRequest{ + Rr: "www", + Type: "A", + Value: "192.168.1.1", + } +result, err := LdClient.AddRecord("zone-mk2guy4qxd7c", args) +ExpectEqual(t.Errorf, nil, err) +RecordId := result.RecordId +log.Debug(RecordId) +``` + +## 修改解析记录 + +```go +args := &UpdateRecordRequest{ + Rr: "www", + Type: "A", + Value: "192.168.1.2", + } +err := LdClient.UpdateRecord("rc-jih8hd5s", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 删除解析记录 + +```go +err := LdClient.DeleteRecord("rc-jih8hd5s") +ExpectEqual(t.Errorf, nil, err) +``` + +## 查询解析记录列表 + +```go +result, err := LdClient.ListRecord("zone-mk2guy4qxd7c") +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +log.Debug(string(r)) +``` + +## 开启解析记录 + +```go +err := LdClient.EnableRecord("rc-jih8hd5s", args) +ExpectEqual(t.Errorf, nil, err) +``` + +## 暂停解析记录 + +```go +err := LdClient.DisableRecord("rc-jih8hd5s", args) +ExpectEqual(t.Errorf, nil, err) +``` + +# 错误处理 + +GO语言以error类型标识错误,LD支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | LD服务返回的错误 + +用户使用SDK调用LD相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +args := &ListPrivateZoneRequest{ + Marker: "zone-mk2guy4qxd7c", +} +result, err := LdClient.ListPrivateZone(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向LD发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当LD服务端出现异常时,LD服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[LD错误码](https://cloud.baidu.com/doc/DNS/s/lkk5elv58) + +## SDK日志 + +LD GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +LD GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the LD go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the LD go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/MCP.md b/bce-sdk-go/doc/MCP.md new file mode 100644 index 0000000..96e678c --- /dev/null +++ b/bce-sdk-go/doc/MCP.md @@ -0,0 +1,894 @@ +# MCP服务 + +# 概述 + +本文档主要介绍MCP GO SDK的使用。在使用本文档前,您需要先了解MCP的一些基本知识,并已开通了MCP服务。若您还不了解MCP,可以参考[产品描述](https://cloud.baidu.com/doc/MCT/s/9jwvz4hes)和[入门指南](https://cloud.baidu.com/doc/MCT/s/mkd8ii2ck)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[使用须知](https://cloud.baidu.com/doc/MCT/s/Sjwvz5hq5)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/Regions.html)。 + +目前支持“华北-北京”、“华南-广州”和“华东-苏州”三个区域。北京区域:`http://media.bj.baidubce.com`,广州区域:`http://media.gz.baidubce.com`,苏州区域:`http://media.su.baidubce.com`。对应信息为: + +| 访问区域 | 对应Endpoint | +| -------- | --------------------- | +| BJ | media.bj.baidubce.com | +| GZ | media.gz.baidubce.com | +| SU | media.su.baidubce.com | + +## 获取密钥 + +要使用百度云MCP,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问MCP做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建MCP Client + +MCP Client是MCP服务的客户端,为开发者与MCP服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建MCP Client + +通过AK/SK方式访问MCP,用户可以参考如下代码新建一个MCP Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/media" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个MCPClient + MEDIA_CLIENT, err := media.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《相关参考 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为MCP的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://media.bj.baidubce.com`。 + +# pipeline队列 + +队列分为免费型与专享型: + +- 免费型队列中的转码任务分享百度智能云为音视频转码所提供的约400路720P转码计算资源。 +- 专享型队列需额外采购,以便更好的满足那些对于转码时效性和稳定性有更高要求的用户的业务需求。 + +用户可以利用队列实现任务优先级。用户通过创建多个队列达到区分任务优先级的目的,将大部分任务创建至普通优先级队列,将高优的任务放入高优先级的队列,以利用队列先到先服务的工作原理来实现任务的优先级调整。 + +## 新建Pipeline + +如下代码可以新建一个Pipeline。 + +```go +pipelineName := "test" +sourceBucket := "testBucket" +targetBucket := "targetBucket" +capacity := 10 +err := MEDIA_CLIENT.CreatePipeline(pipelineName, sourceBucket, targetBucket, capacity) +if err != nil { + fmt.Printf("create Pipeline error: %+v\n", err) + return +} +fmt.Println("create pipeline success") +``` + +## 列出全部pipline + +如下代码可以列出用户所有的pipeline + +```go +pipelines, err := MEDIA_CLIENT.ListPipelines() +if err != nil { + fmt.Printf("list Pipeline error: %+v\n", err) + return +} +fmt.Println("list pipeline success\n") +for _, pipeline := range pipelines.Pipelines { + fmt.Printf("pipeline: %+v\n", pipeline) +} +``` + +## 查询指定pipeline + +如下代码可以按照pipelineName查询pipeline。 + +```go +pipelineName := "test" +pipeline, err := MEDIA_CLIENT.GetPipeline(pipelineName) +if err != nil { + fmt.Printf("list Pipeline error: %+v\n", err) + return +} +fmt.Println("get pipeline success") +fmt.Printf("pipeline: %+v\n", pipeline) +``` + +## 删除pipeline + +如下代码可以按照pipelineName删除pipeline。 + +```go +pipelineName := "test" +err := MEDIA_CLIENT.DeletePipeline(pipelineName) +if err != nil { + fmt.Printf("delete Pipeline error: %+v\n", err) + return +} +fmt.Println("delete pipeline success") +``` + +需要注意的是,如果Pipeline有关联的Job未完成,则Pipeline无法被删除,必须等Job执行结束后才能成功删除。 + +## 更新指定的Pipeline + +如下代码可以对指定的pipeline进行更新。 + +```go +pipelineName := "test" +args, _ := MEDIA_CLIENT.GetPipelineUpdate(pipelineName) +//args := &api.UpdatePipelineArgs{} +args.Description = "update" +args.TargetBucket = "vwdemo" +args.SourceBucket = "vwdemo" + +config := &api.UpdatePipelineConfig{} +config.Capacity = 2 +config.Notification = "zz" +args.UpdatePipelineConfig = config +err := MEDIA_CLIENT.UpdatePipeline(pipelineName, args) +if err != nil { + fmt.Printf("update Pipeline error: %+v\n", err) + return +} +fmt.Println("update pipeline success") +``` + +# Transcoding-Job转码任务 + +Transcoding Job(任务)是音视频转码中最基本的执行单元,每个任务将一个原始的音视频资源转码成目标规格的音视频资源。因此,任务和转码的目标是一一对应的,也就是说如果用户需要将一个原始多媒体文件转换成三种目标规格,比如从AVI格式转码成FLV/MP4/HLS格式,那么用户将会需要创建三个任务。 + +## 创建Transcoding Job + +用户在创建转码任务时,需要为转码任务指定所属的Pipeline、所需应用的Preset以及原始音视频资源的BOS Key以及目标音视频资源BOS Key。 + +如下代码创建一个Job, 并获取新创建的jobID: + +```go +pipelineName := "go_sdk_test" +sourceKey := "test.mp4" +targetKey := "test-result.mp4" +presetName := "test_preset" +jobResponse, err := MEDIA_CLIENT.CreateJob(pipelineName, sourceKey, targetKey, presetName) +if err != nil { + fmt.Printf("create job error: %+v\n", err) + return +} +fmt.Println("create job success jobId:", jobResponse.JobId) +``` + +如下代码创建一个支持视频合并、去水印、加水印(Job上而不是Preset上指定watermarkId)的Job, 并获取新创建的jobID: + +```go +args := &api.CreateJobArgs{} +args.PipelineName = "go_sdk_test" +source := &api.Source{Clips: &[]api.SourceClip{{ + SourceKey: "01.mp4", + EnableDelogo: false, + DurationInMillisecond: 6656, + StartTimeInSecond: 2}}} +args.Source = source +target := &api.Target{} +targetKey := "clips_playback_watermark_delogo_crop2.mp4" +watermarkId := "wmk-xxxx" +target.TargetKey = targetKey +watermarkIdSlice := append(target.WatermarkIds, watermarkId) +target.WatermarkIds = watermarkIdSlice +presetName := "go_test_customize_audio_video" +target.PresetName = presetName + +delogoArea := &api.Area{} +delogoArea.X = 10 +delogoArea.Y = 10 +delogoArea.Width = 30 +delogoArea.Height = 40 +target.DelogoArea = delogoArea + +args.Target = target + +jobResponse, err := MEDIA_CLIENT.CreateJobCustomize(args) +if err != nil { + fmt.Printf("create job error: %+v\n", err) + return +} +fmt.Println("create job success jobId:", jobResponse.JobId) +``` + +如下代码创建一个支持视频合并、去水印、加水印、去黑边、插入多样叠加效果(Insert)的Job, 并获取新创建的jobID: + + + + + + + + + + + +## 列出指定Pipeline的所有Transcoding Job + +如下代码通过指定pipelineName查询该Pipeline下的所有Job: + +```go +pipelineName := "test" +listTranscodingJobsResponse, err := MEDIA_CLIENT.ListTranscodingJobs(pipelineName) +if err != nil { + fmt.Printf("list job error: %+v\n", err) + return +} +fmt.Printf("list job success : %+v\n", listTranscodingJobsResponse) +``` + +## 查询指定的Transcoding Job信息 + +可以通过如下代码通过jobId读取某个Job: + +```go +jobId := "job-xxxxxxxxx" +getTranscodingJobResponse, err := MEDIA_CLIENT.GetTranscodingJob(jobId) +if err != nil { + fmt.Printf("get job error: %+v\n", err) + return +} +fmt.Printf("get job success : %+v\n", getTranscodingJobResponse) +``` + +# Preset模板 + +模板是系统预设的对于一个视频资源在做转码计算时所需定义的集合。用户可以更简便的将一个模板应用于一个和多个视频的转码任务,以使这些任务输出相同规格的目标视频资源。 + +音视频转码为用户预设了丰富且完备的系统模板,以满足用户对于目标规格在格式、码率、分辨率、加解密、水印等诸多方向上的普遍需求,对于不希望过多了解音视频复杂技术背景的用户来说,是最佳的选择。百度为那些在音视频技术上有着丰富积累的用户,提供了可定制化的转码模板,以帮助他们满足复杂业务条件下的转码需求。 + +当用户仅需对于音视频的容器格式做变化时,百度提供Transmux模板帮助用户以秒级的延迟快速完成容器格式的转换,比如从MP4转换成HLS,而保持原音视频的属性不变。 + +## 查询当前用户Preset及所有系统Preset + +用户可以通过如下代码查询所有的Preset + +```go +listPresetsResponse, err := MEDIA_CLIENT.ListPresets() +if err != nil { + fmt.Printf("list preset error: %+v\n", err) + return +} +fmt.Printf("list preset success: %+v\n", listPresetsResponse) +``` + +## 查询指定的Preset信息 + +如下代码通过指定pipelineName查询该Pipeline下的所有Job: + +```go +presetName := "test" +getPresetResponse, err := MEDIA_CLIENT.GetPreset(preset) +if err != nil { + fmt.Printf("list preset error: %+v\n", err) + return +} +fmt.Printf("list preset success: %+v\n", getPresetResponse) +``` + +## 创建Preset + +如果系统预设的Preset无法满足用户的需求,用户可以自定义自己的Preset。根据不同的转码需求,可以使用不同的接口创建Preset。 + +### 创建仅支持容器格式转换的Preset + +如下代码创建仅执行容器格式转换Preset + +```go +presetName := "test" +description := "测试创建模板" +container := "mp4" +err := MEDIA_CLIENT.CreatePreset(presetName, description, container) +if err != nil { + fmt.Printf("create preset error: %+v\n", err) + return +} +fmt.Println("create preset success") +``` + +### 创建音频文件的转码Preset,不需要截取片段和加密 + +如果创建一个不需要截取片段和加密的音频文件转码Preset,可以参考如下代码 + +```go +preset := &api.Preset{} +preset.PresetName = "go_test_customize" +preset.Description = "自定义创建模板" +preset.Container = "mp3" + +audio := &api.Audio{} +audio.BitRateInBps = 256000 +preset.Audio = audio + +err := MEDIA_CLIENT.CreatePrestCustomize(preset) +if err != nil { + fmt.Printf("create preset error: %+v\n", err) + return +} +fmt.Println("create preset success") +``` + +### 创建音频文件转码Preset,需要设置片段截取属性和加密属性 + +如果创建一个支持截取片段和加密的音频文件转码Preset,可以参考如下代码 + +```go +preset := &api.Preset{} +preset.PresetName = "go_test_customize_encryption_clip" +preset.Description = "自定义创建模板" +preset.Container = "mp3" + +audio := &api.Audio{} +audio.BitRateInBps = 256000 +preset.Audio = audio + +clip := &api.Clip{} +clip.StartTimeInSecond = 2 +clip.DurationInSecond = 10 +preset.Clip = clip + +encryption := &api.Encryption{} +encryption.Strategy = "PlayerBinding" +preset.Encryption = encryption + +err := MEDIA_CLIENT.CreatePrestCustomize(preset) +err := MEDIA_CLIENT.CreatePrestCustomize(preset) +if err != nil { + fmt.Printf("create preset error: %+v\n", err) + return +} +fmt.Println("create preset success") +``` + +### 创建视频文件转码Preset,不需要截取片段、加密和水印属性 + +如果创建一个不需要截取片段,加密和水印的视频文件转码Preset,可以参考如下代码 + +```go +preset := &api.Preset{} +preset.PresetName = "go_test_customize_audio_video" +preset.Description = "自定义创建模板" +preset.Container = "mp4" + +audio := &api.Audio{} +audio.BitRateInBps = 256000 +preset.Audio = audio + +video := &api.Video{} +video.BitRateInBps = 1024000 +preset.Video = video + +err := MEDIA_CLIENT.CreatePrestCustomize(preset) +if err != nil { + fmt.Printf("create preset error: %+v\n", err) + return +} +fmt.Println("create preset success") +``` + +### 创建视频文件转码Preset,需要设置片段截取、加密和水印属性 + +如果创建一个需要截取片段,加密和添加水印的视频文件转码Preset,可以参考如下代码 + +```go +preset := &api.Preset{} +preset.PresetName = "go_test_customize_clp_aud_vid_en_wat" +preset.Description = "自定义创建模板" +preset.Container = "mp4" + +clip := &api.Clip{} +clip.StartTimeInSecond = 0 +clip.DurationInSecond = 60 +preset.Clip = clip + +audio := &api.Audio{} +audio.BitRateInBps = 256000 +preset.Audio = audio + +video := &api.Video{} +video.BitRateInBps = 1024000 +preset.Video = video + +encryption := &api.Encryption{} +encryption.Strategy = "PlayerBinding" +preset.Encryption = encryption + +preset.WatermarkID = "wmk-xxxxxx" + +err := MEDIA_CLIENT.CreatePrestCustomize(preset) +if err != nil { + fmt.Printf("create preset error: %+v\n", err) + return +} +fmt.Println("create preset success") +``` + +### 创建Preset,指定所有的参数 + +如果需要定制所有配置参数,可以参考如下代码 + +```go +preset := &api.Preset{} +preset.PresetName = "go_test_customize_full_args" +preset.Description = "全参数" +preset.Container = "hls" +preset.Transmux = false + +clip := &api.Clip{} +clip.StartTimeInSecond = 0 +clip.DurationInSecond = 60 +preset.Clip = clip + +audio := &api.Audio{} +audio.BitRateInBps = 256000 +preset.Audio = audio + +video := &api.Video{} +video.BitRateInBps = 1024000 +preset.Video = video + +encryption := &api.Encryption{} +encryption.Strategy = "PlayerBinding" +preset.Encryption = encryption + +water := &api.Watermarks{} +water.Image = []string{"wmk-pc0rdhzbm8ff99qw"} +preset.Watermarks = water + +transCfg := &api.TransCfg{} +transCfg.TransMode = "normal" +preset.TransCfg = transCfg + +extraCfg := &api.ExtraCfg{} +extraCfg.SegmentDurationInSecond = 6.66 +preset.ExtraCfg = extraCfg + +err := MEDIA_CLIENT.CreatePrestCustomize(preset) +if err != nil { + fmt.Printf("create preset error: %+v\n", err) + return +} +fmt.Println("create preset success") +``` + +## 更新Preset + +用户可以根据模板名更新自己创建的模板: + +```go +preset, _ := MEDIA_CLIENT.GetPreset("go_test_customize") +preset.Description = "test update preset" +err := MEDIA_CLIENT.UpdatePreset(preset) +if err != nil { + fmt.Printf("update preset error: %+v\n", err) + return +} +fmt.Println("update preset success") +``` + +# Mediainfo媒体信息 + +对于BOS中某个Object,可以通过下面代码获取媒体信息 + +```go +bucket := "bucekt" +key := "key" +info, err := MEDIA_CLIENT.GetMediaInfoOfFile(bucket, key) +if err != nil { + fmt.Printf("get media information error: %+v\n", err) + return +} +fmt.Printf("get media information success: %+v\n", info) +``` + +# Thumbnail-Job缩略图任务 + +缩略图是图片、视频经压缩方式处理后的小图。因其小巧,加载速度非常快,故用于快速浏览。缩略图任务可用于为BOS中的多媒体资源创建缩略图。 + +## 创建Thumbnail Job + +通过pipeline,BOS Key以及其他配置信息为指定媒体生成缩略图,并获取返回的缩略图任务jobId。可以参考如下代码: + +```go +pipelineName := "go_test" +sourcekey := "01.mp4" +target := &api.ThumbnailTarget{} +target.Format = "jpg" +target.SizingPolicy = "keep" +capture := &api.ThumbnailCapture{} +capture.Mode = "manual" +capture.StartTimeInSecond = 0.0 +capture.EndTimeInSecond = 5.0 +capture.IntervalInSecond = 1.0 +createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob(pipelineName, sourcekey, TargetOp(target), CaptureOp(capture)) +if err != nil { + fmt.Printf("create thumbanil job error: %+v\n", err) + return +} +fmt.Println("create thumbanil job success jobId: ", createJobResponse.JobId) +``` + +创建去水印的缩略图,可以参考如下代码: + +```go +pipelineName := "go_test" +sourcekey := "01.mp4" +target := &api.ThumbnailTarget{} +target.KeyPrefix = "taget_key_prefix_test_delogo3" +delogo := &api.Area{} +delogo.X = 20 +delogo.Y = 20 +delogo.Height = 50 +delogo.Width = 80 + +createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob(pipelineName, sourcekey, TargetOp(target), DelogoAreaOp(delogo)) +if err != nil { + fmt.Printf("create thumbanil job error: %+v\n", err) + return +} +fmt.Println("create thumbanil job success jobId: ", createJobResponse.JobId) +``` + +创建去水印、去黑边的缩略图,可以参考如下代码: + +```go +pipelineName := "go_test" +sourcekey := "01.mp4" +target := &api.ThumbnailTarget{} +target.KeyPrefix = "taget_key_prefix_test_delogo_crop" +delogo := &api.Area{} +delogo.X = 20 +delogo.Y = 20 +delogo.Height = 50 +delogo.Width = 80 + +crop := &api.Area{} +crop.X = 120 +crop.Y = 120 +crop.Height = 100 +crop.Width = 80 + +createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob(pipelineName, sourcekey, + TargetOp(target), DelogoAreaOp(delogo), CropOp(crop)) +if err != nil { + fmt.Printf("create thumbanil job error: %+v\n", err) + return +} +fmt.Println("create thumbanil job success jobId: ", createJobResponse.JobId) +``` + +创建去水印缩略图任务,其中指定了缩略图格式为jpg、尺寸为与原视频保持一致(keep),抽帧模式(SizingPolicy)为split,根据指定的起止时间和张数截取缩略图,FrameNumber则指定了缩略图张数,代码如下: + +```go +pipelineName := "go_test" +sourcekey := "01.mp4" +target := &api.ThumbnailTarget{} +target.Format = "jpg" +target.SizingPolicy = "keep" + +capture := &api.ThumbnailCapture{} +capture.Mode = "split" +capture.FrameNumber = 30 + +delogo := &api.Area{} +delogo.X = 20 +delogo.Y = 20 +delogo.Height = 50 +delogo.Width = 80 + +createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob(pipelineName, sourcekey, + TargetOp(target), CaptureOp(capture), DelogoAreaOp(delogo)) +if err != nil { + fmt.Printf("create thumbanil job error: %+v\n", err) + return +} +fmt.Println("create thumbanil job success jobId: ", createJobResponse.JobId) +``` + +如果只想创建一个简单的缩略图任务可以参考如下代码: + +```go +pipelineName := "go_test" +sourcekey := "01.mp4" +createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob(pipelineName, sourcekey) +if err != nil { + fmt.Printf("create thumbanil job error: %+v\n", err) + return +} +fmt.Println("create thumbanil job success jobId: ", createJobResponse.JobId) +``` + +## 查询指定Thumbnail Job + +如果需要获取一个已创建的缩略图任务的信息,可以参考如下代码: + +```go +jobId := "job-xxxxxxx" +jobResponse, err := MEDIA_CLIENT.GetThumbanilJob(jobId) +if err != nil { + fmt.Printf("get thumbanil job error: %+v\n", err) + return +} +fmt.Printf("get thumbanil job success job: %+v\n", jobResponse) +``` + +## 查询指定队列的Thumbnail Jobs + +如果需要获取一个队列里的全部缩略图任务的信息,可以参考如下代码: + +```go +pipelineName := "go_sdk_test" +listThumbnailJobsResponse, err := MEDIA_CLIENT.ListThumbnailJobs(pipelineName) +if err != nil { + fmt.Printf("list thumbanil job error: %+v\n", err) + return +} +for _, job := range listThumbnailJobsResponse.Thumbnails { + fmt.Printf("list thumbanil job success : %+v\n", job) +} +``` + +# Watermark水印 + +数字水印是向数据多媒体(如图像、音频、视频信号等)中添加某些数字信息以达到文件真伪鉴别、版权保护等功能。嵌入的水印信息隐藏于宿主文件中,不影响原始文件的可观性和完整性。 + +用户可以将BOS中的一个Object创建为水印,获得对应的watermarkId。然后在转码任务中将此水印添加到目的多媒体文件。 + +## 创建水印 + +如果需要创建一个水印, 指定水印的位置, 并获得水印的唯一ID。其中bucket是水印文件所在bucket名称,key是水印文件在该bucket中的文件名。可以参考如下代码: + +```go +args := &api.CreateWaterMarkArgs{} +args.Bucket = "go-test" +args.Key = "01.jpg" +args.HorizontalAlignment = "right" +args.VerticalAlignment = "top" +createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) +if err != nil { + fmt.Printf("create watermark job error: %+v\n", err) + return +} +fmt.Println("create watermark job success Id: ", createWaterMarkResponse.WatermarkId) +``` + +如果需要创建一个水印, 指定水印的位置、显示时间段、重复显示次数(动态水印)、自动缩放, 并获得水印的唯一ID,可以参考如下代码: + +```go +args := &api.CreateWaterMarkArgs{} +args.Bucket = "go-test" +args.Key = "01.jpg" +args.HorizontalAlignment = "left" +args.VerticalAlignment = "top" +args.HorizontalOffsetInPixel = 20 +args.VerticalOffsetInPixel = 10 +timeline := &api.Timeline{} +timeline.StartTimeInMillisecond = 1000 +timeline.DurationInMillisecond = 3000 +args.Timeline = timeline +args.Repeated = 1 +args.AllowScaling = true +createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) +if err != nil { + fmt.Printf("create watermark job error: %+v\n", err) + return +} +fmt.Println("create watermark job success Id: ", createWaterMarkResponse.WatermarkId) +``` + +## 查询指定水印 + +如果需要查询已创建的水印,可以参考如下代码: + +```go +waterMarkId := "wmk-xxx" +response, err := MEDIA_CLIENT.GetWaterMark(waterMarkId) +if err != nil { + fmt.Printf("get watermark job error: %+v\n", err) + return +} +fmt.Printf("get watermark job success: %+v\n", response) +``` + +## 查询当前用户水印 + +如果需要查询出本用户所创建的全部水印,可以参考如下代码: + +```go +response, err := MEDIA_CLIENT.ListWaterMark() +if err != nil { + fmt.Printf("get watermark job error: %+v\n", err) + return +} +for _, watermark := range response.Watermarks { + fmt.Printf("watermark job: %+v\n", watermark) +} +``` + +## 删除水印 + +如果需要删除某个已知watermarkId的水印,可以参考如下代码: + +```go +waterMarkId := "wmk-xxx" +err := MEDIA_CLIENT.DeleteWaterMark(waterMarkId) +if err != nil { + fmt.Printf("delete watermark job error: %+v\n", err) + return +} +fmt.Println("delete watermark success") +``` + +# Notification通知 + +通知功能可以在音视频转码任务状态转换时主动向开发者服务器推送消息。 + +## 创建通知 + +如果需要创建通知可以参考如下代码: + +```go +name := "test" +endpoint := "http://www.baidu.com" +err := MEDIA_CLIENT.CreateNotification(name, endpoint) +if err != nil { + fmt.Printf("create notification error: %+v\n", err) + return +} +fmt.Println("create notification success") +``` + +## 查询指定通知 + +如果需要查询已创建的通知,可以参考如下代码: + +```go +name := "test" +response, err := MEDIA_CLIENT.GetNotification(test) +if err != nil { + fmt.Printf("get notification error: %+v\n", err) + return +} +fmt.Printf("get notification success : %+v\n", response) +``` + +## 查询当前用户通知 + +如果需要查询出本用户所创建的全部通知,可以参考如下代码: + +```go +response, err := MEDIA_CLIENT.ListNotification() +if err != nil { + fmt.Printf("list user`s notification error: %+v\n", err) + return +} +for _, notification := range response.Notifications { + fmt.Printf("list notification success : %+v\n", notification) +} +``` + +## 删除通知 + +如果需要删除某个通知,可以参考如下代码: + +```go +name := "test" +err := MEDIA_CLIENT.DeleteNotification(name) +if err != nil { + fmt.Printf("delete notification error: %+v\n", err) + return +} +fmt.Println("delete notification success") +``` + +# 错误处理 + +GO语言以error类型标识错误,MCP支持两种错误见下表: + +| 错误类型 | 说明 | +| --------------- | ------------------ | +| BceClientError | 用户操作产生的错误 | +| BceServiceError | MCP服务返回的错误 | + +用户使用SDK调用MCP相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// MEDIA_CLIENT 为已创建的MCP Client对象 +result, err := MEDIA_CLIENT.ListPipelines() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向MCP发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当MCP服务端出现异常时,MCP服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[MCP错误码](https://cloud.baidu.com/doc/MCT/s/bjwvz5h3i) + +## SDK日志 + +MCP GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +MCP GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +```go +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +```go +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the MCP go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the MCP go sdk") +``` +# 版本变更记录 + +首次发布: + +- MCP支持go-sdk啦,现在您可以通过golang调用MCP-SDK服务。当前SDK能力支持pipeline队列操作、Transcoding-Job转码任务操作、Preset模板操作、Thumbnail-Job缩略图任务操作、Watermark水印任务操作、MediaInfo媒资信息操作、Notification通知操作。 \ No newline at end of file diff --git a/bce-sdk-go/doc/MMS.md b/bce-sdk-go/doc/MMS.md new file mode 100644 index 0000000..9b21e41 --- /dev/null +++ b/bce-sdk-go/doc/MMS.md @@ -0,0 +1,568 @@ +# MMS - 多模态媒资检索 + +## 介绍 + +- 百度智能云多模态媒资(Multimodal Media Search,简称 MMS)基于视频指纹特征与视频内容理解,实现多模态的搜索能力,主要包含以视频搜视频、以图搜视频、以图搜图等功能,赋予用户多模态的高效、精准、智能的搜索能力。 + +## 接口调用准备 + +### Endpoint + +- 目前统一为: mms.bj.baidubce.com + +### AK/SK + +- 要使用百度云 SMS,您需要拥有一个有效的 AK(Access Key ID)和 SK(Secret Access Key)用来进行签名认证。AK/SK 是由系统分配给用户的,均为字符串,用于标识用户,为访问 SMS 做签名验证。 +- 可以通过如下步骤获得并了解您的 AK/SK 信息:[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal)、[创建 AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +### AK/SK 应用及客户端初始化 + +```golang + AK := "" // 填充Access Key ID + SK := "" // 填充Secret Access Key + ENDPOINT := "http://xxx" // 填充Endpoint + CLIENT, err := mms.NewClient(AK, SK, ENDPOINT) // 初始化客户端 +``` + +## 视频入库 + +### 接口描述 + +- 本接口用于向视频库中插入视频特征。 +- 入库接口为异步接口,可通过[查询视频入库结果](#查询视频入库结果)接口查询入库结果。或通过通知服务回调结果。 + +### 请求结构 + + PUT /v{version}/videolib/{libName} + host: mms.bj.baidubce.com + Authorization: + { + "source": videoUrl, + "description": desc, + "notification": notificationName + } + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ------------ | ------ | -------- | --------- | -------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的视频库名称 | +| source | String | 是 | Body 参数 | 入库视频的 URL | +| description | String | 否 | Body 参数 | 用户对此次请求的描述 | +| notification | String | 否 | Body 参数 | 入库结果通知的名称 | + +- 注:如使用 notification 参数,需提前配置通知名称及对于的回调地址。 + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| -------- | ------ | -------- | +| status | String | 请求结果 | + +### 请求示例 + + PUT /v2/videolib/baiduyun_test + host: mms.bj.baidubce.com + Authorization: + { + "source": "http://test.mp4", + "description": "test", + "notification": "notification_name" + } + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success" + } + +### 通知服务回调结果示例 + + { + "messageId": "a114f8e1-0de0-473f-9f6c-d47e33df5d7d", + "messageBody": "{\"taskId\":\"n7CCcHIBTmikKXpp-AS8\",\"status\":\"success\",\"source\":\"http://test.mp4\",\"duration\":6.5,\"description\":\"\",\"createTime\":\"2020-06-01T15:32:11Z\",\"startTime\":\"2020-06-01T15:32:11Z\",\"updateTime\":\"2020-06-01T15:32:13Z\",\"finishTime\":\"2020-06-01T15:32:13Z\"}" + } + +## 查询视频入库结果 + +### 接口描述 + +- 本接口用于查询视频入库结果。 + +### 请求结构 + + GET /v{version}/videolib/{libName}?source=videoUrl + host: mms.bj.baidubce.com + Authorization: + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| -------- | ------ | -------- | -------- | ---------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的视频库名称 | +| source | String | 是 | URL 参数 | 入库视频的 URL | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| ----------- | ------ | --------------------------------------------------------------------------------------- | +| status | String | 入库任务状态,取值为 provision/processing/success/failed,分别为排队中/处理中/成功/失败 | +| description | String | 用户入库请求传入的 description 字段 | +| taskId | String | 视频入库任务 ID | +| source | String | 入库视频的 URL | + +### 请求示例 + + GET /v2/videolib/baiduyun_test?source=http://test.mp4 + host: mms.bj.baidubce.com + Authorization: + +### 响应示例 + +- 入库中 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "createTime": "2020-05-13T07:57:25Z", + "description": "", + "source": "http://test.mp4", + "startTime": "2020-05-13T07:57:26Z", + "status": "processing", + "taskId": "VUcJDXIBrTeiQx_QzcWe" + } + +- 入库完成 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "createTime": "2020-05-13T07:55:55Z", + "description": "", + "duration": 6.5, + "finishTime": "2020-05-13T07:55:57Z", + "source": "http://test.mp4", + "startTime": "2020-05-13T07:55:55Z", + "status": "success", + "taskId": "VUcJDXIBrTeiQx_QzcWe" + } + +## 图片入库 + +### 接口描述 + +- 本接口用于向图片库中插入图片特征。 + +### 请求结构 + + PUT /v{version}/imagelib/{libName} + host: mms.bj.baidubce.com + Authorization: + { + "source": imageUrl, + "description": desc + } + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ----------- | ------ | -------- | --------- | -------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的图片库名称 | +| source | String | 是 | Body 参数 | 入库图片的 URL | +| description | String | 否 | Body 参数 | 用户对此次请求的描述 | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| -------- | ------ | -------- | +| status | String | 入库结果 | + +### 请求示例 + + PUT /v2/imagelib/baiduyun_test + host: mms.bj.baidubce.com + Authorization: + { + "source": "http://test.jpg", + "description": "test" + } + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success" + } + +## 删除视频库中的视频 + +### 接口描述 + +- 本接口用于删除视频库中某个视频 + +### 请求结构 + + POST /v{version}/videolib/{libName}?deleteVideo=&source=videoUrl + host: mms.bj.baidubce.com + Authorization: + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ----------- | ------ | -------- | -------- | -------------------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的视频库名称 | +| source | String | 是 | URL 参数 | 要删除视频的 URL(入库时的 URL) | +| deleteVideo | String | 是 | URL 参数 | 标识参数,无内容 | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| -------- | ------ | -------- | +| status | String | 删除结果 | + +### 请求示例 + + POST /v2/videolib/baiduyun_test?deleteVideo=&source=http://test.mp4 + host: mms.bj.baidubce.com + Authorization: + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success" + } + +## 删除图片库中的图片 + +### 接口描述 + +- 本接口用于删除图片库中某张图片 + +### 请求结构 + + POST /v{version}/imagelib/{libName}?deleteImage=&source=imageUrl + host: mms.bj.baidubce.com + Authorization: + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ----------- | ------ | -------- | -------- | -------------------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的图片库名称 | +| source | String | 是 | URL 参数 | 要删除图片的 URL(入库时的 URL) | +| deleteImage | String | 是 | URL 参数 | 标识参数,无内容 | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| -------- | ------ | -------- | +| status | String | 删除结果 | + +### 请求示例 + + POST /v2/imagelib/baiduyun_test?deleteImage=&source=http://test.jpg + host: mms.bj.baidubce.com + Authorization: + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success" + } + +## 视频检索视频 + +### 接口描述 + +- 本接口使用视频来检索库中存在的相似视频。 +- 本接口为异步接口,可通过[查询视频检索结果](#查询视频检索视频结果)接口查询检索结果。或通过通知服务回调结果。 + +### 请求结构 + + POST /v{version}/videolib/{libName}?searchByVideo + host: mms.bj.baidubce.com + Authorization: + { + "source": videoUrl, + "description": desc, + "notification": notificationName + } + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ------------ | ------ | -------- | --------- | -------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的视频库名称 | +| source | String | 是 | Body 参数 | 检索视频的 URL | +| description | String | 否 | Body 参数 | 用户对此次请求的描述 | +| notification | String | 否 | Body 参数 | 检索结果通知的名称 | + +- 注:如使用 notification 参数,需提前配置通知名称及对于的回调地址。 + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| -------- | ------ | --------------- | +| status | String | 请求结果 | +| taskId | String | 视频检索任务 ID | + +### 请求示例 + + POST /v2/videolib/baiduyun_test?searchByVideo + host: mms.bj.baidubce.com + Authorization: + { + "source": "https://test.mp4", + "description": "test", + "notification": "notification_name" + } + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success", + "taskId": "VkcZDXIBrTeiQx_QrcXT" + } + +### 通知服务回调结果示例 + + { + "messageId": "360d15ea-14ae-440e-9be1-f1f431beae19", + "messageBody": "{\"taskId\":\"ybjMcnIBFaqg3FXUVQrA\",\"status\":\"success\",\"lib\":\"video_lib\",\"source\":\"https://test.mp4\",\"duration\":6.5,\"description\":\"\",\"createTime\":\"2020-06-02T02:11:33Z\",\"startTime\":\"2020-06-02T02:12:05Z\",\"updateTime\":\"2020-06-02T02:12:08Z\",\"finishTime\":\"2020-06-02T02:12:08Z\",\"results\":[{\"id\":\"n7CCcHIBTmikKXpp-AS8\",\"name\":\"search_hit.mp4\",\"source\":\"http://hit.mp4\",\"duration\":6.5,\"description\":\"\",\"type\":\"SEARCH_VIDEO_BY_VIDEO\",\"score\":100,\"clips\":[{\"inputStartTime\":0.0,\"inputEndTime\":6.5,\"outputStartTime\":0.0,\"outputEndTime\":6.5}]}]}" + } + +## 查询视频检索视频结果 + +### 接口描述 + +- 本接口用于查询视频检索视频任务的结果。 + +请求结构 + + GET /v{version}/videolib/{libName}?searchByVideo&source=videoUrl + host: mms.bj.baidubce.com + Authorization: + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ------------- | ------ | -------- | -------- | ---------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的视频库名称 | +| source | String | 是 | URL 参数 | 发起检索任务视频的 URL | +| searchByVideo | String | 是 | URL 参数 | 标识参数,无内容 | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| ----------------- | ------ | ------------------------------------------------------------------ | +| status | String | 任务状态,取值为 processing/success/failed,分别为处理中/成功/失败 | +| lib | String | 检索的视频库名称 | +| source | String | 检索视频的 URL | +| description | String | 用户传入的请求描述信息 | +| results | List | 检索视频的结果 | +| +score | Double | 检索视频的相似度,取值范围为[0, 100] | +| +source | String | 结果视频的 URL | +| +description | String | 结果视频的描述 | +| +clips | List | 请求成功时才会有此值 | +| ++inputStartTime | Double | 检索视频片段的开始时间,单位:秒 | +| ++inputEndTime | Double | 检索视频片段的结束时间,单位:秒 | +| ++outputStartTime | Double | 底库视频片段的开始时间,单位:秒 | +| ++outputEndTime | Double | 底库视频片段的结束时间,单位:秒 | +| error | Object | 请求失败时才会有此值 | +| +code | String | 请求失败时才会有此值,表示错误码 | +| +message | String | 请求失败时才会有此值,表示错误信息 | + +### 请求示例 + + GET /v2/videolib/baiduyun_test?searchByVideo&source=https://test.mp4 + host: mms.bj.baidubce.com + Authorization: + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status":"success", + "lib":"baiduyun_test", + "source":"https://test.mp4", + "description":"test", + "results":[ + { + "source":"https://test.mp4", + "description":"test", + "score":100, + "clips":[ + { + "inputStartTime":0.08, + "inputEndTime":20.16, + "outputStartTime":0.08, + "outputEndTime":20.16 + } + ] + } + ] + } + +## 图片检索图片 + +### 接口描述 + +- 本接口使用图片来检索库中存在的相似图片。 + +### 请求结构 + + POST /v{version}/imagelib/{libName}?searchByImage + host: mms.bj.baidubce.com + Authorization: + { + "source": imageUrl, + "description": desc + } + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ----------- | ------ | -------- | --------- | -------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的图片库名称 | +| source | String | 是 | Body 参数 | 检索图片的 URL | +| description | String | 否 | Body 参数 | 用户对此次请求的描述 | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| ------------ | ------ | ---------------------------------------------- | +| status | String | 请求结果 | +| lib | String | 检索的图片库名称 | +| source | String | 用户传入的图片 URL | +| description | String | 用户传入的请求描述信息 | +| results | List | 检索图片的结果 | +| +distance | Double | 检索图片的相似度,取值范围为[0, 1],越小越相似 | +| +source | String | 结果图片的 URL | +| +description | String | 结果图片的描述 | +| error | Object | 请求失败时才会有此值 | +| +code | String | 请求失败时才会有此值,表示错误码 | +| +message | String | 请求失败时才会有此值,表示错误信息 | + +### 请求示例 + + POST /v2/imagelib/baiduyun_test?searchByImage + host: mms.bj.baidubce.com + Authorization: + { + "source": "http://test.jpg", + "description": "nothing to desc" + } + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success", + "lib":" baiduyun_test", + "source": "http://test.jpg", + "description": "nothing to desc", + "results": [ + { + "distance": 0.12, + "source": "http://test2.jpg", + "description":"nothing to desc" + } + ] + } + +## 图片检索视频 + +### 接口描述 + +- 本接口使用图片来检索库中存在的包含相似图片的视频。 + +### 请求结构 + + POST /v{version}/videolib/{libName}?searchByImage + host: mms.bj.baidubce.com + Authorization: + { + "source": imageUrl, + "description": desc + } + +### 请求参数 + +| 参数名称 | 类型 | 是否必需 | 参数位置 | 描述 | +| ----------- | ------ | -------- | --------- | -------------------- | +| version | String | 是 | URL 参数 | API 版本号 | +| libName | String | 是 | URL 参数 | 用户的视频库名称 | +| source | String | 是 | Body 参数 | 检索图片的 URL | +| description | String | 否 | Body 参数 | 用户对此次请求的描述 | + +### 响应参数 + +| 参数名称 | 类型 | 描述 | +| ------------ | ------ | -------------------------------------------------- | +| status | String | 请求结果 | +| lib | String | 检索的视频库名称 | +| source | String | 用户传入的图片 URL | +| description | String | 用户传入的请求描述信息 | +| results | List | 检索视频的结果 | +| +source | String | 结果视频的 URL | +| +distance | Double | 结果视频中命中最相似图片的相似度,取值范围为[0, 1] | +| +description | String | 结果视频的描述 | +| +frames | List | 结果视频中对应的图片 | +| ++distance | Double | 视频中对应图片的相似度,取值范围为[0, 1] | +| ++timestamp | Double | 视频中对应图片的时间戳,单位为秒(s) | +| error | Object | 请求失败时才会有此值 | +| +code | String | 请求失败时才会有此值,表示错误码 | +| +message | String | 请求失败时才会有此值,表示错误信息 | + +### 请求示例 + + POST /v2/videolib/baiduyun_test?searchByImage + host: mms.bj.baidubce.com + Authorization: + { + "source": "http://test.jpg", + "description": "nothing to desc" + } + +### 响应示例 + + HTTP/1.1 200 OK + Content-Type: application/json;charset=UTF-8 + { + "status": "success", + "lib":" baiduyun_test", + "source": "http://test.jpg", + "description": "nothing to desc", + "results": [ + { + "source": "http://test2.jpg", + "description": "nothing to desc", + "distance": 0.12, + "frames": [ + { + "distance": 0.12, + "timestamp": 3.4333 + } + ] + } + ] + } diff --git a/bce-sdk-go/doc/RDS.md b/bce-sdk-go/doc/RDS.md new file mode 100644 index 0000000..fde4ff9 --- /dev/null +++ b/bce-sdk-go/doc/RDS.md @@ -0,0 +1,2435 @@ +# RDS服务 + +# 概述 + +本文档主要介绍RDS GO SDK的使用。在使用本文档前,您需要先了解RDS的一些基本知识,并已开通了RDS服务。若您还不了解RDS,可以参考[产品描述](https://cloud.baidu.com/doc/RDS/s/ujwvyzdzg)和[操作指南](https://cloud.baidu.com/doc/RDS/s/Qjwvz0ikk)。 + +本SDK基于官方开放API进行封装,详细参数解释可参考相关API说明文档[API参考](https://cloud.baidu.com/doc/RDS/s/ajwvz0x1m)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[RDS服务域名](https://cloud.baidu.com/doc/RDS/s/Ejwvz0uoq)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华北-保定”、“华南-广州”、“华东-苏州”、“金融华中-武汉”、“华东-上海”、“中国香港”、“新加坡”区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +北京 | rds.bj.baidubce.com | HTTP and HTTPS +保定 | rds.bj.baidubce.com | HTTP and HTTPS +广州 | rds.gz.baidubce.com | HTTP and HTTPS +苏州 | rds.su.baidubce.com | HTTP and HTTPS +武汉 | rds.fwh.baidubce.com| HTTP and HTTPS +上海 | rds.fsh.baidubce.com| HTTP and HTTPS +香港 | rds.hkg.baidubce.com| HTTP and HTTPS +新加坡 | rds.sin.baidubce.com| HTTP and HTTPS +## 获取密钥 + +要使用百度云RDS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问RDS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建RDS Client + +RDS Client是RDS服务的客户端,为开发者与RDS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建RDS Client + +通过AK/SK方式访问RDS,用户可以参考如下代码新建一个RDS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/rds" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个RDSClient + rdsClient, err := rds.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`rds.bj.baidubce.com`。 + +### 使用STS创建RDS Client + +**申请STS token** + +RDS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问RDS,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建RDS Client** + +申请好STS后,可将STS Token配置到RDS Client中,从而实现通过STS Token创建RDS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建RDS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/rds" //导入RDS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建RDS服务的Client对象,Endpoint使用默认值 + rdsClient, err := rds.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "rds.bj.baidubce.com") + if err != nil { + fmt.Println("create rds client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + rdsClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置RDS Client时,无论对应RDS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问RDS + +RDS支持HTTPS传输协议,您可以通过在创建RDS Client对象时指定的Endpoint中指明HTTPS的方式,在RDS GO SDK中使用HTTPS访问RDS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +ENDPOINT := "https://rds.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +rdsClient, _ := rds.NewClient(AK, SK, ENDPOINT) +``` + +## 配置RDS Client + +如果用户需要配置RDS Client的一些细节的参数,可以在创建RDS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问RDS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +//创建RDS Client对象 +AK, SK := , +ENDPOINT := "rds.bj.baidubce.com" +client, _ := rds.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +AK, SK := , +ENDPOINT := "rds.bj.baidubce.com" +client, _ := rds.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +AK, SK := , +ENDPOINT := "rds.bj.baidubce.com" +client, _ := rds.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问RDS时,创建的RDS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建RDS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# RDS管理 + +云数据库 RDS (Relational Database Service)是专业、高性能、高可靠的云数据库服务。云数据库 RDS 提供 Web 界面进行配置、操作数据库实例,还为您提供可靠的数据备份和恢复、完备的安全管理、完善的监控、轻松扩展等功能支持。相对于自建数据库,云数据库 RDS 具有更经济、更专业、更高效、更可靠、简单易用等特点,使您能更专注于核心业务。 + +## 创建RDS主实例 + +使用以下代码可以创建一个RDS主实例 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.CreateRdsArgs{ + // 指定rds的数据库引擎,取值mysql,sqlserver,postgresql,必选 + Engine: "mysql", + // 指定rds的数据库版本,必选 + EngineVersion: "5.6", + // 计费相关参数,PaymentTiming取值为 预付费:Prepaid,后付费:Postpaid;Reservation:支付方式为后支付时不需要设置,预支付时必须设置;必选 + Billing: rds.Billing{ + PaymentTiming: "Postpaid", + //Reservation: rds.Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + // 预付费时可指定自动续费参数 AutoRenewTime 和 AutoRenewTimeUnit + // 自动续费时长(续费单位为year 不大于3,续费单位为month 不大于9) + // AutoRenewTime: 1, + // 自动续费单位("year";"month") + // AutoRenewTimeUnit: "year", + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //磁盘类型, normal_io:本地盘ssd磁盘, cloud_high:高性能云磁盘, cloud_nor:通用型SSD, cloud_enha:增强型SSD, 必选 + DiskIoType: "normal_io", + //批量创建云数据库 RDS 实例个数, 最大不超过10,默认1,可选 + PurchaseCount: 1, + //rds实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //所属系列,Basic:单机基础版,Standard:双机高可用版。仅SQLServer 2012sp3 支持单机基础版。默认Standard,可选 + Category: "Standard", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + ZoneNames: []string{"cn-bj-d"}, + //vpc,如果不提供则属于默认vpc,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []rds.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +result, err := client.CreateRds(args) +if err != nil { + fmt.Printf("create rds error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create rds success, instanceId: ", e) +} +``` + +> 注意: +> - 实例可选套餐详见(https://cloud.baidu.com/doc/RDS/s/9jwvz0wd3) +> - 创建计费方式为后付费的实例需要账户现金余额+通用代金券大于100;预付费方式的实例则需要账户现金余额大于等于实例费用。 +> - 支持批量创建,且如果创建过程中有一个实例创建失败,所有实例将全部回滚,均创建失败。 +> - 创建接口为异步创建,可通过查询指定实例详情接口查询实例状态。 + +## 创建RDS只读实例 + +使用以下代码可以创建一个RDS只读实例 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.CreateReadReplicaArgs{ + //主实例ID,必选 + SourceInstanceId: "sourceInstanceId" + // 计费相关参数,只读实例只支持后付费Postpaid,必选 + Billing: rds.Billing{ + PaymentTiming: "Postpaid", + }, + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //批量创建云数据库 RDS 只读实例个数, 目前只支持一次创建一个,可选 + PurchaseCount: 1, + //实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + ZoneNames: []string{"cn-bj-d"}, + //与主实例 vpcId 相同,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []rds.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +result, err := client.CreateReadReplica(args) +if err != nil { + fmt.Printf("create rds readReplica error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create rds readReplica success, instanceId: ", e) +} +``` + +> 注意: +> - 需要在云数据库 RDS 主实例的基础上进行创建 +> - 实例可选套餐详见(https://cloud.baidu.com/doc/RDS/s/9jwvz0wd3) +> - 仅数据库类型为 MySQL 的主实例支持创建只读实例 +> - 只读实例的数据库引擎和数据库版本与主实例相同,无需设置,主实例版本最低是 MySQL 5.6 +> - 只读实例的磁盘容量不能小于主实例的磁盘容量 +> - 只读实例的 vpcId 需跟主实例一致 +> - 一个云数据库 RDS 实例,最多只能有 5 个只读实例,且一次只能创建一个 +> - 只读实例只支持后付费方式购买 + +## 创建RDS代理实例 + +使用以下代码可以创建一个RDS代理实例 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.CreateRdsProxyArgs{ + //主实例ID,必选 + SourceInstanceId: "sourceInstanceId" + // 计费相关参数,代理实例只支持后付费Postpaid,必选 + Billing: rds.Billing{ + PaymentTiming: "Postpaid", + }, + // 代理实例节点数。取值范围2,4,6,8,16,必选 + NodeAmount: 2, + //实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + InstanceName: "instanceName", + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a",建议与主实例的可用区保持一致 + ZoneNames: []string{"cn-bj-d"}, + //与主实例 vpcId 相同,可选 + VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + Subnets: []rds.SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-IyWRnII7", + }, + }, + // 实例绑定的标签信息,可选 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +result, err := client.CreateRdsProxy(args) +if err != nil { + fmt.Printf("create rds proxy error: %+v\n", err) + return +} + +for _, e := range result.InstanceIds { + fmt.Println("create rds proxy success, instanceId: ", e) +} +``` + +> 注意: +> - 需要在云数据库 RDS 主实例的基础上进行创建 +> - 仅数据库类型为 MySQL 的主实例支持创建只读实例 +> - 代理实例套餐和主实例套餐绑定,主实例版本最低是MySQL 5.6 +> - 每个主实例最多可以创建1个代理实例 +> - 需与主实例在同一vpc中 +> - 代理实例只支持后付费方式购买 + +## 查询RDS列表 + +使用以下代码可以查询RDS列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.ListRdsArgs{ + // 批量获取列表的查询的起始位置,是一个由系统生成的字符串,可选 + Marker: "marker", + // 指定每页包含的最大数量(主实例),最大数量不超过1000,缺省值为1000,可选 + MaxKeys: 1, +} +result, err := client.ListRds(args) +if err != nil { + fmt.Printf("list rds error: %+v\n", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("rds list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("rds list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("rds list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("rds list maxKeys: ", result.MaxKeys) +// 获取rds的列表信息 +for _, e := range result.Instances { + fmt.Println("rds instanceId: ", e.InstanceId) + fmt.Println("rds instanceName: ", e.InstanceName) + fmt.Println("rds engine: ", e.Engine) + fmt.Println("rds engineVersion: ", e.EngineVersion) + fmt.Println("rds instanceStatus: ", e.InstanceStatus) + fmt.Println("rds cpuCount: ", e.CpuCount) + fmt.Println("rds memoryCapacity: ", e.MemoryCapacity) + fmt.Println("rds volumeCapacity: ", e.VolumeCapacity) + fmt.Println("rds usedStorage: ", e.UsedStorage) + fmt.Println("rds paymentTiming: ", e.PaymentTiming) + fmt.Println("rds instanceType: ", e.InstanceType) + fmt.Println("rds instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("rds instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("rds publicAccessStatus: ", e.PublicAccessStatus) + fmt.Println("rds task: ", e.Task) + fmt.Println("rds vpcId: ", e.VpcId) +} +``` + +> 注意: +> - 只能查看属于自己账号的实例列表。 +> - 接口将每个主实例和其只读、代理实例分成一组,参数maxKeys代表分组数,也就是主实例的个数. + +## 查询指定RDS实例信息 + +使用以下代码可以查询指定RDS实例信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.GetDetail(instanceId) +if err != nil { + fmt.Printf("get rds detail error: %+v\n", err) + return +} + +fmt.Println("rds instanceId: ", result.InstanceId) +fmt.Println("rds instanceName: ", result.InstanceName) +fmt.Println("rds engine: ", result.Engine) +fmt.Println("rds engineVersion: ", result.EngineVersion) +fmt.Println("rds instanceStatus: ", result.InstanceStatus) +fmt.Println("rds cpuCount: ", result.CpuCount) +fmt.Println("rds memoryCapacity: ", result.MemoryCapacity) +fmt.Println("rds volumeCapacity: ", result.VolumeCapacity) +fmt.Println("rds usedStorage: ", result.UsedStorage) +fmt.Println("rds paymentTiming: ", result.PaymentTiming) +fmt.Println("rds instanceType: ", result.InstanceType) +fmt.Println("rds instanceCreateTime: ", result.InstanceCreateTime) +fmt.Println("rds instanceExpireTime: ", result.InstanceExpireTime) +fmt.Println("rds publicAccessStatus: ", result.PublicAccessStatus) +fmt.Println("rds vpcId: ", result.VpcId) + +``` + +## 删除RDS实例 + +使用以下代码可以删除RDS实例。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +//多个实例间用英文半角逗号","隔开,最多可输入10个 +if err := client.DeleteRds(instanceIds); err != nil { + fmt.Printf("delete rds error: %+v\n", err) + return +} +fmt.Printf("delete rds success\n") +``` + +> 注意: +> - 只有付费类型为Postpaid或者付费类型为Prepaid且已过期的实例才可以释放。 +> - 如果主实例被释放,那么和主实例关联的只读实例和代理实例也会被释放。 + +## RDS实例扩缩容 + +使用以下代码可以对RDS实例扩缩容操作。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.ResizeRdsArgs{ + // cpu核数 + CpuCount: 2, + // 内存大小,单位GB + MemoryCapacity: 8, + // 磁盘大小,单位GB,每5G递增 + VolumeCapacity: 20, + // 代理实例节点数,代理实例变配时此项必填 + NodeAmount: 2, + // 是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, +} +err = client.ResizeRds(instanceId, args) +if err != nil { + fmt.Printf("resize rds error: %+v\n", err) + return +} + +fmt.Println("resize rds success.") +``` + +> 注意: +> - 实例可选套餐详见(https://cloud.baidu.com/doc/RDS/s/9jwvz0wd3) +> - 主实例或只读实例变配时至少填写cpuCount、memoryCapacity、volumeCapacity其中的一个。 +> - 实例计费方式采用后付费时,可弹性扩缩容;采用预付费方式,不能进行缩容操作。 +> - 只有实例available状态时才可以进行扩缩容操作。 +> - 实例扩缩容之后会重启一次。 +> - 为异步接口,可通过查询实例详情接口查看instanceStatus是否恢复。 + +## 重启实例 + +使用以下代码可以重启实例。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +err := client.RebootInstance(instanceId) +if err != nil { + fmt.Printf("reboot rds error: %+v\n", err) + return +} +``` + +## 修改实例名称 + +使用以下代码可以修改RDS实例名称。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.UpdateInstanceNameArgs{ + InstanceName: "instanceName", +} +err = client.UpdateInstanceName(instanceId, args) +if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return +} +fmt.Printf("update instance name success\n") +``` +> 注意: +> +> - 实例名称支持大小写字母、数字以及-_ /.等特殊字符,必须以字母开头,长度1-64。 + +## 已创建实例自动续费 + +使用以下代码可以为已创建的预付费实例创建自动续费 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.AutoRenewArgs{ + // 自动续费时长(续费单位为year 不大于3,续费单位为month 不大于9)必选 + AutoRenewTime: 1, + // 自动续费单位("year";"month")必选 + AutoRenewTimeUnit: "year", + // 实例id集合 必选 + InstanceIds: []string{ + "rds-y9dJu77d", + "rds-aQFOoncr", + }, +} +err := client.AutoRenew(args) +if err != nil { + fmt.Printf("create auto renew error: %+v\n", err) + return +} +``` +> 注意: +> +> - 用于已创建的实例开启自动续费。 +> - 可以传入多个实例id,多个实例需保证在同一地域。 + + +## 修改同步模式 + +使用以下代码可以修改RDS实例同步模式。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.ModifySyncModeArgs{ + //"Async"异步复制,"Semi_sync"半同步复制。 + SyncMode: "Async", +} +err = client.ModifySyncMode(instanceId, args) +if err != nil { + fmt.Printf("modify syncMode error: %+v\n", err) + return +} +fmt.Printf("modify syncMode success\n") +``` + +## 修改连接信息 + +使用以下代码可以修改RDS域名前缀。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.ModifyEndpointArgs{ + Address: "newAddress", +} +err = client.ModifyEndpoint(instanceId, args) +if err != nil { + fmt.Printf("modify endpoint error: %+v\n", err) + return +} +fmt.Printf("modify endpoint success\n") +``` + +> 注意: +> +> - 只传输域名前缀即可。域名前缀由小写字母和数字组成,以小写字母开头,长度在3-30之间。 + +## 开关公网访问 + +使用以下代码可以修改RDS域名前缀。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.ModifyPublicAccessArgs{ + // true or false + PublicAccess: true, +} +err = client.ModifyPublicAccess(instanceId, args) +if err != nil { + fmt.Printf("modify public access error: %+v\n", err) + return +} +fmt.Printf("modify public access success\n") +``` + + +> 注意: +> +> - true:开启公网访问; false:关闭公网访问。 +## 修改时间窗口 + +使用以下代码可以修改操作时间窗口 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.MaintainTimeArgs{ + MaintainStartTime: "14:00:00", + MaintainDuration: 2, +} +err = client.UpdateMaintainTime(instanceId, args) +if err != nil { + fmt.Printf("update maintain time error: %+v\n", err) + return +} +fmt.Printf("update maintain time success\n") +``` +## 实例开启关闭修改存储自动扩容配置 + +使用以下代码可以开启关闭修改存储自动扩容配置 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.DiskAutoResizeArgs{ + FreeSpaceThreshold: 10, + DiskMaxLimit: 2000, +} +err = client.ConfigDiskAutoResize(instanceId,"open", args) +if err != nil { + fmt.Printf("config disk auto resize error: %+v\n", err) + return +} +fmt.Printf("config disk auto resize success\n") +``` + +## 获取指定实例的自动扩容配置信息 + +使用以下代码可以获取指定实例的自动扩容配置信息 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err = client.GetAutoResizeConfig(instanceId) +if err != nil { + fmt.Printf("get config error: %+v\n", err) + return +} +fmt.Printf("get config success\n") +``` + +## 实例是否支持启用自动扩容 + +使用以下代码可以实例是否支持启用自动扩容 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err = client.EnableAutoExpansion(instanceId) +if err != nil { + fmt.Printf("get enable auto expansion error: %+v\n", err) + return +} +fmt.Printf("get enable auto expansion success\n") +``` + +## 可用区迁移 + +使用以下代码可以操作实例可用区迁移 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.AzoneMigration{ + MasterAzone: "cn-bj-d", + BackupAzone: "cn-bj-e", + ZoneNames: []string{"cn-bj-d", "cn-bj-e"}, + Subnets: []SubnetMap{ + { + ZoneName: "cn-bj-d", + SubnetId: "sbn-nedt51qre6r2", + }, + { + ZoneName: "cn-bj-e", + SubnetId: "sbn-hc20wss3idai", + }, + }, + EffectiveTime: "timewindow", +} +result, err = client.AzoneMigration(instanceId, args) +if err != nil { + fmt.Printf("azone migration error: %+v\n", err) + return +} +fmt.Printf("azone migration success\n") +``` +# 账号管理 + +## 创建账号 + +使用以下代码可以在某个主实例下创建一个新的账号。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +args := &rds.CreateAccountArgs{ + // 账号名称,不能为保留关键字,必选 + AccountName: "accountName", + // 账号的密码,由字母、数字或下划线组成,长度6~32位,密码需要加密传输,禁止明文传输,必选 + Password: "password", + // 账号权限类型,Common:普通帐号,Super:super账号。默认为普通账号,可选 + AccountType: "Common", + // MySQL和SQL Server实例可设置此项,可选 + DatabasePrivileges: []rds.DatabasePrivilege{ + { + //数据库名称 + DbName: "user_photo_001", + //授权类型。ReadOnly:只读,ReadWrite:读写 + AuthType: "ReadOnly", + }, + }, + // 帐号的描述信息,可选 + Desc: "账号user1", + // 帐号归属类型,OnlyMaster:主实例上使用的帐号,RdsProxy:该主实例对应的代理实例上使用的帐号。默认为OnlyMaster账号,可选 + Type: "OnlyMaster", +} +err = client.CreateAccount(instanceId, args) +if err != nil { + fmt.Printf("create account error: %+v\n", err) + return +} + +fmt.Println("create account success.") +``` + +> 注意: +> - 实例状态为Available,实例必须是主实例。 +> - 没有超出实例最大账号数量。 +> - 若实例的数据库引擎为PostgreSQL,则只允许创建Super账号。其它账号和数据库操作通过这个Super账号来管理。 +> - 若实例的数据库引擎为MySQL,则允许创建任意类型的账号。 +> - 若实例的数据库引擎为SQLServer,则只允许创建Common账号。 + +## 查询账号列表 + +使用以下代码可以查询指定实例的账号列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.ListAccount(instanceId) +if err != nil { + fmt.Printf("list account error: %+v\n", err) + return +} + +// 获取account的列表信息 +for _, e := range result.Accounts { + fmt.Println("rds accountName: ", e.AccountName) + fmt.Println("rds desc: ", e.Desc) + fmt.Println("rds status: ", e.Status) + fmt.Println("rds type: ", e.Type) + fmt.Println("rds accountType: ", e.AccountType) +} +``` + +## 查询特定账号信息 + +使用以下代码可以查询特定账号信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.GetAccount(instanceId,accountName) +if err != nil { + fmt.Printf("get account error: %+v\n", err) + return +} + +// 获取account的列表信息 +fmt.Println("rds accountName: ", result.AccountName) +fmt.Println("rds desc: ", result.Desc) +fmt.Println("rds status: ", result.Status) +fmt.Println("rds type: ", result.Type) +fmt.Println("rds accountType: ", result.AccountType) +``` +## 更新账号描述信息 + +使用以下代码可以更新账号描述信息 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &ModifyAccountDesc{ + Remark: "test", +} +err := client.ModifyAccountDesc(instanceId,accountName,args) +if err != nil { + fmt.Printf("modify account desc error: %+v\n", err) + return +} +fmt.Printf("modify account desc success\n") +``` + +## 删除特定账号信息 + +使用以下代码可以删除特定账号信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.DeleteAccount(instanceId,accountName) +if err != nil { + fmt.Printf("delete account error: %+v\n", err) + return +} +fmt.Printf("delete account success\n") +``` +## 更新账号密码 + +使用以下代码可以更新账号密码 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &UpdatePasswordArgs{ + Password: "test", +} +err := client.UpdateAccountPassword(instanceId,accountName,args) +if err != nil { + fmt.Printf("update account password error: %+v\n", err) + return +} +fmt.Printf("update account password success\n") +``` +## 更新账号权限 +使用以下代码可以更新账号密码 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &UpdateAccountPrivileges{ + DatabasePrivileges: []DatabasePrivilege{{ + DbName: "test_db", + AuthType: "ReadOnly", + }}, +} +err := client.UpdateAccountPrivileges(instanceId,accountName,args) +if err != nil { + fmt.Printf("update account privilege error: %+v\n", err) + return +} +fmt.Printf("update account privilege success\n") +``` +# 参数管理 + +## 获取参数列表 + +使用以下代码可以获取一个实例下的数据库参数列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.ListParameters(instanceId) +if err != nil { + fmt.Printf("get parameter list error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Printf("get parameter list success\n") +fmt.Println(result.Etag) +``` + +> 注意: +> +> - 在修改配置参数时需要通过该接口获取Etag。 + +## 修改配置参数 + +使用以下代码可以云数据库 RDS for MySQL 的参数配置。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.ListParameters(instanceId) +if err != nil { + fmt.Printf("get parameter list error: %+v\n", err) + return +} +fmt.Printf("get parameter list success\n") +fmt.Println(result.Etag) + +args := &rds.UpdateParameterArgs{ + Parameters: []rds.KVParameter{ + { + Name: "connect_timeout", + Value: "15", + }, + }, + } +er := client.UpdateParameter(instanceId, result.Etag, args) +if er != nil { + fmt.Printf("update parameter error: %+v\n", er) + return +} +fmt.Printf("update parameter success\n") +``` + +> 注意: +> +> - 在修改配置参数时需要通过获取参数列表接口获取最新的Etag。 + +## 参数修改历史 + +使用以下代码可以云数据库 RDS for MySQL 的参数配置。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.ParameterHistory(instanceId) +if err != nil { + fmt.Printf("get parameter history error: %+v\n", err) + return +} +fmt.Printf("get parameter history success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +# 数据库管理 + +## 修改数据库端口 + +使用以下代码可以修改数据库端口 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.UpdateDatabasePortArgs{ + EntryPort: 3309, +}) +err := client.UpdateDatabasePort(instanceId, args) +if err != nil { + fmt.Printf("update database port error: %+v\n", err) + return +} +fmt.Printf("update database port success\n") + +``` + +## 获取数据库列表 + +使用以下代码可以获取数据库列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.ListDatabases(instanceId) +if err != nil { + fmt.Printf("get database list error: %+v\n", err) + return +} +fmt.Printf("get database list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) + +``` + +## 修改数据库描述 + +使用以下代码可以修改数据库描述 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ModifyDatabaseDesc{ + Remark: "test", +} +err := client.ModifyDatabaseDesc(instanceId, "test_db", args) +if err != nil { + fmt.Printf("modify database discription error: %+v\n", err) + return +} +fmt.Printf("modify database discriptio success\n") + +``` + +## 删除数据库 + +使用以下代码可以删除数据库 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +err := client.DeleteDatabase(instanceId, "test_db") +if err != nil { + fmt.Printf("delete database error: %+v\n", err) + return +} +fmt.Printf("delete database success\n") + +``` +## 创建数据库 + +使用以下代码可以创建数据库 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.CreateDatabaseArgs{ + CharacterSetName: "utf8", + DbName: "test_db", + Remark: "test_db", + AccountPrivileges: []AccountPrivilege{ + { + AccountName: "baidu", + AuthType: "ReadOnly", + }, + }, +} +err := client.CreateDatabase(instanceId, args) +if err != nil { + fmt.Printf("create database error: %+v\n", err) + return +} +fmt.Printf("create database success\n") + +``` + +# 任务管理 + +## 获取任务列表 + +使用以下代码可以获取任务列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.TaskListArgs{ + InstanceId: instanceId, +} +result, err := client.TaskList(args) +if err != nil { + fmt.Printf("get task list error: %+v\n", err) + return +} +fmt.Printf("get task list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +# 回收站管理 + +## 查询回收站实例列表 + +使用以下代码可以获取回收站实例列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ListRdsArgs{} +result, err := client.ListRecyclerInstance(args) +if err != nil { + fmt.Printf("get recycle list error: %+v\n", err) + return +} +fmt.Printf("get recycle list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 实例开机 + +使用以下代码可以开机。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.RecyclerRecoverArgs{ + InstanceIds: []string{instanceId}, +} +err := client.RecyclerRecover(args) +if err != nil { + fmt.Printf("recycler recover error: %+v\n", err) + return +} +fmt.Printf("recycler recover success\n") +``` +## 删除单个回收站实例 + +使用以下代码可以删除单个回收站实例 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +err := client.DeleteRecyclerInstance(instanceId) +if err != nil { + fmt.Printf("delete error: %+v\n", err) + return +} +fmt.Printf("delete success\n") +``` + +# 实例组管理 + +## 创建实例组 +使用以下代码可以创建实例组。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.InstanceGroupArgs{ + Name: "test_group", + LeaderId: instanceId, +} +err := client.CreateInstanceGroup(args) +if err != nil { + fmt.Printf("create instance group error: %+v\n", err) + return +} +fmt.Printf("create instance group success\n") +``` + +## 实例组列表 +使用以下代码可以获取实例组列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ListInstanceGroupArgs{ + Manner: "page", +} +result, err := client.ListInstanceGroup(args) +if err != nil { + fmt.Printf("get instance group list error: %+v\n", err) + return +} +fmt.Printf("get instance group list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 实例组详情 +使用以下代码可以获取实例组详情 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.InstanceGroupDetail(groupId) +if err != nil { + fmt.Printf("get instance group detail error: %+v\n", err) + return +} +fmt.Printf("get instance group detail success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 实例组前置检查-GTID检查 +使用以下代码可以进行GTID检查 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.CheckGtidArgs{ + InstanceId: instanceId, +} +result, err := client.InstanceGroupCheckGtid(args) +if err != nil { + fmt.Printf("GTID check error: %+v\n", err) + return +} +fmt.Printf("GTID check success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 实例组前置检查-连通性检查 +使用以下代码可以进行连通性检查 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.CheckPingArgs{ + SourceId: instanceId, + TargetId: instanceId, +} +result, err := client.InstanceGroupCheckPing(args) +if err != nil { + fmt.Printf("check ping error: %+v\n", err) + return +} +fmt.Printf("check ping success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 实例组前置检查-数据检查 +使用以下代码可以进行数据检查 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.CheckDataArgs{ + InstanceId: instanceId, +} +result, err := client.InstanceGroupCheckData(args) +if err != nil { + fmt.Printf("check data error: %+v\n", err) + return +} +fmt.Printf("check data success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 小版本前置检查 +使用以下代码可以进行小版本前置检查 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.CheckVersionArgs{ + LeaderId: instanceId, + FollowerId: instanceId, +} +result, err := client.InstanceGroupCheckVersion(args) +if err != nil { + fmt.Printf("check data error: %+v\n", err) + return +} +fmt.Printf("check data success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 修改热活实例组的名称 +使用以下代码可以修改热活实例组的名称 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.InstanceGroupNameArgs{ + Name: "test_group_name", +} +err := client.UpdateInstanceGroupName(groupId, args) +if err != nil { + fmt.Printf("update instance group name error: %+v\n", err) + return +} +fmt.Printf("update instance group name success\n") +``` + +## 加入热活实例组 +使用以下代码可以加入热活实例组 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.InstanceGroupAddArgs{ + FollowerId: instanceId, +} +err := client.InstanceGroupAdd(groupId, args) +if err != nil { + fmt.Printf("add instance group error: %+v\n", err) + return +} +fmt.Printf("add instance group success\n") +``` + +## 批量加入热活实例组 +使用以下代码可以批量加入热活实例组 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.InstanceGroupBatchAddArgs{ + FollowerIds: []string{instanceId}, + Name: "test_group_name", + LeaderId: instanceId, +} +err := client.InstanceGroupBatchAdd(args) +if err != nil { + fmt.Printf("batch add instance group error: %+v\n", err) + return +} +fmt.Printf("batch add instance group success\n") +``` +## 强制切换热活实例组 +使用以下代码可以强制切换热活实例组 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ForceChangeArgs{ + LeaderId: instanceId, + Force: 0, +} +err := client.InstanceGroupForceChange(groupId, args) +if err != nil { + fmt.Printf("instance group force change error: %+v\n", err) + return +} +fmt.Printf("instance group force change success\n") +``` +## 主角色变更 +使用以下代码可以主角色变更 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GroupLeaderChangeArgs{ + LeaderId: instanceId, +} +err := client.InstanceGroupLeaderChange(groupId, args) +if err != nil { + fmt.Printf("instance group leader change error: %+v\n", err) + return +} +fmt.Printf("instance group leader change success\n") +``` + +## 退出热活实例组 +使用以下代码可以退出热活实例组 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +err := client.InstanceGroupRemove(groupId, instanceId) +if err != nil { + fmt.Printf("instance group remove error: %+v\n", err) + return +} +fmt.Printf("instance group remove success\n") +``` + +## 删除热活实例组 +使用以下代码可以删除热活实例组 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +err := client.DeleteInstanceGroup(groupId) +if err != nil { + fmt.Printf("delete instance group error: %+v\n", err) + return +} +fmt.Printf("delete instance group success\n") +``` + +# 版本管理 +## 查看实例允许升级的小版本列表 + +使用以下代码可以查看实例允许升级的小版本列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.InstanceMinorVersionList(instanceId) +if err != nil { + fmt.Printf("get instance minor version list error: %+v\n", err) + return +} +fmt.Printf("get instance minor version list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) + +``` +## 实例升级小版本 + +使用以下代码可以升级小版本 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.UpgradeMinorVersionArgs{ + TargetMinorVersion: "5.7.38", + EffectiveTime: "immediate", +} +err := client.InstanceUpgradeMinorVersion(instanceId, args) +if err != nil { + fmt.Printf("update instance minor version list error: %+v\n", err) + return +} +fmt.Printf("update instance minor version list success\n") + +``` +# SmartDBA +## 查询慢SQL诊断开通状态 +使用以下代码可以查询慢SQL诊断开通状态 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.SlowSqlFlowStatus(instanceId) +if err != nil { + fmt.Printf("get slow sql flow status error: %+v\n", err) + return +} +fmt.Printf("get slow sql flow status success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 开通慢SQL诊断 + +使用以下代码可以开通慢SQL诊断 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +err := client.EnableSlowSqlFlow(instanceId) +if err != nil { + fmt.Printf("enable slow sql flow error: %+v\n", err) + return +} +fmt.Printf("enable slow sql flow success\n") + +``` +## 关闭慢SQL诊断 + +使用以下代码可以关闭慢SQL诊断 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +err := client.DisableSlowSqlFlow(instanceId) +if err != nil { + fmt.Printf("disable slow sql flow error: %+v\n", err) + return +} +fmt.Printf("disable slow sql flow success\n") + +``` + +## 获取慢SQL诊断列表 + +使用以下代码可以获取慢SQL诊断列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &GetSlowSqlArgs{} +result, err := client.GetSlowSqlList(instanceId, args) +if err != nil { + fmt.Printf("get slow sql flow list error: %+v\n", err) + return +} +fmt.Printf("get slow sql flow list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 根据SQLID获取慢SQL + +使用以下代码可以根据SQLID获取慢SQL + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowSqlBySqlId(instanceId, sqlId) +if err != nil { + fmt.Printf("get slow sql detail by sqlid error: %+v\n", err) + return +} +fmt.Printf("get slow sql detail by sqlid success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取慢SQL说明 + +使用以下代码可以获取慢SQL说明 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowSqlExplain(instanceId, sqlId, db) +if err != nil { + fmt.Printf("get slow sql explain error: %+v\n", err) + return +} +fmt.Printf("get slow sql explain success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 获取SQL模板维度的统计信息 + +使用以下代码可以获取SQL模板维度的统计信息 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetSlowSqlArgs{} +result, err := client.GetSlowSqlStatsDigest(instanceId, args) +if err != nil { + fmt.Printf("get slow sql stats digest error: %+v\n", err) + return +} +fmt.Printf("get slow sql stats digest success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 获取慢SQL耗时分布 + +使用以下代码可以获取慢SQL耗时分布 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetSlowSqlDurationArgs{} +result, err := client.GetSlowSqlDuration(instanceId, args) +if err != nil { + fmt.Printf("get slow sql duration error: %+v\n", err) + return +} +fmt.Printf("get slow sql duration success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取慢SQL来源IP分布 + +使用以下代码可以获取慢SQL来源IP分布 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetSlowSqlSourceArgs{} +result, err := client.GetSlowSqlSource(instanceId, args) +if err != nil { + fmt.Printf("get slow sql source error: %+v\n", err) + return +} +fmt.Printf("get slow sql source success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取慢SQL中的表 + +使用以下代码可以获取慢SQL中的表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowSqlSchema(instanceId, sqlId, db) +if err != nil { + fmt.Printf("get slow sql schema error: %+v\n", err) + return +} +fmt.Printf("get slow sql schema success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取慢SQL中的列 + +使用以下代码可以获取慢SQL中的列 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowSqlTable(instanceId, sqlId, db, table) +if err != nil { + fmt.Printf("get slow sql table error: %+v\n", err) + return +} +fmt.Printf("get slow sql table success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 获取慢SQL表中的索引 + +使用以下代码可以获取慢SQL表中的索引 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetSlowSqlIndexArgs{ + SqlId: "e9fa9802-0d0e-41b4-b3ba-6496466b6cad", + Schema: "db1", + Table: "table1", +} +result, err := client.GetSlowSqlIndex(instanceId, args) +if err != nil { + fmt.Printf("get slow sql index error: %+v\n", err) + return +} +fmt.Printf("get slow sql index success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取慢SQL趋势 + +使用以下代码可以获取慢SQL趋势 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetSlowSqlTrendArgs{ + Start: "2023-05-05T05:30:13.000Z", + End: "2023-05-06T05:30:13.000Z", +} +result, err := client.GetSlowSqlTrend(instanceId, args) +if err != nil { + fmt.Printf("get slow sql trend error: %+v\n", err) + return +} +fmt.Printf("get slow sql trend success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取慢SQL调优建议 + +使用以下代码可以获取慢SQL调优建议 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowSqlAdvice(instanceId, sqlId, db) +if err != nil { + fmt.Printf("get slow sql advice error: %+v\n", err) + return +} +fmt.Printf("get slow sql advice success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取库表空间概况 + +使用以下代码可以获取库表空间概况 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetDiskInfo(instanceId) +if err != nil { + fmt.Printf("get disk info error: %+v\n", err) + return +} +fmt.Printf("get disk info success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取数据空间的数据库列表 + +使用以下代码可以获取数据空间的数据库列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetDbListSize(instanceId) +if err != nil { + fmt.Printf("get db list size info error: %+v\n", err) + return +} +fmt.Printf("get db list size info success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取数据空间表的详情 + +使用以下代码可以获取数据空间表的详情 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetTableListArgs{ + DbName: "db1", +} +result, err := client.GetTableListInfo(instanceId, args) +if err != nil { + fmt.Printf("get table list error: %+v\n", err) + return +} +fmt.Printf("get table list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取指定会话kill类型的相关参数 + +使用以下代码可以获取指定会话kill类型的相关参数 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetKillSessionTypes(instanceId) +if err != nil { + fmt.Printf("get kill session types error: %+v\n", err) + return +} +fmt.Printf("get kill session types success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取指定实例的会话概览 + +使用以下代码可以获取指定实例的会话概览 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSessionSummary(instanceId) +if err != nil { + fmt.Printf("get kill session summary error: %+v\n", err) + return +} +fmt.Printf("get kill session summary success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取指定实例的实时会话 + +使用以下代码可以获取指定实例的实时会话 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.SessionDetailArgs{} +result, err := client.GetSessionDetail(instanceId, args) +if err != nil { + fmt.Printf("get session detail error: %+v\n", err) + return +} +fmt.Printf("get session detail success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 校验执行kill操作的数据库用户及密码是否正确 + +使用以下代码可以校验执行kill操作的数据库用户及密码是否正确 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.KillSessionAuthArgs{} +result, err := client.CheckKillSessionAuth(instanceId, args) +if err != nil { + fmt.Printf("check kill session auth error: %+v\n", err) + return +} +fmt.Printf("check kill session auth success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取指定实例的会话kill记录 + +使用以下代码可以获取指定实例的会话kill记录 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.KillSessionHistory{} +result, err := client.GetKillSessionHistory(instanceId, args) +if err != nil { + fmt.Printf("get kill session history error: %+v\n", err) + return +} +fmt.Printf("get kill session history success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 根据传入的kill类型及类型所对应的值执行kill会话的操作 + +使用以下代码可以根据传入的kill类型及类型所对应的值执行kill会话的操作 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.KillSessionArgs{} +result, err := client.KillSession(instanceId, args) +if err != nil { + fmt.Printf("kill session error: %+v\n", err) + return +} +fmt.Printf("kill session success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取指定实例的会话统计 + +使用以下代码可以获取指定实例的会话统计 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSessionStatistics(instanceId) +if err != nil { + fmt.Printf("get session statistics error: %+v\n", err) + return +} +fmt.Printf("get session statistics success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 查询错误日志服务是否开启 + +使用以下代码可以查询错误日志服务是否开启 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetErrorLogStatus(instanceId) +if err != nil { + fmt.Printf("get error log status error: %+v\n", err) + return +} +fmt.Printf("get error log status success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 开启错误日志服务 + +使用以下代码可以开启错误日志服务 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.EnableErrorLog(instanceId) +if err != nil { + fmt.Printf("enable error log status error: %+v\n", err) + return +} +fmt.Printf("enable error log status success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 关闭错误日志服务 + +使用以下代码可以关闭错误日志服务 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.DisableErrorLog(instanceId) +if err != nil { + fmt.Printf("disable error log status error: %+v\n", err) + return +} +fmt.Printf("disable error log status success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取错误日志列表 + +使用以下代码可以获取错误日志列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ErrorLogListArgs{} +result, err := client.GetErrorLogList(instanceId, args) +if err != nil { + fmt.Printf("get error log list error: %+v\n", err) + return +} +fmt.Printf("get error log list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 获取实例限流规则列表 + +使用以下代码可以获取实例限流规则列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSqlFilterList(instanceId) +if err != nil { + fmt.Printf("get sql filter list error: %+v\n", err) + return +} +fmt.Printf("get sql filter list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 获取某个限流规则详情 + +使用以下代码可以获取某个限流规则详情 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSqlFilterDetail(instanceId, filterId) +if err != nil { + fmt.Printf("get sql filter detail error: %+v\n", err) + return +} +fmt.Printf("get sql filter detail success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 添加一条限流规则 + +使用以下代码可以添加一条限流规则 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.SqlFilterArgs{ + FilterType: "SELECT", + FilterKey: "123", + FilterLimit: 0, +} +result, err := client.AddSqlFilter(instanceId, args) +if err != nil { + fmt.Printf("add sql filter error: %+v\n", err) + return +} +fmt.Printf("add sql filter success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 更新一条限流规则 + +使用以下代码可以更新一条限流规则 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.SqlFilterArgs{ + FilterType: "SELECT", + FilterKey: "123", + FilterLimit: 0, +} +result, err := client.UpdateSqlFilter(instanceId, args) +if err != nil { + fmt.Printf("update sql filter error: %+v\n", err) + return +} +fmt.Printf("update sql filter success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 开启关闭某个限流规则 + +使用以下代码可以开启关闭某个限流规则 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.StartOrStopSqlFilterArgs{ + Action: "OFF", +} +result, err := client.StartOrStopSqlFilter(instanceId, filterId, args) +if err != nil { + fmt.Printf("start or stop sql filter error: %+v\n", err) + return +} +fmt.Printf("start or stop sql filter success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 删除某个限流规则 + +使用以下代码可以删除某个限流规则 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.DeleteSqlFilter(instanceId, filterId) +if err != nil { + fmt.Printf("delete sql filter error: %+v\n", err) + return +} +fmt.Printf("delete sql filter success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 实例是否支持限流 + +使用以下代码可以实例是否支持限流 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" + +result, err := client.IsAllowedSqlFilter(instanceId) +if err != nil { + fmt.Printf("is allowed sql filter error: %+v\n", err) + return +} +fmt.Printf("is allowed sql filter success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +# Performance +## Kill会话 + +使用以下代码可以Kill会话 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &ProcessArgs{ + Ids: []int64{123}, +} + +err := client.ProcessKill(instanceId, args) +if err != nil { + fmt.Printf("process kill error: %+v\n", err) + return +} +fmt.Printf("process kill success\n") +``` +## 查询innodbstatus快照数据 + +使用以下代码可以查询innodbstatus快照数据 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.InnodbStatus(instanceId) +if err != nil { + fmt.Printf("get innodb status error: %+v\n", err) + return +} +fmt.Printf("get innodb status success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` + +## 查询processlist快照数据 + +使用以下代码可以查询processlist快照数据 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.ProcessList(instanceId) +if err != nil { + fmt.Printf("get process list error: %+v\n", err) + return +} +fmt.Printf("get process list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 查询事务列表 + +使用以下代码可以查询事务列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.TransactionList(instanceId) +if err != nil { + fmt.Printf("get transaction list error: %+v\n", err) + return +} +fmt.Printf("get transaction list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +## 查询连接列表 + +使用以下代码可以查询连接列表 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.ConnectionList(instanceId) +if err != nil { + fmt.Printf("get ConnectionList list error: %+v\n", err) + return +} +fmt.Printf("get ConnectionList list success\n") +jsonData, _ := json.Marshal(result) +fmt.Println(string(jsonData)) +``` +# 备份管理 + +## 获取备份列表 + +使用以下代码可以获取一个实例下的备份列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.GetBackupListArgs{} +_, err := client.GetBackupList(instanceId, args) +if err != nil { + fmt.Printf("get backup list error: %+v\n", err) + return +} +fmt.Printf("get backup list success\n") +``` + +> 注意: +> +> - 请求参数 marker 和 maxKeys 不是必须的。 + +## 获取备份详情 + +使用以下代码可以获取一个实例备份的详情信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetBackupDetail(instanceId, backupId) +if err != nil { + fmt.Printf("get backup detail error: %+v\n", err) + return +} +fmt.Printf("get backup detail success\n") +``` + +## 删除备份 + +使用以下代码可以删除手动备份 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +_, err := client.DeleteBackup(instanceId, backupId) +if err != nil { + fmt.Printf("delete backup detail error: %+v\n", err) + return +} +fmt.Printf("delete backup detail success\n") +``` +## 更新备份策略 + +使用以下代码可以更新一个实例的备份策略。 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ModifyBackupPolicyArgs{ + BackupDays: "1,3", + BackupTime: "10:00:00Z", + Persistent: true, + ExpireInDays: 20, +} +err := client.ModifyBackupPolicy(instanceId, args) +if err != nil { + fmt.Printf("modify backup policy error: %+v\n", err) + return +} +fmt.Printf("modify backup policy success\n") +``` +## 获取binlog列表 + +使用以下代码可以获取binlog列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetBinlogList(instanceId, detaTime) +if err != nil { + fmt.Printf("get binlog list error: %+v\n", err) + return +} +fmt.Printf("get binlog list success\n") +``` + +## 获取binlog信息 + +使用以下代码可以获取binlog信息 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetBinlogInfo(instanceId, binlogId, downloadValidTimeInSec) +if err != nil { + fmt.Printf("get binlog detail error: %+v\n", err) + return +} +fmt.Printf("get binlog detail success\n") +``` + +## 按时间点进行库表恢复 + +使用以下代码可以按时间点进行库表恢复 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +recoveryByDatetimeArgs := &RecoveryByDatetimeArgs{ + Datetime: "2022-01-11T16:05:52Z", + Data: []RecoveryData{ + { + DbName: "test_db", + NewDbname: "new_test_db", + RestoreMode: "database", + Tables: []TableData{ + { + TableName: "table_name", + NewTablename: "new_table_name", + }, + }, + }, + }, +} +err := client.RecoveryToSourceInstanceByDatetime(instanceId, recoveryByDatetimeArgs) +if err != nil { + fmt.Printf("recovery by datetime error: %+v\n", err) + return +} +fmt.Printf("recovery by datetime success\n") +``` +## 按备份集进行库表恢复 + +使用以下代码可以按备份集进行库表恢复 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +recoveryBySnapshotArgs := &RecoveryBySnapshotArgs{ + SnapshotId: "1691734023130272802", + Data: []RecoveryData{ + { + DbName: "test_db", + NewDbname: "new_test_db", + RestoreMode: "database", + Tables: []TableData{ + { + TableName: "table_name", + NewTablename: "new_table_name", + }, + }, + }, + }, +} +err := client.RecoveryToSourceInstanceBySnapshot(instanceId, recoveryBySnapshotArgs) +if err != nil { + fmt.Printf("recovery by snapshot error: %+v\n", err) + return +} +fmt.Printf("recovery by snapshot success\n") +``` +# 慢日志下载任务 + +## 慢日志下载任务列表 +``` go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowLogDownloadTaskList(instanceId, datetime) +if err != nil { + fmt.Printf("get slowlog download task list error: %+v\n", err) + return +} +fmt.Printf("get slowlog download task list success\n") +fmt.Printf(result) +``` +## 慢日志下载详情 +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSlowLogDownloadDetail(instanceId, logId, downloadValidTimeInSec) +if err != nil { + fmt.Printf("get slowlog download detail error: %+v\n", err) + return +} +fmt.Printf("get slowlog download detail success\n") +fmt.Printf(result) +``` +# 其它 + +## 获取可用区列表 + +使用以下代码可以获取可用区列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +err = client.GetZoneList() +if err != nil { + fmt.Printf("get zone list error: %+v\n", err) + return +} +fmt.Printf("get zone list success\n") +fmt.Println("rds instanceId: ", result.InstanceId) +``` + +## 获取子网列表 + +使用以下代码可以获取一个实例下的子网列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +args := &rds.ListSubnetsArgs{} +_, err := client.ListSubnets(args) +if err != nil { + fmt.Printf("get subnet list error: %+v\n", err) + return +} +fmt.Printf("get subnet list success\n") +``` + +> 注意: +> +> - 请求参数 vpcId 和 zoneName 不是必须的。 + +## 查看白名单 + +使用以下代码可以获取一个实例下的白名单列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSecurityIps(instanceId) +if err != nil { + fmt.Printf("get securityIp list error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Println(result.Etag) +fmt.Printf("get securityIp list success\n") +``` + +> 注意: +> +> - 在更新白名单时需要通过该接口获取最新的Etag。 + +## 更新白名单 + +使用以下代码可以更新一个实例下的白名单列表。 + +```go +// import "github.com/baidubce/bce-sdk-go/services/rds" +result, err := client.GetSecurityIps(instanceId) +if err != nil { + fmt.Printf("get securityIp list error: %+v\n", err) + return +} +fmt.Println(result.Etag) +fmt.Printf("get securityIp list success\n") + +args := &rds.UpdateSecurityIpsArgs{ + SecurityIps: []string{ + "%", + "192.0.0.1", + "192.0.0.2", + }, + } +er := client.UpdateSecurityIps(instanceId, result.Etag, args) +if er != nil { + fmt.Printf("update securityIp list error: %+v\n", er) + return +} +fmt.Printf("update securityIp list success\n") +``` + +> 注意: +> +> - 在更新白名单时需要通过查看白名单接口获取最新的Etag。 +> - 白名单需要全量更新,每次更新需要把全部白名单列表都添加上。 + +# 错误处理 + +GO语言以error类型标识错误,RDS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | RDS服务返回的错误 + +用户使用SDK调用RDS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// rdsClient 为已创建的RDS Client对象 +result, err := client.ListRds() +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向RDS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当RDS服务端出现异常时,RDS服务端会返回给用户相应的错误信息,以便定位问题。 + +## SDK日志 + +RDS GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +RDS GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the RDS go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the RDS go sdk") +``` + + + +首次发布: + + - 支持创建RDS主实例、创建RDS只读实例、创建RDS代理实例、查询RDS列表、查询指定RDS实例信息、删除RDS实例、RDS实例扩缩容、创建账号、查询账号列表、查询特定账号信息、删除特定账号信息。 \ No newline at end of file diff --git a/bce-sdk-go/doc/SCS.md b/bce-sdk-go/doc/SCS.md new file mode 100644 index 0000000..606402d --- /dev/null +++ b/bce-sdk-go/doc/SCS.md @@ -0,0 +1,1537 @@ +# SCS服务 + +# 概述 + +本文档主要介绍SCS GO SDK的使用。在使用本文档前,您需要先了解SCS的一些基本知识。若您还不了解SCS,可以参考[产品描述](https://cloud.baidu.com/doc/SCS/s/Rjxbm160f)和[入门指南](https://cloud.baidu.com/doc/SCS/s/6jxyfy2ly)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[SCS访问域名](https://cloud.baidu.com/doc/SCS/s/fjwvxtrd9)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云SCS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问SCS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建SCS Client + +SCS Client是SCS服务的客户端,为开发者与SCS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建SCS Client + +通过AK/SK方式访问SCS,用户可以参考如下代码新建一个SCS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/scs" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个SCSClient + scsClient, err := scs.NewClient(ACCESS_KEY_ID, SECRET_ACCESS_KEY, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/SCS/s/ojwvynrqn)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为SCS的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`redis.bj.baidubce.com`。 + +### 使用STS创建SCS Client + +**申请STS token** + +SCS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问SCS,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7)。 + +**用STS token新建SCS Client** + +申请好STS后,可将STS Token配置到SCS Client中,从而实现通过STS Token创建SCS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建SCS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/scs" //导入SCS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建SCS服务的Client对象,Endpoint使用默认值 + scsClient, err := scs.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create scs client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + scsClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置SCS Client时,无论对应SCS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问SCS + +SCS支持HTTPS传输协议,您可以通过在创建SCS Client对象时指定的Endpoint中指明HTTPS的方式,在SCS GO SDK中使用HTTPS访问SCS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/scs" + +ENDPOINT := "https://redis.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +scsClient, _ := scs.NewClient(AK, SK, ENDPOINT) +``` + +## 配置SCS Client + +如果用户需要配置SCS Client的一些细节的参数,可以在创建SCS Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问SCS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/scs" + +//创建SCS Client对象 +AK, SK := , +ENDPOINT := "redis.bj.baidubce.com" +client, _ := scs.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/scs" + +AK, SK := , +ENDPOINT := "redis.bj.baidubce.com" +client, _ := scs.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/scs" + +AK, SK := , +ENDPOINT := "redis.bj.baidubce.com" +client, _ := scs.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问SCS时,创建的SCS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建SCS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# 主要接口 + +云数据库 SCS(Simple Cache Service)提供稳定、高效以及高可扩展性的分布式缓存服务。云数据库 SCS 兼容 Redis/Memcached 协议,基于 Redis 提供标准版和集群版的架构模式,并支持自定义副本数量,为您提供多样化的数据结构支持。 + +## 实例管理 + +### 创建实例 + +使用以下代码可以创建SCS实例,用于创建一个或多个redis实例 +```go +args := &scs.CreateInstanceArgs{ + // 选择付款方式,可以选择预付费或后付费 + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + // 购买个数,最大不超过10,默认1 + PurchaseCount: 1, + // 实例名 + // 要求:1)支持大小写字母、数字以及-_ /.等特殊字符,必须以字母开头;2)长度限制为1-64; + InstanceName: "sdk-scs", + // 端口号 1025 **提示:** +> 1. 创建SCS请求是一个异步请求,返回200表明订单生成,后续可以通过实例id查询实例创建进度。 +> 2. 本接口用于创建一个或多个同配置SCS实例。 +> 3. 创建实例需要实名认证,没有通过实名认证的可以前往百度开放云官网控制台中的安全认证下的实名认证中进行认证。 +> 4. 创建计费方式为后付费的实例需要账户现金余额+通用代金券大于100;预付费方式的实例则需要账户现金余额大于等于实例费用。 +> 5. 支支持批量创建,且如果创建过程中有一个实例创建失败,所有实例将全部回滚。 +> 6. 创建请求详细使用请参考SCS API 文档[创建实例](https://cloud.baidu.com/doc/SCS/s/hk0qhwxom) +> 7. 创建SCS需要使用指定规格, 详细请参考SCS API 文档[实例规格](https://cloud.baidu.com/doc/SCS/s/1jwvxtsh0#%E5%AE%9E%E4%BE%8B%E8%A7%84%E6%A0%BC) + + +### 查询实例列表 + +以下代码可以查询SCS实例列表 +```go +args := &scs.ListInstancesArgs{} + +result, err := client.ListInstances(args) +if err != nil { + fmt.Println("list instance failed:", err) +} else { + fmt.Println("list instance success: ", result) +} +``` + +### 查询指定实例详情 + +使用以下代码可以查询指定SCS虚机的详细信息 +```go +result, err := client.GetInstanceDetail(instanceId) +if err != nil { + fmt.Println("get instance detail failed:", err) +} else + fmt.Println("get instance detail success ", result) +} +``` +### 创建实例价格查询 + +使用以下代码可以查询指定SCS虚机的详细信息 +```go +args := &scs.CreatePriceArgs{ + Engine: 2, + Period: 1, + ChargeType: "prepay", + NodeType: "cache.n1.small", + ReplicationNum: 2, + ClusterType: "cluster", +} +result, err := client.GetCreatePrice(args) +if err != nil { + fmt.Println("get instance price failed:", err) +} else + fmt.Println("get instance price success ", result) +} +``` +### 变配实例价格查询 + +使用以下代码可以查询指定SCS虚机的详细信息 +```go +args := &scs.ResizePriceArgs{ + ChangeType: "nodeModify", + ShardNum: 2, + ReplicationNum: 1, + NodeType: "cache.n1.small", + Period: 1, +} +result, err := client.GetResizePrice(args) +if err != nil { + fmt.Println("get instance price failed:", err) +} else + fmt.Println("get instance price success ", result) +} +``` +### 修改实例名称 + +如下代码可以修改实例名称 +```go +args := &scs.UpdateInstanceNameArgs{ + InstanceName: "newInstanceName", +} +err := client.UpdateInstanceName(instanceId, args) +if err != nil { + fmt.Println("update instance name failed:", err) +} else { + fmt.Println("update instance name success") +} +``` + +> **提示:** +> +> - 只有实例Running状态时可以修改实例名称 + +### 释放实例 + +如下代码可以释放实例,实例将自动进入回收站,保留7天后删除 +```go +err := client.DeleteInstance(instanceId) +if err != nil { + fmt.Println("delete instance failed:", err) +} else { + fmt.Println("delete instance success") +} +``` +> **提示:** +> - 释放单个SCS实例,释放后实例将进入回收站,保留7天后自动删除所有物理资源。 +> - 可以从回收站内恢复实例或者彻底删除实例,预付费实例需要通过续费实例接口进行恢复。 + +## 重启实例 + +使用以下代码可以重启实例。支持用户决定是否延迟到维护窗口内重启。 + +```go +// 立即重启 +args := &scs.RestartInstanceArgs{ + // 需要延迟到维护窗口重启时需传入true + IsDefer: false, +} +err := SCS_CLIENT.RestartInstance(instanceId, args) +if err != nil { + fmt.Println("restart instance failed:", err) +} else { + fmt.Println("restart instance success") +} +``` + +## 续费实例 +使用以下代码可以对已有的预付费实例进行续费,如果实例在回收站中,续费后会从回收站中恢复。 +```go + +// 要恢复的实例Id列表 +instanceIds := []string{ + instancId, +} +args := &scs.RenewInstanceArgs{ + // 实例Id列表 + InstanceIds: instanceIds, + // 续费周期,单位为月 + Duration: 1, +} +result, err := client.RenewInstances(args) +if err != nil { + fmt.Printf("renew instances error: %+v\n", err) + return +} +// 异步任务,返回订单Id +fmt.Println("renew instances success. orderId:" + result.OrderId) +``` + +## 获取回收站中的实例列表 +使用以下代码可以获取回收站中的实例列表。 +```go + +// marker分页参数 +marker := &scs.Marker{MaxKeys: 10} +instances, err := client.ListRecycleInstances(marker) +if err != nil { + fmt.Printf("list recycler instances error: %+v\n", err) + return +} +for _, instance := range instances.Result { + fmt.Println("instanceId: ", instance.InstanceID) + fmt.Println("instanceName: ", instance.InstanceName) + fmt.Println("engine: ", instance.Engine) + fmt.Println("engineVersion: ", instance.EngineVersion) + fmt.Println("instanceStatus: ", instance.InstanceStatus) + // 进入回收站后isolatedStatus为Isolated,表示实例已隔离 + fmt.Println("isolatedStatus: ", instance.IsolatedStatus) + fmt.Println("paymentTiming: ", instance.PaymentTiming) + fmt.Println("clusterType: ", instance.ClusterType) + fmt.Println("domain: ", instance.Domain) + fmt.Println("port: ", instance.Port) + fmt.Println("vnetIP: ", instance.VnetIP) + fmt.Println("instanceCreateTime: ", instance.InstanceCreateTime) + fmt.Println("usedCapacity: ", instance.UsedCapacity) + fmt.Println("zoneNames: ", instance.ZoneNames) + fmt.Println("tags: ", instance.Tags) +} +``` + +## 从回收站中批量恢复实例 +使用以下代码可以从回收站中批量恢复实例,批量恢复仅支持后付费实例,回收站中的预付费实例请通过实例续费接口恢复。 +```go + +// 要恢复的实例Id列表 +instanceIds := []string{ + instanceId_1, + instanceId_2, +} +err := client.RecoverRecyclerInstances(instanceIds) +if err != nil { + fmt.Printf("recover recycler instances error: %+v\n", err) + return +} +fmt.Println("recover recycler instances success.") +``` + +## 从回收站中批量删除实例 +使用以下代码可以从回收站中批量删除实例,实例将被彻底删除。 +```go + +// 要删除的实例Id列表 +instanceIds := []string{ + instanceId_1, + instanceId_2, +} +err := client.DeleteRecyclerInstances(instanceIds) +if err != nil { + fmt.Printf("delete recycler instances error: %+v\n", err) + return +} +fmt.Println("delete recycler instances success.") +``` + +### 添加节点 + +```go +args := &scs.ReplicationArgs{ + ResizeType: "add", // add 添加从节点 add_readonly 添加只读节点 + ReplicationInfo: []Replication{ + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 1}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + }, + ClientToken: getClientToken(), +} +result, err := client.AddReplication(instanceId, args) + +if err != nil { + fmt.Println("resize instance failed:", err) +} else { + fmt.Println("resize instance success") +``` + +### 删除节点 + +```go +args := &scs.ReplicationArgs{ + ResizeType: "delete", // delete 删除节点 delete_readonly 删除只读节点 + ReplicationInfo: []Replication{ + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 1}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + }, + ClientToken: getClientToken(), +} +result, err := client.DeleteReplication(instanceId, args) + +if err != nil { + fmt.Println("resize instance failed:", err) +} else { + fmt.Println("resize instance success") +``` + +### 变更配置 + +```go +args := &scs.ResizeInstanceArgs{ + NodeType:"cache.n1.small", + ShardNum:2, + // 需要延迟到维护窗口变配时需传入true + IsDefer: false, +} +err := client.ResizeInstance(instanceId, args) +if err != nil { + fmt.Println("resize instance failed:", err) +} else { + fmt.Println("resize instance success") +``` + +> **提示:** +> - 实例计费方式为预付费时,不能进行缩容操作 +> - 实例计费方式为后付费时,可弹性扩缩容 +> - 只有实例正常运行状态时才可以进行扩缩容操作,变更接口为异步变更,可通过查询指定实例详情接口查询实例状态 + +### 查询实例套餐规格 + +如下代码可以查询当前可以创建的实例的套餐的规格 +```go +result, err := client.GetNodeTypeList() +if err != nil { + fmt.Println("list node type failed: ", err) +} else { + fmt.Println("list node type success: ", result) +} +``` + +### 获取子网列表 + +如下代码可以获取子网列表 + +```go +args := &scs.ListSubnetsArgs{} +_, err := client.ListSubnets(args) +if err != nil { + fmt.Println("get subnet list failed:", err) +} else { + fmt.Println("get subnet list success") +} +``` + +> **提示:** +> +> - 请求参数 vpcId 和 zoneName 不是必须的 + +### 修改实例域名 + +如下代码可以修改实例域名 + +```go +args := &scs.UpdateInstanceDomainNameArgs{ + Domain: "newDomainName", +} +err := client.UpdateInstanceDomainName(instanceId, args) +if err != nil { + fmt.Println("update instance domain name failed:", err) +} else { + fmt.Println("update instance domain name success") +} +``` + +> **提示:** +> +> - 只有实例Running状态时可以修改实例域名 + +### 获取可用区列表 + +使用以下代码可以获取可用区列表 + +```go +result, err := client.GetZoneList() +if err != nil { + fmt.Println("get zone list failed:", err) +} else + fmt.Println("get zone list success ", result) +} +``` + +### 修改访问密码 + +如下代码可以修改访问密码 + +```go +args := &scs.ModifyPasswordArgs{ + Password: "newPassword", +} +result, err := client.ModifyPassword(instanceId, args) +if err != nil { + fmt.Println("modify password failed:", err) +} else + fmt.Println("modify password success ", result) +} +``` + +> **提示:** +> +> - 密码长度8~16位,至少包含字母、数字和特殊字符中两种。允许的特殊字符包括 $^*()_+-= + +### 变更域名 + +如下代码可以变更域名 + +```go +args := &scs.RenameDomainArgs{ + Domain: "newDomain", + ClientToken: getClientToken(), +} +err := client.RenameDomain(instanceId, args) +if err != nil { + fmt.Println("rename domain failed:", err) +} +``` +### 域名交换 + +如下代码可以域名交换 + +```go +args := &scs.SwapDomainArgs{ + SourceInstanceId: SCS_TEST_ID, + TargetInstanceId: "scs-bj-xeelkkdsx", + ClientToken: getClientToken(), +} +err := client.SwapDomain(instanceId, args) +if err != nil { + fmt.Println("swap domain failed:", err) +} +``` +### 清空实例 + +如下代码可以清空实例 + +```go +args := &scs.FlushInstanceArgs{ + Password: "Password", +} +result, err := client.FlushInstance(instanceId, args) +if err != nil { + fmt.Println("flush instance failed:", err) +} else + fmt.Println("flush instance success ", result) +} +``` + +> **提示:** +> +> - 对redis实例,清空后表现为数据占用内存下降,数据被清空;对memcache实例,清空后表现为占用内存不会下降,但是数据被清空 +> - 如果没有设置密码,传递空字符串 + +### 绑定标签 + +如下代码可以绑定标签 + +```go +args := &scs.BindingTagArgs{ + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, +} +result, err := client.BindingTag(instanceId, args) +if err != nil { + fmt.Println("bind tags failed:", err) +} else + fmt.Println("bind tags success ", result) +} +``` + +### 解绑标签 + +如下代码可以解绑标签 + +```go +args := &scs.BindingTagArgs{ + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, +} +result, err := client.UnBindingTag(instanceId, args) +if err != nil { + fmt.Println("unbind tags failed:", err) +} else + fmt.Println("unbind tags success ", result) +} +``` + +> **提示:** +> +> - 解绑实例上定义的标签 +> - 可以同时解绑多个标签 + +### 设置集群为热活主地域 + +如下代码可以设置集群为热活主地域 + +```go +err := client.SetAsMaster(instanceId) +if err != nil { + fmt.Println("set as master failed:", err) +} else + fmt.Println("set as master success ", result) +} +``` +### 设置集群为热活从地域 + +如下代码可以设置集群为热活从地域 + +```go +args := &scs.SetAsSlaveArgs{ + MasterDomain: "masterDomain", + MasterPort: 6379, +} +err := client.SetAsSlave(instanceId, args) +if err != nil { + fmt.Println("set as slave failed:", err) +} else + fmt.Println("set as slave success ", result) +} +``` +### 查询IP白名单 + +如下代码可以查询允许访问实例的IP白名单 + +```go +result, err := client.GetSecurityIp(instanceId) +if err != nil { + fmt.Println("get security IP failed:", err) +} else + fmt.Println("get security IP success ", result) +} +``` + +> **提示:** +> +> - 返回参数 IP白名单列表, 包括常规地址: 如192.168.0.1,CIDR地址: 如192.168.1.0/24,0.0.0.0/0代表允许所有地址 + +### 增加IP白名单 + +如下代码可以增加访问实例的IP白名单 + +```go +args := &scs.SecurityIpArgs{ + SecurityIps: []string{ + "192.0.0.1", + }, +} +result, err := client.AddSecurityIp(instanceId, args) +if err != nil { + fmt.Println("add security IP failed:", err) +} else + fmt.Println("add security IP success ", result) +} +``` + +### 删除IP白名单 + +如下代码可以删除访问实例的IP白名单 + +```go +args := &scs.SecurityIpArgs{ + SecurityIps: []string{ + "192.0.0.1", + }, +} +result, err := client.DeleteSecurityIp(instanceId, args) +if err != nil { + fmt.Println("delete security IP failed:", err) +} else + fmt.Println("delete security IP success ", result) +} +``` + +## 获取VPC下的安全组 +使用以下代码可以获取指定VPC下的安全组列表。 +```go + +// vpcId := "vpc-j1vaxw1cx2mw" +securityGroups, err := client.ListSecurityGroupByVpcId(vpcId) +if err != nil { + fmt.Printf("list security group by vpcId error: %+v\n", err) + return +} +for _, group := range securityGroups.Groups { + fmt.Println("securityGroup id: ", group.SecurityGroupID) + fmt.Println("name: ", group.Name) + fmt.Println("description: ", group.Description) + fmt.Println("associateNum: ", group.AssociateNum) + fmt.Println("createdTime: ", group.CreatedTime) + fmt.Println("version: ", group.Version) + fmt.Println("defaultSecurityGroup: ", group.DefaultSecurityGroup) + fmt.Println("vpc name: ", group.VpcName) + fmt.Println("vpc id: ", group.VpcShortID) + fmt.Println("tenantId: ", group.TenantID) +} +fmt.Println("list security group by vpcId success.") +``` + +## 获取实例已绑定安全组 +使用以下代码可以获取指定实例已绑定的安全组列表。 +```go + +// instanceId := "scs-m1h4mma5" +result, err := client.ListSecurityGroupByInstanceId(instanceId) +if err != nil { + fmt.Printf("list security group by instanceId error: %+v\n", err) + return +} +for _, group := range result.Groups { + fmt.Println("securityGroupId: ", group.SecurityGroupID) + fmt.Println("securityGroupName: ", group.SecurityGroupName) + fmt.Println("securityGroupRemark: ", group.SecurityGroupRemark) + fmt.Println("projectId: ", group.ProjectID) + fmt.Println("vpcId: ", group.VpcID) + fmt.Println("vpcName: ", group.VpcName) + fmt.Println("inbound: ", group.Inbound) + fmt.Println("outbound: ", group.Outbound) +} +fmt.Println("list security group by instanceId success.") +``` + +## 绑定安全组 +使用以下代码可以批量将指定的安全组绑定到实例上。 +```go + +// instanceIds := []string{ +// "scs-mjafcdu0", +// } +// securityGroupIds := []string{ +// "g-iutg5rtcydsk", +// } +args := &scs.SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, +} + +err := client.BindSecurityGroups(args) +if err != nil { + fmt.Printf("bind security groups to instances error: %+v\n", err) + return +} +fmt.Println("bind security groups to instances success.") +``` +> 注意: +> - 实例状态必须为Available。 +> - 实例ID最多可以传入10个。 +> - 安全组ID最多可以传入10个。 +> - 每个实例最多可以绑定10个安全组。 + +## 解绑安全组 +使用以下代码可以从实例上批量解绑指定的安全组。 +```go +// securityGroupIds := []string{ +// "g-iutg5rtcydsk", +// } +args := &scs.UnbindSecurityGroupArgs{ + InstanceId: "scs-su-bbjhgxyqyddd", + SecurityGroupIds: securityGroupIds, +} +err := client.UnBindSecurityGroups(args) +if err != nil { + fmt.Printf("unbind security groups to instances error: %+v\n", err) + return +} +fmt.Println("unbind security groups to instances success.") +``` +> 注意: +> - 实例状态必须为Available。 +> - 当前版本实例ID最多可以传入1个。 +> - 安全组ID最多可以传入10个。 + +### 获取参数列表 + +使用以下代码可以获取Redis实例的配置参数和运行参数 + +```go +result, err := client.GetParameters(instanceId) +if err != nil { + fmt.Println("get parameter list failed:", err) +} else + fmt.Println("get parameter list success ", result) +} +``` + +### 修改参数 + +如下代码可以修改redis实例参数值 + +```go +args := &scs.ModifyParametersArgs{ + Parameter: InstanceParam{ + Name: "parameter name", + Value: "new value", + }, +} +result, err := client.ModifyParameters(instanceId, args) +if err != nil { + fmt.Println("modify parameters failed:", err) +} else + fmt.Println("modify parameters success ", result) +} +``` + +### 查看备份列表 + +使用以下代码可以查询某个实例备份列表 + +```go +result, err := client.GetBackupList(instanceId) +if err != nil { + fmt.Println("get backup list failed:", err) +} else + fmt.Println("get backup list success ", result) +} +``` +### 获取备份信息 + +使用以下代码可以获取某个实例备份信息 + +```go +result, err := client.GetBackupDetail(instanceId, backupId) +if err != nil { + fmt.Println("get backup detail failed:", err) +} else + fmt.Println("get backup detail success ", result) +} +``` +### 修改备份策略 + +如下代码可以修改redis实例自动备份策略 + +```go +args := &scs.ModifyBackupPolicyArgs{ + BackupDays: "Sun,Mon,Tue,Wed,Thu,Fri,Sta", + BackupTime: "01:05:00", + ExpireDay: 7, +} +result, err := client.ModifyBackupPolicy(instanceId, args) +if err != nil { + fmt.Println("modify backup policy failed:", err) +} else + fmt.Println("modify backup policy success ", result) +} +``` + +> **提示:** +> +> - BackupDays: 标识一周中哪几天进行备份备份周期:Mon(周一)Tue(周二)Wed(周三)Thu(周四)Fri(周五)Sat(周六)Sun(周日)逗号分隔,取值如:Sun,Wed,Thu,Fri,Sta +> - BackupTime: 标识一天中何时进行备份,UTC时间(+8为北京时间)取值如:01:05:00 +> - ExpireDay: 备份文件过期时间,取值如:3 + +# 日志管理 + +## 日志列表 +使用以下代码可以获取一个实例下的运行日志或者慢日志列表。 +```go +// import "time" + +// 一天前 +date := time.Now(). + AddDate(0, 0, -1). + Format("2006-01-02 03:04:05") +fmt.Println(date) +args := &scs.ListLogArgs{ + // 运行日志 runlog 慢日志 slowlog + FileType: "runlog", + // 开始时间格式 "yyyy-MM-dd hh:mm:ss" + StartTime: date, + // 结束时间,可选,默认返回开始时间+24小时内的日志 + // EndTime: date, +} +listLogResult, err := client.ListLogByInstanceId(instanceId, args) +if err != nil { + fmt.Printf("list logs of instance error: %+v\n", err) + return +} +fmt.Println("list logs of instance success.") +for _, shardLog := range listLogResult.LogList { + fmt.Println("shard id: ", shardLog.ShardID) + fmt.Println("logs size: ", shardLog.TotalNum) + for _, log := range shardLog.LogItem { + fmt.Println("log id: ", log.LogID) + fmt.Println("size: ", log.LogSizeInBytes) + fmt.Println("start time: ", log.LogStartTime) + fmt.Println("end time: ", log.LogEndTime) + fmt.Println("download url: ", log.DownloadURL) + fmt.Println("download url expires: ", log.DownloadExpires) + } +} +``` + +## 日志详情 +使用以下代码可以查询日志的详细信息,包括该日志文件有效的下载链接。 +```go +args := &GetLogArgs{ + // 下载链接有效时间,单位为秒,可选,默认为1800秒 + ValidSeconds: 60, +} +logId := "scs-bj-mktaypucksot_8742_slowlog_202104160330" +log, err := client.GetLogById(instanceId, logId, args) +if err != nil { + fmt.Printf("get log detail of instance error: %+v\n", err) + return +} +fmt.Println("get log detail success.") +fmt.Println("id: ", log.LogID) +// 日志文件下载链接 +fmt.Println("download url: ", log.DownloadURL) +// 下载链接截止该时间有效 +fmt.Println("download url expires: ", log.DownloadExpires) +``` + +# 维护窗口 +## 查询实例的维护时间窗口 +使用以下代码可以查询实例的维护时间窗口。 +```go +resp, err := client.GetMaintainTime(instanceId) +if err != nil { + fmt.Printf("get maintainTime of instance error: %+v\n", err) + return +} +fmt.Println("get maintainTime success.") +fmt.Println("start time: ", resp.MaintainTime.StartTime) +fmt.Println("dutation: ", resp.MaintainTime.Duration) +fmt.Println("period: ", resp.MaintainTime.Period) +``` + +> 注意: +> +> - startTime 为北京时间24小时制,例如14:00。 + +## 修改实例的维护时间窗口 +使用以下代码可以修改实例的维护时间窗口。 +```go +newMaintainTime := &scs.MaintainTime{ + StartTime: "16:00", + Duration: 1, + Period: []int{1, 2, 3}, +} +err := client.ModifyMaintainTime(instanceId, newMaintainTime) +if err != nil { + fmt.Printf("modify maintainTime of instance error: %+v\n", err) + return +} +fmt.Println("modify maintainTime success.") +``` + +# 热活实例组 + +## 前置检查 +热活实例组前置检查,检查数据配置及网络联通性,不通过检查不能创建。 +```go +args := &scs.GroupPreCheckArgs{ + Leader: GroupLeader{ + LeaderRegion: "bj", + LeaderId: SCS_TEST_ID, + }, + Followers: []GroupFollower{ + { + FollowerId: "scs-bdbl-dzkqigawuhzy", + FollowerRegion: "bd", + }, + }, +} +result, err := client.GroupPreCheck(args) +if err != nil { + fmt.Printf("group pre check error: %+v\n", err) + return +} +fmt.Println("group pre check success.") +data, _ := json.Marshal(result) +fmt.Println(string(data)) +``` +## 创建热活实例组 +创建热活实例组 +```go +args := &scs.CreateGroupArgs{ + Leader: CreateGroupLeader{ + GroupName: "test_create", + LeaderRegion: "bj", + LeaderId: SCS_TEST_ID, + }, +} +result, err := client.CreateGroup(args) +if err != nil { + fmt.Printf("create group error: %+v\n", err) + return +} +fmt.Println("create group success.") +data, _ := json.Marshal(result) +fmt.Println(string(data)) +``` +## 获取热活实例组列表 +获取热活实例组列表 +```go +args := &scs.GetGroupListArgs{ + PageNo: 1, + PageSize: 10 +} +result, err := client.GetGroupList(args) +if err != nil { + fmt.Printf("get group list error: %+v\n", err) + return +} +fmt.Println("get group list success.") +data, _ := json.Marshal(result) +fmt.Println(string(data)) +``` +## 获取热活实例组详情 +获取热活实例组详情 +```go +result, err := client.GetGroupDetail(groupId) +if err != nil { + fmt.Printf("get group detail error: %+v\n", err) + return +} +fmt.Println("get group detail success.") +data, _ := json.Marshal(result) +fmt.Println(string(data)) +``` + +## 释放热活实例组 +释放热活实例组 +```go +err := client.DeleteGroup(groupId) +if err != nil { + fmt.Printf("delete group error: %+v\n", err) + return +} +fmt.Println("delete group success.") +``` + +## 热活实例组添加从集群 +```go +args := &scs.FollowerInfo{ + FollowerId: "scs-bdbl-dzkqigawuhzy", + FollowerRegion: "bd", + SyncMaster: "sync", +} +err := client.GroupAddFollower(groupId, args) +if err != nil { + fmt.Printf("group add follower error: %+v\n", err) + return +} +fmt.Println("group add follower success.") +``` +## 热活实例组移除从集群 +```go + +err := client.GroupRemoveFollower(groupId, instanceId) +if err != nil { + fmt.Printf("group remove follower error: %+v\n", err) + return +} +fmt.Println("group remove follower success.") +``` +## 修改热活实例组名称 +```go +args := &scs.roupNameArgs{ + GroupName: "test_group", +} +err := client.UpdateGroupName(groupId, args) +if err != nil { + fmt.Printf("update group name error: %+v\n", err) + return +} +fmt.Println("update group name success.") +``` +## 变更主角色 +```go +err := client.SetAsLeader(groupId, instanceId) +if err != nil { + fmt.Printf("set as leader error: %+v\n", err) + return +} +fmt.Println("set as leader success.") +``` +## 实例组禁写修改 +```go +args := &scs.ForbidWriteArgs{ + ForbidWriteFlag: true, +} +err := client.GroupForbidWrite(groupId, args) +if err != nil { + fmt.Printf("update forbid write error: %+v\n", err) + return +} +fmt.Println("update forbid write success.") +``` +## 设置流控规则 +```go +args := &scs.GroupSetQpsArgs{ + ClusterShowId: "scs-bj-bftgjzjxbmex", + QpsWrite: 10, + QpsRead: 20, +} +err := client.GroupSetQps(groupId, args) +if err != nil { + fmt.Printf("group set qps error: %+v\n", err) + return +} +fmt.Println("group set qps success.") +``` +## 获取从角色同步状态 +```go +result, err := client.GroupSyncStatus(groupId) +if err != nil { + fmt.Printf("group sync status error: %+v\n", err) + return +} +fmt.Println("group sync status success.") +data, _ := json.Marshal(result) +fmt.Println(string(data)) +``` +## 获取IP白名单列表 +```go +result, err := client.GroupWhiteList(groupId) +if err != nil { + fmt.Printf("group white list error: %+v\n", err) + return +} +fmt.Println("group white list success.") +data, _ := json.Marshal(result) +fmt.Println(string(data)) +``` +## 添加IP白名单 +```go +args := &scs.GroupWhiteList{ + WhiteLists: []string{"127.0.0.1"}, +} +err := client.GroupWhiteListAdd(groupId, args) +if err != nil { + fmt.Printf("group white add error: %+v\n", err) + return +} +fmt.Println("group white add success.") +``` +## 删除IP白名单 +```go +args := &scs.GroupWhiteList{ + WhiteLists: []string{"127.0.0.1"}, +} +err := client.GroupWhiteListDelete(groupId, args) +if err != nil { + fmt.Printf("group white delete error: %+v\n", err) + return +} +fmt.Println("group white delete success.") +``` + +## 设置从角色脏读 +```go +args := &scs.taleReadableArgs{ + FollowerId: SCS_TEST_ID, + StaleReadable: true, +} +err := client.GroupStaleReadable(groupId, args) +if err != nil { + fmt.Printf("groupstale readable error: %+v\n", err) + return +} +fmt.Println("groupstale readable success.") +``` + +# 参数模板管理 +## 创建参数模板 +```go + +args := &scs.CreateTemplateArgs{ + EngineVersion: "5.0", + TemplateType: 1, + ClusterType: "master_slave", + Engine: "redis", + Name: "test_template", + Comment: "test template", + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, +} +result, err := client.CreateParamsTemplate(args) +if err != nil { + fmt.Printf("create params template error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Println("create params template success.") +``` + +## 获取参数模版列表 +```go + +args := &Marker{ + Marder: "-1", + MaxKeys: 1000 +} +result, err := client.GetParamsTemplateList(args) +if err != nil { + fmt.Printf("get params template error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Println("get params template success.") +``` +## 获取参数模版详情 +```go +result, err := client.GetParamsTemplateDetail("scs-tmpl-vxslemqppzuz") +if err != nil { + fmt.Printf("get params template detail error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Println("get params template detail success.") +``` +## 删除参数模板 +```go +err := client.DeleteParamsTemplate("scs-tmpl-vxslemqppzuz") +if err != nil { + fmt.Printf("delete params template error: %+v\n", err) + return +} +fmt.Println("delete params template success.") +``` + + +## 修改参数模板名称 +```go +args := &scs.RenameTemplateArgs{ + Name: "scs-test-template", +} +err := client.RenameParamsTemplate("scs-tmpl-kctbndsfdhya", args) +if err != nil { + fmt.Printf("rename params template error: %+v\n", err) + return +} +fmt.Println("rename params template success.") +``` + +## 应用参数模板 +```go +args := &ApplyTemplateArgs{ + RebootType: 0, + Extra: "0", + CacheClusterShowIdItem: []CacheClusterShowId{ + { + CacheClusterShowId: SCS_TEST_ID, + Region: "bj", + }, + }, + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, +} +err := client.ApplyParamsTemplate("scs-tmpl-kctbndsfdhya", args) +if err != nil { + fmt.Printf("apply params template error: %+v\n", err) + return +} +fmt.Println("apply params template success.") +``` +## 参数模版添加参数 +```go +args := &scs.AddParamsArgs{ + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, +} +err := client.TemplateAddParams("scs-tmpl-kctbndsfdhya", args) +if err != nil { + fmt.Printf("add params template error: %+v\n", err) + return +} +fmt.Println("add params template success.") +``` +## 参数模版修改参数 +```go +args := &scs.ModifyParamsArgs{ + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, +} +err := client.TemplateModifyParams("scs-tmpl-kctbndsfdhya", args) +if err != nil { + fmt.Printf("modify params template error: %+v\n", err) + return +} +fmt.Println("modify params template success.") +``` +## 参数模版删除参数 +```go +args := &scs.DeleteParamsArgs{ + Parameters: []string{"appendonly"}, +} +err := client.TemplateDeleteParams("scs-tmpl-kctbndsfdhya", args) +if err != nil { + fmt.Printf("template delete params error: %+v\n", err) + return +} +fmt.Println("template delete params success.") +``` + +## 获取系统参数模板 +```go +args := &scs.GetSystemTemplateArgs{ + Engine: "redis", + EngineVersion: "5.0", + ClusterType: "master_slave", +} +result, err := client.GetSystemTemplate(args) +if err != nil { + fmt.Printf("get system template error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Println("get system template success.") +``` +## 获取应用参数模版记录 +```go +args := &scs.Marker{ + Marker: "-1", + MaxKeys: 100, +} +result, err := client.GetApplyRecords("scs-tmpl-kctbndsfdhya", args) +if err != nil { + fmt.Printf("get apply record error: %+v\n", err) + return +} +data, _ := json.Marshal(result) +fmt.Println(string(data)) +fmt.Println("get apply record success.") +``` +# 错误处理 + +GO语言以error类型标识错误,SCS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | SCS服务返回的错误 + +用户使用SDK调用SCS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// scsClient 为已创建的SCS Client对象 +instanceDetail, err := scsClient.GetInstanceDetail(instanceId) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("get instance detail success: ", instanceDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向SCS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError;当上传文件时发生IO异常时,也会抛出BceClientError。 + +## 服务端异常 + +当SCS服务端出现异常时,SCS服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[SCS错误返回](https://cloud.baidu.com/doc/SCS/s/Yjwvxtsti) + diff --git a/bce-sdk-go/doc/SMS.md b/bce-sdk-go/doc/SMS.md new file mode 100644 index 0000000..096993b --- /dev/null +++ b/bce-sdk-go/doc/SMS.md @@ -0,0 +1,508 @@ +# SMS简单消息服务 + +# 概述 +本文档主要介绍普通型SMS GO SDK的使用。在使用本文档前,您需要先了解普通型SMS的一些基本知识。若您还不了解普通型SMS,可以参考[产品描述](https://cloud.baidu.com/doc/SMS/s/0jwvxrjyt)和[入门指南](https://cloud.baidu.com/doc/SMS/s/sk4m6mxke)。 + +# 初始化 +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[SMS访问域名](https://cloud.baidu.com/doc/SMS/s/pjwvxrw6w)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +## 获取密钥 + +要使用百度云SMS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问SMS做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建SMS Client + +SMS Client是SMS服务的客户端,为开发者与SMS服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建SMS Client + +通过AK/SK方式访问SMS,用户可以参考如下代码新建一个SMS Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/sms" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个SmsClient + smsClient, err := sms.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [管理ACCESSKEY](https://cloud.baidu.com/doc/SMS/GettingStarted.html#.E7.AE.A1.E7.90.86ACCESSKEY) 》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为SMS的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://smsv3.bj.baidubce.com`。 + +### 使用STS创建SMS Client + +**申请STS token** + +SMS可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问SMS,用户需要先通过STS的client申请一个认证字符串,申请方式可参见[百度云STS使用介绍](https://cloud.baidu.com/doc/IAM/s/gjwvyc7n7) 。 + +**用STS token新建SMS Client** + +申请好STS后,可将STS Token配置到SMS Client中,从而实现通过STS Token创建SMS Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建SMS Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/sms" //导入SMS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建SMS服务的Client对象,Endpoint使用默认值 + smsClient, err := sms.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "") + if err != nil { + fmt.Println("create sms client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + smsClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置SMS Client时,无论对应SMS服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com 。上述代码中创建STS对象时使用此默认值。 + +## 配置HTTPS协议访问SMS + +SMS支持HTTPS传输协议,您可以通过在创建SMS Client对象时指定的Endpoint中指明HTTPS的方式,在SMS GO SDK中使用HTTPS访问SMS服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/sms" + +ENDPOINT := "https://smsv3.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +smsClient, _ := sms.NewClient(AK, SK, ENDPOINT) +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/sms" + +AK, SK := , +ENDPOINT := "smsv3.bj.baidubce.com" +client, _ := sms.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/sms" + +AK, SK := , +ENDPOINT := "smsv3.bj.baidubce.com" +client, _ := sms.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问SMS时,创建的SMS Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建SMS Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +# 主要接口 +## 发送消息 + +通过以下代码可以发送SMS消息 +```go + contentMap := make(map[string]interface{}) + contentMap["code"] = "123" + contentMap["minute"] = "1" + sendSmsArgs := &api.SendSmsArgs{ + Mobile: "13800138000", + Template: "your template id", + SignatureId: "your signature id", + ContentVar: contentMap, + } + result, err := client.SendSms(sendSmsArgs) + if err != nil { + fmt.Printf("send sms error, %s", err) + return + } + fmt.Printf("send sms success. %s", result) +``` +> **提示:** +> - 详细的参数配置及限制条件,可以参考SMS API 文档[短信下发](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb#%E7%9F%AD%E4%BF%A1%E4%B8%8B%E5%8F%91) + +## 签名 +### 申请签名 +通过以下代码,可以申请一个SMS签名 +```go + // Open file on disk. + f, _ := os.Open("/dir1/dir2/your_sign_pic.png") + // Read entire JPG into byte slice. + reader := bufio.NewReader(f) + content, _ := ioutil.ReadAll(reader) + // Encode as base64. + encoded := base64.StdEncoding.EncodeToString(content) + result, err := client.CreateSignature(&api.CreateSignatureArgs{ + Content: "Baidu", + ContentType: "Enterprise", + Description: "test", + CountryType: "DOMESTIC", + SignatureFileBase64: encoded, + SignatureFileFormat: "png", + }) + if err != nil { + fmt.Printf("create signature error, %s", err) + return + } + fmt.Printf("create signature success. %s", result) +``` +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[申请签名](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 获取签名详情 +通过以下代码,可以获取一个SMS签名详情 +```go + result, err := client.GetSignature(&api.GetSignatureArgs{ + SignatureId: "your signature id", + }) + if err != nil { + fmt.Printf("get signature error, %s", err) + return + } + fmt.Printf("get signature success. %s", result) +``` +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[获取签名详情](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 变更签名申请 +通过以下代码,可以变更一个SMS签名申请 +```go + // Open file on disk. + f, _ := os.Open("/dir1/dir2/your_sign_pic.png") + // Read entire JPG into byte slice. + reader := bufio.NewReader(f) + content, _ := ioutil.ReadAll(reader) + // Encode as base64. + encoded := base64.StdEncoding.EncodeToString(content) + err := client.ModifySignature(&api.ModifySignatureArgs{ + SignatureId: "your signature id", + Content: "Baidu", + ContentType: "MobileApp", + Description: "this is a test", + CountryType: "INTERNATIONAL", + SignatureFileBase64: encoded, + SignatureFileFormat: "png", + }) + if err != nil { + fmt.Printf("modify signature error, %s", err) + return + } + fmt.Printf("modify signature success.") +``` +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[变更签名申请](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 删除签名 +通过以下代码,可以删除一个SMS签名 +```go + err := client.DeleteSignature( + &api.DeleteSignatureArgs{SignatureId: "your signature id"}) + if err != nil { + fmt.Printf("delete signature error, %s", err) + return + } + fmt.Printf("delete signature success.") +``` + +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[删除签名](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +## 模板 +### 申请模板 +通过以下代码,可以申请一个sms模板 +```go + result, err := client.CreateTemplate(&api.CreateTemplateArgs{ + Name: "my template", + Content: "${content}", + SmsType: "CommonNotice", + CountryType: "DOMESTIC", + Description: "this is a test", + }) + if err != nil { + fmt.Printf("create template error, %s", err) + return + } + fmt.Printf("create template success. %s", result) +``` +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[申请模板](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 获取模板详情 +通过以下代码,可以获取一个sms模板详情 +```go + result, err := client.GetTemplate(&api.GetTemplateArgs{TemplateId: your template id"}) + if err != nil { + fmt.Printf("get template error, %s", err) + return + } + fmt.Printf("get template success. %s", result) +``` + +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[获取模板详情](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 变更模板 +通过以下代码,可以变更一个sms模板申请 +```go + err := client.ModifyTemplate(&api.ModifyTemplateArgs{ + TemplateId: "your template id", + Name: "my template", + Content: "${code}", + SmsType: "CommonVcode", + CountryType: "GLOBAL", + Description: "this is a test", + }) + if err != nil { + fmt.Printf("modify template error, %s", err) + return + } + fmt.Printf("modify template success.") +``` + +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[变更模板](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 删除模板 +通过以下代码,可以删除一个模板 +```go + err := client.DeleteTemplate(&api.DeleteTemplateArgs{TemplateId: "your template id"}) + if err != nil { + fmt.Printf("delete template error, %s", err) + return + } + fmt.Printf("delete template success.") +``` + +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[删除模板](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +## 配额频控 +### 查看配额和频控 +通过以下代码,可以查看配额和频控 +```go + result, err := client.QueryQuotaAndRateLimit() + if err != nil { + fmt.Printf("query quota or rate limit error, %s", err) + return + } + fmt.Printf("query quota or rate limit success. %s", result) +``` +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[查看配额和频控](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +### 变更配额或频控 +通过以下代码,可以变更配额或频控 +```go + err := client.UpdateQuotaAndRateLimit(&api.UpdateQuotaRateArgs{ + QuotaPerDay: 200, + QuotaPerMonth: 200, + RateLimitPerDay: 60, + RateLimitPerHour: 20, + RateLimitPerMinute: 10, + }) + if err != nil { + fmt.Printf("update quota or rate limit template error, %s", err) + return + } + fmt.Printf("update quota or rate limit success") +``` +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[变更配额和频控](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + +## 手机号黑名单 +### 创建手机号黑名单 +通过以下代码,可以创建手机号黑名单 +```go + err := client.CreateMobileBlack(&api.CreateMobileBlackArgs{ + Type: "MerchantBlack", + SmsType: "CommonNotice", + SignatureIdStr: "sddd", + Phone: "12345678901", + }) + if err != nil { + fmt.Printf("CreateMobileBlack error, %s", err) + return + } + fmt.Printf("CreateMobileBlack success") +``` + +### 查询手机号黑名单 +通过以下代码,可以查询手机号黑名单 +```go + err := client.GetMobileBlack(&api.GetMobileBlackArgs{ + SmsType: "CommonNotice", + SignatureIdStr: "sddd", + Phone: "12345678901", + StartTime: "2023-07-18", + EndTime: "2023-07-19", + PageNo: "1", + PageSize: "10", + }) + if err != nil { + fmt.Printf("GetMobileBlack error, %s", err) + return + } + fmt.Printf("GetMobileBlack success") +``` + +### 删除手机号黑名单 +通过以下代码,可以删除手机号黑名单 +```go + err := client.DeleteMobileBlack(&api.DeleteMobileBlackArgs{ + Phones: "12345678901", + }) + if err != nil { + fmt.Printf("DeleteMobileBlack error, %s", err) + return + } + fmt.Printf("DeleteMobileBlack success") +``` + +> **提示:** +> - 详细参数配置及限制条件,可以参考SMS API 文档[手机号黑名单](https://cloud.baidu.com/doc/SMS/s/Yjwvxrwzb) + + + +# 错误处理 + +GO语言以error类型标识错误,SMS支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | SMS服务返回的错误 + +用户使用SDK调用SMS相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +```go +// smsClient 为已创建的SMS Client对象 +smsDetail, err := smsClient.SendSms(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} else { + fmt.Println("send sms success: ", smsDetail) +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向SMS发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当SMS服务端出现异常时,SMS服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[短信发送接口响应码](https://cloud.baidu.com/doc/SMS/s/zjwvxry6e) + +# 版本变更记录 + +## v0.9.19 [2020-08-08] + +首次发布: +- 支持短信发送接口 +- 支持签名、模板管理接口 +- 支持配额、频控查看和变更 + +## v0.9.32 [2023-07-20] +- 配额频控查询增加申请信息字段 +- 增加手机号黑名单增、删、查接口 \ No newline at end of file diff --git a/bce-sdk-go/doc/SNIC.md b/bce-sdk-go/doc/SNIC.md new file mode 100644 index 0000000..356a371 --- /dev/null +++ b/bce-sdk-go/doc/SNIC.md @@ -0,0 +1,451 @@ +# SNIC服务 + +# 概述 + +本文档主要介绍SNIC GO SDK的使用。在使用本文档前,您需要先了解SNIC的一些基本知识,并已开通了SNIC服务。若您还不了解SNIC,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/sjwvytvh0 )和[操作指南](https://cloud.baidu.com/doc/VPC/s/6jwvyu1dn) 。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[ENDPOINT服务域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw )的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/ )。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云SNIC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问SNIC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建SNIC Client + +SNIC Client是SNIC服务的客户端,为开发者与ENDPOINT服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建ENDPOINT Client + +通过AK/SK方式访问ENDPOINT,用户可以参考如下代码新建一个ENDPOINT Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个SNICClient + snicClient, err := endpoint.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/ )》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建SNIC Client + +**申请STS token** + +SNIC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问SNIC,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建SNIC Client** + +申请好STS后,可将STS Token配置到SNIC Client中,从而实现通过STS Token创建SNIC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建SNIC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/endpoint" //导入SNIC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建SNIC服务的Client对象,Endpoint使用默认值 + snicClient, err := endpoint.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create snic client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + snicClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置SNIC Client时,无论对应SNIC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问SNIC + +SNIC支持HTTPS传输协议,您可以通过在创建SNIC Client对象时指定的Endpoint中指明HTTPS的方式,在SNIC GO SDK中使用HTTPS访问SNIC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +snicClient, _ := endpoint.NewClient(AK, SK, ENDPOINT) +``` + +## 配置SNIC Client + +如果用户需要配置SNIC Client的一些细节的参数,可以在创建SNIC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问SNIC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +//创建SNIC Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := endpoint.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := endpoint.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := endpoint.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问SNIC时,创建的SNIC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + +1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建SNIC Client”小节。 +2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 +3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + +## 获取公共服务 + +使用以下代码获取公共服务 +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +result, err := client.GetServices() + if err != nil { + fmt.Printf("list public services error: %+v\n", err) + return + } +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 创建SNIC + +使用以下代码可以申请一个SNIC。 +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +args := &endpoint.CreateEndpointArgs{ + VpcId: "vpcId", + Name: "TestSDK-SNIC", + SubnetId: "subnetId", + Service: "service", + Description: "desc", + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + ClientToken: getClientToken(), +} +result, err := client.CreateEndpoint(args) +if err != nil { + fmt.Printf("create snic error: %+v\n", err) + return +} + +fmt.Println("create snic success, snic: ", result.Id) +``` + + +## 查询SNIC 列表 + +使用以下代码可以查询SNIC列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +args := &endpoint.ListEndpointArgs{ + VpcId: "vpcId", + SubnetId: "subnetId", + } +res, err := client.ListEndpoints(args) + if err != nil { + fmt.Printf("list snic error: %+v\n", err) + return + } + // 返回标记查询的起始位置 + fmt.Println("snic list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("snic list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("snic list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("snic list maxKeys: ", result.MaxKeys) + // 获取snic的列表信息 + for _, e := range res.Endpoints { + fmt.Println("snic id: ", e.EndpointId) + fmt.Println("snic name: ", e.Name) + fmt.Println("snic ipAddress: ", e.IpAddress) + fmt.Println("snic status: ", e.Status) + fmt.Println("snic service: ", e.Service) + fmt.Println("snic subnetId: ", e.SubnetId) + fmt.Println("snic description: ", e.Description) + fmt.Println("snic createTime: ", e.CreateTime) + fmt.Println("snic vpcId: ", e.VpcId) + fmt.Println("snic productType: ", e.ProductType) + } +``` + +## 查询SNIC详情 + +使用以下代码可以实现查询SNIC的详情信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" +result,err:=endpoint.GetEndpointDetail("endpointId") + + if err != nil { + fmt.Printf("get snic detail error: %+v\n", err) + return + } + fmt.Println("snic id: ", e.EndpointId) + fmt.Println("snic name: ", e.Name) + fmt.Println("snic ipAddress: ", e.IpAddress) + fmt.Println("snic status: ", e.Status) + fmt.Println("snic service: ", e.Service) + fmt.Println("snic subnetId: ", e.SubnetId) + fmt.Println("snic description: ", e.Description) + fmt.Println("snic createTime: ", e.CreateTime) + fmt.Println("snic vpcId: ", e.VpcId) + fmt.Println("snic productType: ", e.ProductType) +} +``` + +## 更新SNIC + +使用以下代码可以实现SNIC的更新。 +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" +args := &endpoint.UpdateEndpointArgs{ + ClientToken: getClientToken(), + Name: "snicTest", + Description: "Description", +} + err := client.UpdateEndpoint("endpointId", args) +if err != nil { + fmt.Printf("update snic error: %+v\n", err) + return +} +fmt.Printf("update snic success\n") +``` + + +## 释放SNIC + +使用以下代码可以释放指定的SNIC。 +```go +// import "github.com/baidubce/bce-sdk-go/services/endpoint" + +err := client.DeleteEndpoint("endpointId", clientToken) +if err != nil { + fmt.Printf("delete snic error: %+v\n", err) + return +} + +fmt.Printf("delete snic success\n") +``` + +> 注意: +> - 释放指定SNIC,被释放的SNIC无法找回 + +# 错误处理 + +GO语言以error类型标识错误,SNIC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | SNIC服务返回的错误 + +用户使用SDK调用SNIC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// snicClient 为已创建的SNIC Client对象 +args := &endpoint.ListEndpointArgs{} +result, err := client.ListEndpoints(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向SNIC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当SNIC服务端出现异常时,SNIC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[SNIC错误码](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +SNIC GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +SNIC GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: +1. 日志默认输出级别为`DEBUG` +2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 +3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB +4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the SNIC go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the SNIC go sdk") +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/STS.md b/bce-sdk-go/doc/STS.md new file mode 100644 index 0000000..9c858f7 --- /dev/null +++ b/bce-sdk-go/doc/STS.md @@ -0,0 +1,98 @@ +# STS服务 + +# 概述 + +本文档主要介绍STS服务的使用。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 +若您还不了解STS,可以参考[产品描述](https://cloud.baidu.com/doc/IAM/s/xjwvybxhv)和[操作指南](https://cloud.baidu.com/doc/IAM/s/njwvyc2zd)。 + +# 使用方法 + +## 确认Endpoint + +目前使用STS服务时,STS的Endpoint都统一使用`http://sts.bj.baidubce.com`,为默认值。 + +## 获取密钥 + +要使用百度云STS,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问服务做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 创建Client对象并获取临时token + +STS Client是STS服务的客户端,为开发者与STS服务进行交互提供了获取临时token的方法。示例代码如下: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := "", "" + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + obj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", obj.AccessKeyId) + fmt.Println(" secretAccessKey:", obj.SecretAccessKey) + fmt.Println(" sessionToken:", obj.SessionToken) + fmt.Println(" createTime:", obj.CreateTime) + fmt.Println(" expiration:", obj.Expiration) + fmt.Println(" userId:", obj.UserId) +} +``` + +## 获取关联指定角色的临时身份凭证 + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 + "github.com/baidubce/bce-sdk-go/services/sts/api" +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := "", "" + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + AccountId, RoleName := "", "" + args := &api.AssumeRoleArgs{ + AccountId: AccountId, + RoleName: RoleName, + } + obj, err := client.AssumeRole(args) + if err != nil { + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", obj.AccessKeyId) + fmt.Println(" secretAccessKey:", obj.SecretAccessKey) + fmt.Println(" sessionToken:", obj.SessionToken) + fmt.Println(" createTime:", obj.CreateTime) + fmt.Println(" expiration:", obj.Expiration) + fmt.Println(" userId:", obj.UserId) + fmt.Println(" roleId:", obj.RoleId) +} +``` \ No newline at end of file diff --git a/bce-sdk-go/doc/VPC.md b/bce-sdk-go/doc/VPC.md new file mode 100644 index 0000000..a77d81c --- /dev/null +++ b/bce-sdk-go/doc/VPC.md @@ -0,0 +1,1811 @@ +# VPC服务 + +# 概述 + +本文档主要介绍VPC GO SDK的使用。在使用本文档前,您需要先了解VPC的一些基本知识,并已开通了VPC服务。若您还不了解VPC,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/Vjwvytu2v)和[操作指南](https://cloud.baidu.com/doc/VPC/s/qjwvyu0at)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[VPC访问域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云VPC,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问VPC做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建VPC Client + +VPC Client是VPC服务的客户端,为开发者与VPC服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建VPC Client + +通过AK/SK方式访问VPC,用户可以参考如下代码新建一个VPC Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个VpcClient + vpcClient, err := vpc.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`http://bcc.bj.baidubce.com`。 + +### 使用STS创建VPC Client + +**申请STS token** + +VPC可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问VPC,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建VPC Client** + +申请好STS后,可将STS Token配置到VPC Client中,从而实现通过STS Token创建VPC Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建VPC Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/vpc" //导入VPC服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建VPC服务的Client对象,Endpoint使用默认值 + vpcClient, err := vpc.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create vpc client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + vpcClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置VPC Client时,无论对应VPC服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问VPC + +VPC支持HTTPS传输协议,您可以通过在创建VPC Client对象时指定的Endpoint中指明HTTPS的方式,在VPC GO SDK中使用HTTPS访问VPC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpc" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +vpcClient, _ := vpc.NewClient(AK, SK, ENDPOINT) +``` + +## 配置VPC Client + +如果用户需要配置VPC Client的一些细节的参数,可以在创建VPC Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问VPC服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpc" + +//创建VPC Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := vpc.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpc" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := vpc.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpc" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := vpc.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问VPC时,创建的VPC Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建VPC Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + +# VPC管理 + +私有网络(Virtual private Cloud,VPC) 是一个用户能够自定义的虚拟网络,能够帮助用户构建属于自己的网络环境。通过指定IP地址范围和子网等配置,即可快速创建一个VPC,不同的VPC之间完全隔离,用户可以在VPC内创建和管理BCC实例。 + +## 创建VPC + +通过以下代码可以创建VPC实例: +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.CreateVPCArgs{ + // 设置创建vpc使用的名称 + Name: "test-vpc", + // 设置创建vpc使用的描述信息 + Description: "test-vpc-description", + // 设置创建vpc使用的cidr + Cidr: "102.168.0.0/24", + // 设置创建vpc使用的标签键值对列表 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +if result, err := client.CreateVPC(args); err != nil { + fmt.Println("create vpc failed: ", err) + return +} + +fmt.Println("create vpc success, vpc id: ", result.VPCID) +``` + +> 注意: 对请求参数的内容解释如下 +> - Name: 表示VPC名称,不能取值"default",长度不超过65个字符,可由数字,字符,下划线组成; +> - ClientToken: 表示幂等性Token,是一个长度不超过64位的ASCII字符串,详见[ClientToken幂等性](https://cloud.baidu.com/doc/VPC/s/gjwvyu77i/#%E5%B9%82%E7%AD%89%E6%80%A7) +> - Description: VPC描述,不超过200字符 +> - Cidr: VPC的cidr +> - Tags: 待创建的标签键值对列表 + +## 查询VPC列表 + +使用以下代码查询VPC列表信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.ListVPCArgs{ + // 设置每页包含的最大数量,最大数量通常不超过1000,缺省值为1000 + MaxKeys: 2, + // 设置批量获取列表的查询的起始位置,是一个由系统生成的字符串 + Marker: marker, + // 设置是否为默认VPC,可选值:true、false;当不填写此参数时返回所有VPC + IsDefault: "false", +} +result, err := client.ListVPC(listArgs) +if err != nil { + fmt.Println("list vpc error: ", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("vpc list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("vpc list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("vpc list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("vpc list maxKeys: ", result.MaxKeys) +// 获取vpc的具体信息 +for _, v := range result.VPCs { + fmt.Println("vpc id: ", v.VPCID) + fmt.Println("vpc name: ", v.Name) + fmt.Println("vpc cidr: ", v.Cidr) + fmt.Println("vpc description: ", v.Description) + fmt.Println("vpc isDefault: ", v.IsDefault) + fmt.Println("vpc secondaryCidr: ", v.SecondaryCidr) + fmt.Println("vpc tags: ", v.Tags) +} +``` + +## 查询指定VPC + +根据特定的VPC ID可以查看相关VPC的详情信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +result, err := client.GetVPCDetail(vpcId) +if err != nil { + fmt.Println("get vpc detail error: ", err) + return +} + +// 查询得到vpc的id +fmt.Println("VPC id: ", result.VPC.VPCId) +// 查询得到vpc的名称 +fmt.Println("VPC name: ", result.VPC.Name) +// 查询得到vpc的网段及子网掩码 +fmt.Println("VPC cidr: ", result.VPC.Cidr) +// 查询得到vpc的描述 +fmt.Println("VPC description: ", result.VPC.Description) +// 查询得到是否为默认vpc +fmt.Println("VPC isDefault: ", result.VPC.IsDefault) +// 查询得到vpc中包含的子网 +fmt.Println("VPC subnets: ", result.VPC.Subnets) +// 查询得到vpc的辅助网段cidr列表 +fmt.Println("VPC secondaryCidr: ", result.VPC.SecondaryCidr) +``` + +查询得到的VPC详情信息包括名称、网段、创建时间、描述等信息。 + +## 删除VPC + +使用以下代码可以删除特定的VPC。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.DeleteVPC(vpcId, clientToken); err != nil { + fmt.Println("delete vpc error: ", err) + return +} + +fmt.Printf("delete vpc %s success.", vpcId) +``` + +> 注意: 参数中的clientToken表示幂等性Token,是一个长度不超过64位的ASCII字符串,详见[ClientToken幂等性](https://cloud.baidu.com/doc/VPC/s/gjwvyu77i/#%E5%B9%82%E7%AD%89%E6%80%A7) + +## 更新VPC + +使用以下代码可以更新指定VPC的名称和描述信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UpdateVPCArgs{ + // 设置vpc的新名称 + Name: "TestVPCUpdate", + // 设置vpc的新备注 + Description: "Test VPC description update", + // 设置幂等性Token + ClientToken: clientToken, +} +if err := client.UpdateVPC(vpcId, args); err != nil { + fmt.Println("update vpc error: ", err) + return +} + +fmt.Printf("update vpc %s success.", vpcId) +``` + +> 注意: 更新VPC时,对name和description字段的规范要求参考`创建VPC`一节。 + + +## 查询VPC内内网Ip的信息 +使用以下代码可以更新指定VPC的名称和描述信息。 +>PrivateIpRange的格式为"192.168.0.1-192.168.0-5" + 参数中PrivateIpAddresses或PrivateIpRange的ip数量大小不能超过100. + 若PrivateIpAddresses和PrivateIpRange同时存在,PrivateIpRange优先。 + +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &GetVpcPrivateIpArgs{ + VpcId: "vpc-2pa2x0bjt26i", + PrivateIpAddresses: []string{"192.168.0.1,192.168.0.2"}, + PrivateIpRange: "192.168.0.0-192.168.0.45", + } + +result, err := client.GetVPCDetail(vpcId) +if err != nil { + fmt.Println("get vpc privateIp address info error: ", err) + return +} + + +fmt.Println("privateIpAddresses size is : ", len(result.VpcPrivateIpAddresses)) + +``` +# 子网管理 + +子网是 VPC 内的用户可定义的IP地址范围,根据业务需求,通过CIDR(无类域间路由)可以指定不同的地址空间和IP段。未来用户可以将子网作为一个单位,用来定义Internet访问权限、路由规则和安全策略。 + +## 创建子网 + +通过以下代码可以在指定VPC中创建子网。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.CreateSubnetArgs{ + // 设置子网的名称 + Name: "TestSDK-Subnet", + // 设置子网的可用区名称 + ZoneName: "cn-bj-a", + // 设置子网的cidr + Cidr: "192.168.1.0/24", + // 设置子网所属vpc的id + VpcId: "vpc-4njbqurm0uag", + // 设置子网的类型,包括“BCC”、“BCC_NAT”、“BBC”三种 + SubnetType: vpc.SUBNET_TYPE_BCC, + // 设置子网的描述 + Description: "test subnet", + // 是否分配IPv6网段,true表示开启,默认false不开启 + EnableIpv6: true, + // 设置子网的标签键值对列表 + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, +} +result, err := client.CreateSubnet(args) +if err != nil { + fmt.Println("create subnet error: ", err) + return +} + +fmt.Println("create subnet success, subnet id: ", result.SubnetId) +``` + +> 注意: +> - 子网名称,不能取值"default",长度不超过65个字符,可由数字,字符,下划线组成 +> - 可用区名称, 其查询方式参考[查询可用区列表](https://cloud.baidu.com/doc/BCC/s/ijwvyo9im/) + +## 查询子网列表 + +使用以下代码可以查询符合条件的子网列表。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.ListSubnetArgs{ + // 设置批量获取列表的查询的起始位置,是一个由系统生成的字符串 + Marker: marker, + // 设置每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 + MaxKeys: maxKeys, + // 设置所属vpc的id + VpcId: vpcId, + // 设置所属可用区的名称 + ZoneName: zoneName, + // 设置子网类型 + SubnetType: vpc.SUBNET_TYPE_BCC, +} +result, err := client.ListSubnets(args) +if err != nil { + fmt.Println("list subnets error: ", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("subnet list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("subnet list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("subnet list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("subnet list maxKeys: ", result.MaxKeys) +// 获取subnet的具体信息 +for _, sub := range result.Subnets { + fmt.Println("subnet id: ", sub.SubnetId) + fmt.Println("subnet name: ", sub.Name) + fmt.Println("subnet zoneName: ", sub.ZoneName) + fmt.Println("subnet cidr: ", sub.Cidr) + fmt.Println("subnet vpcId: ", sub.VPCId) + fmt.Println("subnet subnetType: ", sub.SubnetType) + fmt.Println("subnet description: ", sub.Description) + fmt.Println("subnet availableIp: ", sub.AvailableIp) + fmt.Println("subnet tags: ", sub.Tags) +} +``` + +根据该API,可以根据vpcId、zoneName、subnetType等条件查询符合要求的子网列表。 + +## 查询指定子网 + +根据以下代码可以查询指定子网的详细信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +result, err := client.GetSubnetDetail(subnetId) +if err != nil { + fmt.Println("get subnet detail error: ", err) + return +} + +// 查询得到子网的id +fmt.Println("subnet id: ", result.Subnet.SubnetId) +// 查询得到子网的名称 +fmt.Println("subnet name: ", result.Subnet.Name) +// 查询得到子网所属可用区的名称 +fmt.Println("subnet zoneName: ", result.Subnet.ZoneName) +// 查询得到子网的cidr +fmt.Println("subnet cidr: ", result.Subnet.Cidr) +// 查询得到子网所属vpc的id +fmt.Println("subnet vpcId: ", result.Subnet.VPCId) +// 查询得到子网的类型 +fmt.Println("subnet subnetType: ", result.Subnet.SubnetType) +// 查询得到子网的描述 +fmt.Println("subnet description: ", result.Subnet.Description) +// 查询得到子网内可用ip数 +fmt.Println("subnet availableIp: ", result.Subnet.AvailableIp) +// 查询得到子网绑定的标签列表 +fmt.Println("subnet tags: ", result.Subnet.Tags) +``` + +通过该接口可以得到子网的名称、可用区、cidr、类型、描述、可用ip数、标签列表等信息。 + +> 注意: 子网类型包括"BCC”、"BCC_NAT”、”BBC”三种。 + +## 删除子网 + +通过以下代码可以删除指定子网。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.DeleteSubnet(subnetId, clientToken); err != nil { + fmt.Println("delete subnet error: ", err) + return +} + +fmt.Printf("delete subnet %s success.", subnetId) +``` + +> 注意: 参数中的clientToken表示幂等性Token,是一个长度不超过64位的ASCII字符串,详见[ClientToken幂等性](https://cloud.baidu.com/doc/VPC/s/gjwvyu77i/#%E5%B9%82%E7%AD%89%E6%80%A7) + +## 更新子网 + +使用以下代码可以更新子网信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UpdateSubnetArgs{ + // 设置更新操作使用的幂等性token + ClientToken: clientToken, + // 设置更新后的子网名称 + Name: "TestSDK-Subnet-update", + // 设置更新后的子网描述 + Description: "subnet update", + // 是否分配IPv6网段,true表示开启,默认false不开启 + EnableIpv6: true, +} +if err := client.UpdateSubnet(subnetId, args); err != nil { + fmt.Println("update subnet error: ", err) + return +} + +fmt.Printf("update subnet %s success.", subnetId) +``` + +使用该接口可以实现对子网名称和描述信息的更新操作。 + +## 创建预留网段 + +使用以下代码可以创建预留网段。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // Initialize ak, sk, and endpoint + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) // Initialize VPC client + + args := &vpc.CreateIpreserveArgs{ + SubnetId: "sbn-4fa15xxxxxxx", // ID of the subnet to create the reserved ip segment + IpCidr: "192.168.0.0/31", // Reserved CIDR + IpVersion: 4, // IP version (4 for IPv4, 6 for IPv6) + // Description: "test", // Description of the reserved CIDR, optional + // ClientToken: "", // Client token, optional + } + + result, err := VPC_CLIENT.CreateIpreserve(args) + + if err != nil { + fmt.Println("create reserved ip error: ", err) + return + } + + fmt.Println("create reserved ip success, reserved CIDR id: ", result.IpReserveId) + +``` +## 查询预留网段列表 + +使用以下代码可以查询符合条件的预留网段列表。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // Initialize ak, sk, and endpoint + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) // Initialize VPC client + + ipReserveId := "ipr-nc4xxxxx" // ID of the reserved CIDR to be deleted + clientToken := "" // optional yourclientToken + + err := VPC_CLIENT.DeleteIpreserve(ipReserveId, clientToken) + + if err != nil { + fmt.Println("DeleteIpreserve error: ", err) + return + } + + fmt.Printf("delete reserved CIDR %s success.", ipReserveId) + +``` +## 删除预留网段 + +使用以下代码可以删除指定预留网段。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + + // 设置AK、SK和Endpoint + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // Initialize ak, sk, and endpoint + + // 创建VPC客户端 + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + args := &vpc.ListIpeserveArgs{ + SubnetId: "sbn-4fxx51yxxxx", + Marker: "", // 查询的起始位置,为空则从第一条开始查询 + MaxKeys: 10, + } + + // 添加查询保留IP范围的代码 + result, err := VPC_CLIENT.ListIpreserve(args) + if err != nil { + fmt.Printf("List reserved IP ranges failed with %s\n", err) + } + + // 输出子网ID和保留IP范围信息 + for _, IpReserve := range result.IpReserves { + fmt.Printf("IP Range: %s, Description: %s\n", IpReserve.IpCidr, IpReserve.SubnetId) + fmt.Println("isTruncated %d", result.IsTruncated) + } + +``` + +# 路由表管理 + +路由表是指路由器上管理路由条目的列表。 + +## 查询所有路由表 + +使用以下代码可以完成对路由表的查询。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +// 方式1: 通过路由表id进行查询 +result, err := client.GetRouteTableDetail(routeTableId, "") +if err != nil { + fmt.Println("get route table error: ", err) + return +} + +// 方式2: 通过vpc id进行查询 +result, err := client.GetRouteTableDetail("", vpcId) +if err != nil { + fmt.Println("get route table error: ", err) + return +} + +// 查询得到路由表id +fmt.Println("result of route table id: ", result.RouteTableId) +// 查询得到vpc id +fmt.Println("result of vpc id: ", result.VpcId) +// 查询得到所有的路由规则列表 +for _, route := range result.RouteRules { + fmt.Println("route rule id: ", route.RouteRuleId) + fmt.Println("route rule routeTableId: ", route.RouteTableId) + fmt.Println("route rule sourceAddress: ", route.SourceAddress) + fmt.Println("route rule destinationAddress: ", route.DestinationAddress) + fmt.Println("route rule nexthopId: ", route.NexthopId) + fmt.Println("route rule nexthopType: ", route.NexthopType) + fmt.Println("route rule description: ", route.Description) +} +``` + +> 注意: +> - 请求参数routeTableId和vpcId不可以同时为空 +> - 使用该接口可以查询得到所有相关的路由规则列表 + +## 创建路由规则 + +使用以下代码可以创建路由规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.CreateRouteRuleArgs{ + // 设置路由表id,必选 + RouteTableId: RouteTableID, + // 设置源网段,必选 + SourceAddress: "192.168.1.0/24", + // 设置目标网段,必选 + DestinationAddress: "172.17.0.0/16", + // 设置下一跳类型,必选, 创建单线路由必填 + NexthopType: vpc.NEXTHOP_TYPE_NAT, + // 多线路由下一跳信息,创建多线路由时该字段必填,NextHop的nexthopType目前只支持专线网关类型:"dcGateway" + NextHopList: []NextHop, + // 设置下一跳id,必选 + NexthopId: NatID, + // 设置路由规则的描述信息,可选 + Description: "test route rule", +} +result, err := client.CreateRouteRule(args) +if err != nil { + fmt.Println("create route rule error: ", err) + return +} +fmt.Println("create route rule success, route rule id: ", result.RouteRuleId) +``` + +创建路由表规则,有以下几点需要注意: +- 源网段选择自定义时,自定义网段需在已有子网范围内,0.0.0.0/0除外; +- 目标网段不能与当前所在VPC cidr重叠(目标网段或本VPC cidr为0.0.0.0/0时例外); +- 新增路由条目的源网段和目标网段,不能与路由表中已有条目源网段和目标网段完全一致。 +- 针对下一跳的类型,目前支持如下几种: + - Bcc类型是 "custom"; + - VPN类型是 "vpn"; + - NAT类型是 "nat"; + - 专线网关类型是 "dcGateway"; + - 创建单线路由时该字段必填NexthopType + - NextHopList 多线路由下一跳信息,创建多线路由时该字段必填 + - NextHop.nexthopId 下一跳ID + - NextHop.nexthopType 路由类型。目前只支持专线网关类型:"dcGateway" + - NextHop.pathType 多线模式。负载均衡取值为ecmp;主备模式取值ha:active、ha:standby,分别表示主、备路由 + - 对等连接类型是 "peerConn",nexthopId需要传端口ID(qpif-vx034sff4tsm) + - IPv6网关类型是 "ipv6gateway" + - 弹性网卡类型是 "enic" + - 高可用虚拟IP是 "havip" + +## 删除路由规则 + +使用以下代码可以删除特定的路由规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.DeleteRouteRule(routeRuleId, clientToken); err != nil { + fmt.Println("delete route rule error: ", err) + return +} + +fmt.Printf("delete route rule %s success.", routeRuleId) +``` + +> 注意: 参数中的clientToken表示幂等性Token,是一个长度不超过64位的ASCII字符串,详见[ClientToken幂等性](https://cloud.baidu.com/doc/VPC/s/gjwvyu77i/#%E5%B9%82%E7%AD%89%E6%80%A7) + + +## 更新路由规则 + +使用以下代码可以更新路由规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + args := &vpc.UpdateRouteRuleArgs{ + RouteRuleId: "rr-1zcxxxxxxyyy", + // SourceAddress: "Your SourceAddress", // optional + // DestinationAddress: "Your DestinationAddress", // optional + // NexthopId: "your NewNexthopId", // optional + // Description: "Your New Description", // optional + } + + err := VPC_CLIENT.UpdateRouteRule(args) + if err != nil { + fmt.Println("Route rule updated fail") + } + + fmt.Println("Route rule %s updated successfully", args.RouteRuleId) +``` + +## 查询路由规则 + +使用以下代码可以查询路由规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + routeTableId := "rt-hf1ezardxxxx" + vpcId := "vpc-nx6bs5xxxxxx" + + // routeTableId and vpcId should not be empty at the same time + result, err := VPC_CLIENT.GetRouteTableDetail(routeTableId, vpcId) + if err != nil { + fmt.Println("get route table error: ", err) + } + + // print result + fmt.Println("result of route table id: ", result.RouteTableId) + fmt.Println("result of vpc id: ", result.VpcId) + + for _, route := range result.RouteRules { + fmt.Println("route rule id: ", route.RouteRuleId) + fmt.Println("route rule routeTableId: ", route.RouteTableId) + fmt.Println("route rule sourceAddress: ", route.SourceAddress) + fmt.Println("route rule destinationAddress: ", route.DestinationAddress) + fmt.Println("route rule nexthopId: ", route.NexthopId) + fmt.Println("route rule nexthopType: ", route.NexthopType) + fmt.Println("route rule description: ", route.Description) + } +``` + +# ACL管理 + +访问控制列表(Access Control List,ACL)作为应用在子网上的防火墙组件帮助用户实现子网级别的安全访问控制。 + +## 查询ACL + +使用以下代码可以完成acl信息的查询。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +result, err := client.ListAclEntrys(vpcId) +if err != nil { + fmt.Println("list acl entrys error: ", err) + return +} + +// 查询得到acl所属的vpc id +fmt.Println("acl entrys of vpcId: ", result.VpcId) +// 查询得到acl所属的vpc名称 +fmt.Println("acl entrys of vpcName: ", result.VpcName) +// 查询得到acl所属的vpc网段 +fmt.Println("acl entrys of vpcCidr: ", result.VpcCidr) +// 查询得到acl的详细信息 +for _, acl := range result.AclEntrys { + fmt.Println("subnetId: ", acl.SubnetId) + fmt.Println("subnetName: ", acl.SubnetName) + fmt.Println("subnetCidr: ", acl.SubnetCidr) + fmt.Println("aclRules: ", acl.AclRules) +} +``` + +根据该接口得到的AclEntry列表,包括subnetId、subnetName、subnetCidr、aclRules。 + +## 添加ACL规则 + +根据以下代码可以创建acl规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +requests := []vpc.AclRuleRequest{ + { + // 设置acl规则所属的子网id + SubnetId: "sbn-e4cg8e8zkizs", + // 设置acl规则的协议 + Protocol: vpc.ACL_RULE_PROTOCOL_TCP, + // 设置acl规则的源ip + SourceIpAddress: "192.168.2.0", + // 设置acl规则的目的ip + DestinationIpAddress: "192.168.0.0/24", + // 设置acl规则的源端口 + SourcePort: "8888", + // 设置acl规则的目的端口 + DestinationPort: "9999", + // 设置acl规则的优先级 + Position: 12, + // 设置acl规则的方向 + Direction: vpc.ACL_RULE_DIRECTION_INGRESS, + // 设置acl规则的策略 + Action: vpc.ACL_RULE_ACTION_ALLOW, + // 设置acl规则的描述信息 + Description: "test", + }, +} +args := &vpc.CreateAclRuleArgs{ + AclRules: requests, +} + +if err := client.CreateAclRule(args); err != nil { + fmt.Println("create acl rule error: ", err) + return +} + +fmt.Println("create acl rule success.") +``` + +使用该接口可以一次创建多条acl规则,对规则参数中的注意事项描述如下: +- protocol: 支持的协议包括all tcp udp icmp +- sourcePort: 源端口,例如1-65535,或8080 +- destinationPort: 目的端口,例如1-65535,或8080 +- position: 优先级 1-5000且不能与已有条目重复。数值越小,优先级越高,规则匹配顺序为按优先级由高到低匹配 +- direction: 规则的入站ingress, 规则的出站egress +- action: 支持的策略包括allow和deny + +## 查询ACL规则 + +使用以下代码可以查询acl规则信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.ListAclRulesArgs{ + // 设置acl所属子网的id + SubnetId: subnetId, + // 设置批量获取列表的查询的起始位置 + Marker: marker, + // 设置每页包含的最大数量 + MaxKeys: maxKeys, +} + +result, err := client.ListAclRules(args) +if err != nil { + fmt.Println("list acl rules error: ", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("acl list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("acl list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("acl list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("acl list maxKeys: ", result.MaxKeys) +// 获取acl的列表信息 +for _, acl := range result.AclRules { + fmt.Println("acl rule id: ", acl.Id) + fmt.Println("acl rule subnetId: ", acl.SubnetId) + fmt.Println("acl rule description: ", acl.Description) + fmt.Println("acl rule protocol: ", acl.Protocol) + fmt.Println("acl rule sourceIpAddress: ", acl.SourceIpAddress) + fmt.Println("acl rule destinationIpAddress: ", acl.DestinationIpAddress) + fmt.Println("acl rule sourcePort: ", acl.SourcePort) + fmt.Println("acl rule destinationPort: ", acl.DestinationPort) + fmt.Println("acl rule position: ", acl.Position) + fmt.Println("acl rule direction: ", acl.Direction) + fmt.Println("acl rule action: ", acl.Action) +} +``` + +> 注意: +> - 使用该接口时,必需提供subnetId参数,以获取特定子网的acl规则列表信息。 +> - 系统为用户创建了2条默认ACL规则(无id)。其中入站和出站各一条,规则内容均为全入全出。默认规则,不支持更改和删除。 + +## 更新ACL规则 + +使用以下代码可以实现对特定acl规则的更新操作。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UpdateAclRuleArgs{ + // 设置acl的最新协议 + Protocol: vpc.ACL_RULE_PROTOCOL_TCP, + // 设置acl的源ip + SourceIpAddress: "192.168.2.0", + // 设置acl的目的ip + DestinationIpAddress: "192.168.0.0/24", + // 设置acl的源端口 + SourcePort: "3333", + // 设置acl的目的端口 + DestinationPort: "4444", + // 设置acl的优先级 + Position: 12, + // 设置acl的策略 + Action: vpc.ACL_RULE_ACTION_ALLOW, + // 设置acl最新的描述信息 + Description: "test", +} + +if err := client.UpdateAclRule(aclRuleId, args); err != nil { + fmt.Println("update acl rule error: ", err) + return +} + +fmt.Printf("update acl rule %s success.", aclRuleId) +``` + +以上接口可用于对acl规则各个字段的更新过程。 + +## 删除ACL规则 + +使用以下代码可以删除指定的acl规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.DeleteAclRule(aclRuleId, clientToken); err != nil { + fmt.Println("delete acl rule error: ", err) + return +} + +fmt.Printf("delete acl rule %s success.", aclRuleId) +``` + +> 注意: 参数中的clientToken表示幂等性Token,是一个长度不超过64位的ASCII字符串,详见[ClientToken幂等性](https://cloud.baidu.com/doc/VPC/s/gjwvyu77i/#%E5%B9%82%E7%AD%89%E6%80%A7) + + +# NAT网关管理 + +NAT(Network Address Translation)网关为私有网络提供访问Internet服务,支持SNAT和DNAT,可以使多台云服务器共享公网IP资源访问Internet,也可以使云服务器能够提供Internet服务。NAT网关可以绑定EIP实例及共享带宽,为云服务器实现从内网IP到公网IP的多对一或多对多的地址转换服务。 + +## 创建NAT网关 + +使用以下代码可以创建nat网关。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.CreateNatGatewayArgs{ + // 设置nat网关的名称 + Name: name, + // 设置nat网关所属的vpc id + VpcId: vpcId, + // 设置nat网关的规格 + Spec: vpc.NAT_GATEWAY_SPEC_SMALL, + // 设置nat网关的eip列表 + Eips: []string{eip}, + // 设置nat网关的计费信息 + Billing: &vpc.Billing{ + PaymentTiming: vpc.PAYMENT_TIMING_POSTPAID, + }, + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + }, +} +result, err := client.CreateNatGateway(args) +if err != nil { + fmt.Println("create nat gateway error: ", err) + return +} + +fmt.Println("create nat gateway success, nat gateway id: ", result.NatId) +``` + +> 注意: 创建过程中,应注意以下事项: +> - NAT网关的名称,由大小写字母、数字以及-_ /.特殊字符组成,必须以字母开头,长度1-65 +> - NAT网关的大小,有small(最多支持绑定5个公网IP)、medium(最多支持绑定10个公网IP)、large(最多支持绑定15个公网IP)三种 +> - NAT网关可以关联一个公网EIP或者共享带宽中的一个或多个EIP +> - 付款方式支持预支付(Prepaid)和后支付(Postpaid)两种,预支付当前仅支持按月,时长取值范围: [1,2,3,4,5,6,7,8,9,12,24,36] + +## 查询NAT网关列表 + +使用以下代码可以查询符合条件的nat网关列表。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.ListNatGatewayArgs{ + // 设置nat网关所属的vpc id,必选 + VpcId: vpcId, + // 指定查询的NAT的Id + NatId: natId, + // 指定查询的NAT的名称 + Name: name, + // 指定查询的NAT绑定的EIP + Ip: ip, + // 设置nat网关批量获取列表的查询的起始位置 + Marker: marker, + // 设置nat网关每页包含的最大数量,最大数量不超过1000。缺省值为1000 + MaxKeys: maxKeys, +} +result, err := client.ListNatGateway(args) +if err != nil { + fmt.Println("list nat gateway error: ", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("nat list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("nat list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("nat list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("nat list maxKeys: ", result.MaxKeys) +// 获取nat的列表信息 +for _, nat := range result.Nats { + fmt.Println("nat id: ", nat.Id) + fmt.Println("nat name: ", nat.Name) + fmt.Println("nat vpcId: ", nat.VpcId) + fmt.Println("nat spec: ", nat.Spec) + fmt.Println("nat eips: ", nat.Eips) + fmt.Println("nat status: ", nat.Status) + fmt.Println("nat paymentTiming: ", nat.PaymentTiming) + fmt.Println("nat expireTime: ", nat.ExpiredTime) + fmt.Println("nat tags: ", nat.Tags) +} +``` + +> 注意: +> - 可根据NAT网关ID、NAT网关的name、NAT网关绑定的EIP来查询。 +> - 若不提供查询条件,则默认查询覆盖所有NAT网关 +> - vpcId为必选参数 + +## 查询NAT网关详情 + +使用以下代码可以查询特定nat网关的详细信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +result, err := client.GetNatGatewayDetail(natId) +if err != nil { + fmt.Println("get nat gateway details error: ", err) + return +} + +// 查询得到nat网关的id +fmt.Println("nat id: ", result.Id) +// 查询得到nat网关的名称 +fmt.Println("nat name: ", result.Name) +// 查询得到nat网关所属的vpc id +fmt.Println("nat vpcId: ", result.VpcId) +// 查询得到nat网关的大小 +fmt.Println("nat spec: ", result.Spec) +// 查询得到nat网关绑定的EIP的IP地址列表 +fmt.Println("nat eips: ", result.Eips) +// 查询得到nat网关的状态 +fmt.Println("nat status: ", result.Status) +// 查询得到nat网关的付费方式 +fmt.Println("nat paymentTiming: ", result.PaymentTiming) +// 查询得到nat网关的过期时间 +fmt.Println("nat expireTime: ", result.ExpiredTime) +``` + +## 更新NAT网关名称 + +使用以下代码可以对nat网关的名称进行更改。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UpdateNatGatewayArgs{ + // 设置nat网关的最新名称 + Name: "TestNatUpdate", +} + +if err := client.UpdateNatGateway(natId, args); err != nil { + fmt.Println("update nat gateway error: ", err) + return +} + +fmt.Printf("update nat gateway %s success.", natId) +``` + +> 注意: 目前该接口仅支持对网关名称属性的更改。 + +## 绑定EIP + +使用以下代码可以为nat网关绑定eip。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.BindEipsArgs{ + // 设置绑定的EIP ID列表 + Eips: []string{eip}, +} +if err := client.BindEips(natId, args); err != nil { + fmt.Println("bind eips error: ", err) + return +} + +fmt.Println("bind eips success.") +``` + +注意: +- 若该NAT已经绑定EIP,必须解绑后才可绑定。 +- 若该NAT已经绑定共享带宽,可以继续绑定该共享带宽中的其他IP。 + +## 解绑EIP + +使用以下代码可以为nat网关解绑eip。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UnBindEipsArgs{ + // 设置解绑的EIP ID列表 + Eips: []string{eip}, +} +if err := client.UnBindEips(natId, args); err != nil { + fmt.Println("unbind eips error: ", err) + return +} + +fmt.Println("unbind eips success.") +``` + +## 绑定DNAT EIP + +使用以下代码可以为nat网关绑定DNAT EIP。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.BindDnatEipsArgs{ + // 设置绑定的DNAT EIP ID列表 + DnatEips: []string{dnatEips}, +} +if err := client.BindDnatEips(natId, args); err != nil { + fmt.Println("bind DNAT Eips error: ", err) + return +} + +fmt.Println("bind DNAT Eips success.") +``` + +注意: +- 若该NAT DNAT已经绑定EIP,必须解绑后才可绑定。 +- 若该NAT DNAT已经绑定共享带宽,可以继续绑定该共享带宽中的其他IP。 + +## 解绑DNAT EIP + +使用以下代码可以为nat网关解绑DNAT EIP。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UnBindDnatEipsArgs{ + // 设置解绑的DNAT EIP ID列表 + DnatEips: []string{dnatEips}, +} +if err := client.UnBindDnatEips(natId, args); err != nil { + fmt.Println("unbind DNAT Eips error: ", err) + return +} + +fmt.Println("unbind DNAT Eips success.") +``` + +## 释放NAT网关 + +使用以下代码释放特定的nat网关。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.DeleteNatGateway(natId, clientToken); err != nil { + fmt.Println("delete nat gateway error: ", err) + return +} + +fmt.Printf("delete nat gateway %s success.", natId) +``` + +> 注意: 预付费未到期的NAT网关不能释放。 + +## NAT网关续费 + +使用以下接口完成nat网关的续费操作,延长过期时间。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.RenewNatGatewayArgs{ + // 设置nat网关续费的订单信息 + Billing: &vpc.Billing{ + Reservation: &vpc.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, +} +if err := client.RenewNatGateway(natId, args); err != nil { + fmt.Println("renew nat gateway error: ", err) + return +} + +fmt.Printf("renew nat gateway %s success.", natId) +``` + +> 注意: +- 后付费的NAT网关不能续费 + +## 创建SNAT规则 +使用以下代码可以创建nat网关的snat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &CreateNatGatewaySnatRuleArgs{ +RuleName: "sdk-test", +PublicIpsAddress: []string{"100.88.10.84"}, +SourceCIDR: "192.168.3.3", +} +result, err := VPC_CLIENT.CreateNatGatewaySnatRule("nat-b1jb3b5e34tc", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 删除SNAT规则 +使用以下代码可以删除nat网关的snat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +VPC_CLIENT.DeleteNatGatewaySnatRule("nat-b1jb3b5e34tc", "rule-hprz7sv9zvcx", getClientToken()) +``` + +## 修改SNAT规则 +使用以下代码可以修改nat网关的snat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &UpdateNatGatewaySnatRuleArgs{ +RuleName: "sdk-test-1", +SourceCIDR: "192.168.3.6", +} +VPC_CLIENT.UpdateNatGatewaySnatRule("nat-b1jb3b5e34tc", "rule-hprz7sv9zvcx", args) +``` + +## 查询SNAT规则 +使用以下代码可以查询nat网关的snat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &ListNatGatewaySnatRuleArgs{ +NatId: "nat-b1jb3b5e34tc", +} +result, err := VPC_CLIENT.ListNatGatewaySnatRules(args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 创建DNAT规则 +使用以下代码可以创建nat网关的dnat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &CreateNatGatewayDnatRuleArgs{ + RuleName: "dnat_go", + PublicIpAddress: "100.88.14.90", + PrivateIpAddress: "192.168.1.1", + Protocol: "TCP", + PublicPort: "1212", + PrivatePort: "1212", +} +result, err := VPC_CLIENT.CreateNatGatewayDnatRule("nat-b1jb3b5e34tc", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +## 删除DNAT规则 +使用以下代码可以删除nat网关的dnat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +VPC_CLIENT.DeleteNatGatewayDnatRule("nat-b1jb3b5e34tc", "rule-8gee5abqins0", getClientToken()) +``` + +## 修改DNAT规则 +使用以下代码可以修改nat网关的dnat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &UpdateNatGatewayDnatRuleArgs{ +RuleName: "sdk-test-3", +PrivateIpAddress: "192.168.1.5", +} +VPC_CLIENT.UpdateNatGatewayDnatRule("nat-b1jb3b5e34tc", "rule-8gee5abqins0", args) +``` + +## 查询DNAT规则 +使用以下代码可以查询nat网关的dnat规则。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &ListNatGatewaDnatRuleArgs{} +result, err := VPC_CLIENT.ListNatGatewayDnatRules("nat-b1jb3b5e34tc", args) +ExpectEqual(t.Errorf, nil, err) +r, err := json.Marshal(result) +fmt.Println(string(r)) +``` + +# 对等连接管理 + +对等连接(Peer Connection)为用户提供了VPC级别的网络互联服务,使用户实现在不同虚拟网络之间的流量互通,实现同区域/跨区域,同用户/不同用户之间稳定高速的虚拟网络互联。 + +## 创建对等连接 + +使用以下代码创建对等连接。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.CreatePeerConnArgs{ + // 设置对等连接的带宽 + BandwidthInMbps: 10, + // 设置对等连接的描述信息 + Description: "test peer conn", + // 设置对等连接的本端端口名称 + LocalIfName: "local-interface", + // 设置对等连接的本端vpc的id + LocalVpcId: vpcId, + // 设置对等连接的对端账户ID,只有在建立跨账号的对等连接时需要该字段 + peerAccountId: peerAccountId, + // 设置对等连接的对端vpc的id + PeerVpcId: peerVpcId, + // 设置对等连接的对端区域 + PeerRegion: region, + // 设置对等连接的对端接口名称,只有本账号的对等连接才允许设置该字段 + PeerIfName: "peer-interface", + // 设置对等连接的计费信息 + Billing: &vpc.Billing{ + PaymentTiming: vpc.PAYMENT_TIMING_POSTPAID, + }, + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + }, +} +result, err := client.CreatePeerConn(args) +if err != nil { + fmt.Println("create peerconn error: ", err) + return +} + +fmt.Println("create peerconn success, peerconn id: ", result.PeerConnId) +``` + +> 注意: +> - 对于本端区域和对端区域相同的对等连接,只支持后付费。 +> - 跨账号的对等连接,必须接受端接受后对等连接才可用。 +> - 对于同账号的对等连接,系统会触发对端自动接受。 +> - 任意两个VPC之间最多只能存在一条对等连接。 +> - 发起端和接收端的VPC不能是同一个。 +> - 如果本端vpc和对端vpc均为中继vpc,则不可以建立对等连接。 + +## 查询对等连接列表 + +使用以下代码可以查询对等连接的列表信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.ListPeerConnsArgs{ + // 指定对等连接所属的vpc id + VpcId: vpcId, + // 指定批量获取列表的查询的起始位置 + Marker: marker, + // 指定每页包含的最大数量,最大数量不超过1000。缺省值为1000 + MaxKeys: maxKeys, +} +result, err := client.ListPeerConn(args) +if err != nil { + fmt.Println("list peer conns error: ", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("peerconn list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("peerconn list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("peerconn list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("peerconn list maxKeys: ", result.MaxKeys) +// 获取对等连接的列表信息 +for _, pc := range result.PeerConns { + fmt.Println("peerconn id: ", pc.PeerConnId) + fmt.Println("peerconn role: ", pc.Role) + fmt.Println("peerconn status: ", pc.Status) + fmt.Println("peerconn bandwithInMbp: ", pc.BandwidthInMbps) + fmt.Println("peerconn description: ", pc.Description) + fmt.Println("peerconn localIfId: ", pc.LocalIfId) + fmt.Println("peerconn localIfName: ", pc.LocalIfName) + fmt.Println("peerconn localVpcId: ", pc.LocalVpcId) + fmt.Println("peerconn localRegion: ", pc.LocalRegion) + fmt.Println("peerconn peerVpcId: ", pc.PeerVpcId) + fmt.Println("peerconn peerRegion: ", pc.PeerRegion) + fmt.Println("peerconn peerAccountId: ", pc.PeerAccountId) + fmt.Println("peerconn paymentTiming: ", pc.PaymentTiming) + fmt.Println("peerconn dnsStatus: ", pc.DnsStatus) + fmt.Println("peerconn createdTime: ", pc.CreatedTime) + fmt.Println("peerconn expiredTime: ", pc.ExpiredTime) +} +``` + +使用该接口可以查询得到所有符合条件的对等连接信息,其中,vpcId是可选参数。 + +## 查看对等连接详情 + +通过以下代码可以查询特定对等连接的详细信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +result, err := client.GetPeerConnDetail(peerConnId, vpc.PEERCONN_ROLE_INITIATOR) +if err != nil { + fmt.Println("get peer conn detail error: ", err) + return +} + +// 查询得到对等连接的id +fmt.Println("peerconn id: ", result.PeerConnId) +// 查询得到对等连接的角色, "initiator"表示发起端"acceptor"表示接受端 +fmt.Println("peerconn role: ", result.Role) +// 查询得到对等连接的状态 +fmt.Println("peerconn status: ", result.Status) +// 查询得到对等连接的带宽 +fmt.Println("peerconn bandwithInMbp: ", result.BandwidthInMbps) +// 查询得到对等连接的描述 +fmt.Println("peerconn description: ", result.Description) +// 查询得到对等连接的本端接口ID +fmt.Println("peerconn localIfId: ", result.LocalIfId) +// 查询得到对等连接的本端接口名称 +fmt.Println("peerconn localIfName: ", result.LocalIfName) +// 查询得到对等连接的本端VPC ID +fmt.Println("peerconn localVpcId: ", result.LocalVpcId) +// 查询得到对等连接的本端区域 +fmt.Println("peerconn localRegion: ", result.LocalRegion) +// 查询得到对等连接的对端VPC ID +fmt.Println("peerconn peerVpcId: ", result.PeerVpcId) +// 查询得到对等连接的对端区域 +fmt.Println("peerconn peerRegion: ", result.PeerRegion) +// 查询得到对等连接的对端账户ID +fmt.Println("peerconn peerAccountId: ", result.PeerAccountId) +// 查询得到对等连接的计费方式 +fmt.Println("peerconn paymentTiming: ", result.PaymentTiming) +// 查询得到对等连接的dns状态 +fmt.Println("peerconn dnsStatus: ", result.DnsStatus) +// 查询得到对等连接的创建时间 +fmt.Println("peerconn createdTime: ", result.CreatedTime) +// 查询得到对等连接的过期时间 +fmt.Println("peerconn expiredTime: ", result.ExpiredTime) +// 查询得到对等连接的标签 +fmt.Println("peerconn tags: ", result.Tags) +``` + +> 注意: "initiator"表示发起端"acceptor"表示接受端,同region的对等连接可以据此进行详情查询,若不设置该参数,同region则随机返回一端信息。 + +## 更新对等连接本端接口名称和备注 + +使用以下代码可以更新对等连接本端接口名称和备注。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.UpdatePeerConnArgs{ + // 设置对等连接的接口ID 不可更改,必选 + LocalIfId: localIfId, + // 设置对等连接的本端端口名称 + LocalIfName: "test-update", + // 设置对等连接的本端端口描述 + Description: "test-description", +} +if err := client.UpdatePeerConn(peerConnId, args); err != nil { + fmt.Println("update peer conn error: ", err) + return +} + +fmt.Printf("update peer conn %s success", peerConnId) +``` + +## 接受对等连接申请 + +使用以下代码可以接受对等连接的申请信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.AcceptPeerConnApply(peerConnId, clientToken); err != nil { + fmt.Println("accept peer conn error: ", err) + return +} + +fmt.Printf("accept peer conn %s success.", peerConnId) +``` + +> 注意: +> - 发起端发出的连接请求超时时间为7天,超时后发起端对等连接的状态为协商失败。 +> - 接收端拒绝后,发起端对等连接状态为协商失败。 + +## 拒绝对等连接申请 + +使用以下代码可以接受对等连接的申请信息。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.RejectPeerConnApply(peerConnId, clientToken); err != nil { + fmt.Println("reject peer conn error: ", err) + return +} + +fmt.Printf("reject peer conn %s success.", peerConnId) +``` + +## 释放对等连接 + +使用以下代码可以释放特定的对等连接。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +if err := client.DeletePeerConn(peerConnId, clientToken); err != nil { + fmt.Println("delete peer conn error: ", err) + return +} + +fmt.Printf("delete peer conn %s success", peerConnId) +``` + +> 注意: +> - 跨账号只有发起端可以释放。 +> - 预付费可用且未到期的对等连接不能释放。 +> - 预付费协商失败的可以释放。 + +## 对等连接带宽升降级 + +使用以下代码可以为指定的对等连接进行带宽升级操作。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.ResizePeerConnArgs{ + // 指定对等连接升降级的带宽 + NewBandwidthInMbps: 20, +} + +if err := client.ResizePeerConn(peerConnId, args); err != nil { + fmt.Println("resize peer conn error: ", err) + return +} + +fmt.Printf("resize peer conn %s success.", peerConnId) +``` + +> 注意: +> - 跨账号只有发起端才可以进行带宽的升降级操作。 +> - 预付费的对等连接只能进行带宽升级不能降级。 +> - 后付费的对等连接可以进行带宽的升级和降级。 + +## 对等连接续费 + +使用以下代码可以为对等连接进行续费操作,延长过期时间。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.RenewPeerConnArgs{ + // 指定对等连接的续费信息 + Billing: &vpc.Billing{ + Reservation: &vpc.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, +} + +if err := client.RenewPeerConn(peerConnId, args); err != nil { + fmt.Println("renew peer conn error: ", err) + return +} + +fmt.Printf("renew peer conn %s success.", peerConnId) +``` + +> 注意: +> - 后付费的对等连接不能续费。 +> - 跨账号续费操作只能由发起端来操作。 + +## 开启对等连接同步DNS + +使用以下代码可以开启对等连接同步DNS记录。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.PeerConnSyncDNSArgs{ + // 指定对等连接的角色,发起端"initiator" 接收端"acceptor" + Role: vpc.PEERCONN_ROLE_INITIATOR, +} + +if err := client.OpenPeerConnSyncDNS(peerConnId, args); err != nil { + fmt.Println("open peer conn sync dns error: ", err) + return +} + +fmt.Printf("open peer conn %s sync dns success.", peerConnId) +``` + +> 注意: +> - 对等连接的状态为可用的时候才能开启DNS。 +> - 对等连接的DNS状态为同步中或同步关闭中不可开启同步DNS。 + +## 关闭对等连接同步DNS + +使用以下代码可以关闭对等连接同步DNS记录。 +```go +//import "github.com/baidubce/bce-sdk-go/services/vpc" + +args := &vpc.PeerConnSyncDNSArgs{ + // 指定对等连接的角色,发起端"initiator" 接收端"acceptor" + Role: vpc.PEERCONN_ROLE_INITIATOR, +} + +if err := client.ClosePeerConnSyncDNS(peerConnId, args); err != nil { + fmt.Println("close peer conn sync dns error: ", err) + return +} + +fmt.Printf("close peer conn %s sync dns success.", peerConnId) +``` + +> 注意: +> - 对等连接的状态为可用的时候才能关闭DNS。 +> - 对等连接的DNS状态为同步中或同步关闭中不可关闭同步DNS。 + + +# 错误处理 + +GO语言以error类型标识错误,VPC支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | VPC服务返回的错误 + +用户使用SDK调用VPC相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// vpcClient 为已创建的VPC Client对象 +args := &vpc.ListVPCArgs{} +result, err := client.ListVPC(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向VPC发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当VPC服务端出现异常时,VPC服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[VPC错误信息格式](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +VPC GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +VPC GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the VPC go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the VPC go sdk") +``` + + +# 版本变更记录 +## v0.9.8 [2022-11-14] +- 路由支持:专线网关、对等连接、IPv6网关、弹性网卡、高可用虚拟IP类型 +## v0.9.7 [2022-11-14] +- NAT、对等连接创建、详情接口支持Tags +## v0.9.6 [2020-12-27] +- 增加vpc查询PrivateIpAddress信息接口 +## v0.9.5 [2019-09-24] + +首次发布: + + - 支持创建VPC、查询VPC列表、查询指定VPC、删除VPC、更新VPC接口; + - 支持创建子网、查询子网列表、查询指定子网、删除子网、更新子网接口; + - 支持查询路由表、创建路由规则、删除路由规则接口; + - 支持查询ACL、添加ACL规则、查询ACL规则、更新ACL规则、删除ACL规则接口; + - 支持创建NAT网关、查询NAT网关列表、查询NAT网关详情、更新NAT网关名称、绑定EIP、解绑EIP、释放NAT网关、NAT网关续费接口; + - 支持创建对等连接、查询对等连接列表、查看对等连接详情、更新对等连接本端接口名称和备注、接受对等连接申请、拒绝对等连接申请、释放对等连接、对等连接带宽升降级、对等连接续费、开启对等连接同步DNS、关闭对等连接同步DNS接口。 + \ No newline at end of file diff --git a/bce-sdk-go/doc/VPN.md b/bce-sdk-go/doc/VPN.md new file mode 100644 index 0000000..57917ec --- /dev/null +++ b/bce-sdk-go/doc/VPN.md @@ -0,0 +1,799 @@ +# VPN服务 + +# 概述 + +本文档主要介绍VPN GO SDK的使用。在使用本文档前,您需要先了解VPN的一些基本知识,并已开通了VPN服务。若您还不了解VPN,可以参考[产品描述](https://cloud.baidu.com/doc/VPC/s/sjwvytvh0)和[操作指南](https://cloud.baidu.com/doc/VPC/s/9jwvytzz8)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[VPN服务域名](https://cloud.baidu.com/doc/VPC/s/xjwvyuhpw)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”、“香港”、“金融华中-武汉”和“华北-保定”六个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | bcc.bj.baidubce.com | HTTP and HTTPS +GZ | bcc.gz.baidubce.com | HTTP and HTTPS +SU | bcc.su.baidubce.com | HTTP and HTTPS +HKG| bcc.hkg.baidubce.com| HTTP and HTTPS +FWH| bcc.fwh.baidubce.com| HTTP and HTTPS +BD | bcc.bd.baidubce.com | HTTP and HTTPS + +## 获取密钥 + +要使用百度云VPN,您需要拥有一个有效的AK(Access Key ID)和SK(Secret Access Key)用来进行签名认证。AK/SK是由系统分配给用户的,均为字符串,用于标识用户,为访问VPN做签名验证。 + +可以通过如下步骤获得并了解您的AK/SK信息: + +[注册百度云账号](https://login.bce.baidu.com/reg.html?tpl=bceplat&from=portal) + +[创建AK/SK](https://console.bce.baidu.com/iam/?_=1513940574695#/iam/accesslist) + +## 新建VPN Client + +VPN Client是VPN服务的客户端,为开发者与VPN服务进行交互提供了一系列的方法。 + +### 使用AK/SK新建VPN Client + +通过AK/SK方式访问VPN,用户可以参考如下代码新建一个VPN Client: + +```go +import ( + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func main() { + // 用户的Access Key ID和Secret Access Key + ACCESS_KEY_ID, SECRET_ACCESS_KEY := , + + // 用户指定的Endpoint + ENDPOINT := + + // 初始化一个VPNClient + vpnClient, err := vpn.NewClient(AK, SK, ENDPOINT) +} +``` + +在上面代码中,`ACCESS_KEY_ID`对应控制台中的“Access Key ID”,`SECRET_ACCESS_KEY`对应控制台中的“Access Key Secret”,获取方式请参考《操作指南 [如何获取AKSK](https://cloud.baidu.com/doc/Reference/s/9jwvz2egb/)》。第三个参数`ENDPOINT`支持用户自己指定域名,如果设置为空字符串,会使用默认域名作为VPC的服务地址。 + +> **注意:**`ENDPOINT`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`bcc.bj.baidubce.com`。 + +### 使用STS创建VPN Client + +**申请STS token** + +VPN可以通过STS机制实现第三方的临时授权访问。STS(Security Token Service)是百度云提供的临时授权服务。通过STS,您可以为第三方用户颁发一个自定义时效和权限的访问凭证。第三方用户可以使用该访问凭证直接调用百度云的API或SDK访问百度云资源。 + +通过STS方式访问VPN,用户需要先通过STS的client申请一个认证字符串。 + +**用STS token新建VPN Client** + +申请好STS后,可将STS Token配置到VPN Client中,从而实现通过STS Token创建VPN Client。 + +**代码示例** + +GO SDK实现了STS服务的接口,用户可以参考如下完整代码,实现申请STS Token和创建VPN Client对象: + +```go +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/auth" //导入认证模块 + "github.com/baidubce/bce-sdk-go/services/vpn" //导入VPN服务模块 + "github.com/baidubce/bce-sdk-go/services/sts" //导入STS服务模块 +) + +func main() { + // 创建STS服务的Client对象,Endpoint使用默认值 + AK, SK := , + stsClient, err := sts.NewClient(AK, SK) + if err != nil { + fmt.Println("create sts client object :", err) + return + } + + // 获取临时认证token,有效期为60秒,ACL为空 + stsObj, err := stsClient.GetSessionToken(60, "") + if err != nil { + fmt.Println("get session token failed:", err) + return + } + fmt.Println("GetSessionToken result:") + fmt.Println(" accessKeyId:", stsObj.AccessKeyId) + fmt.Println(" secretAccessKey:", stsObj.SecretAccessKey) + fmt.Println(" sessionToken:", stsObj.SessionToken) + fmt.Println(" createTime:", stsObj.CreateTime) + fmt.Println(" expiration:", stsObj.Expiration) + fmt.Println(" userId:", stsObj.UserId) + + // 使用申请的临时STS创建VPN服务的Client对象,Endpoint使用默认值 + vpnClient, err := vpn.NewClient(stsObj.AccessKeyId, stsObj.SecretAccessKey, "bcc.bj.baidubce.com") + if err != nil { + fmt.Println("create vpn client failed:", err) + return + } + stsCredential, err := auth.NewSessionBceCredentials( + stsObj.AccessKeyId, + stsObj.SecretAccessKey, + stsObj.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return + } + vpnClient.Config.Credentials = stsCredential +} +``` + +> 注意: +> 目前使用STS配置VPN Client时,无论对应VPN服务的Endpoint在哪里,STS的Endpoint都需配置为http://sts.bj.baidubce.com。上述代码中创建STS对象时使用此默认值。 + +# 配置HTTPS协议访问VPN + +VPN支持HTTPS传输协议,您可以通过在创建VPN Client对象时指定的Endpoint中指明HTTPS的方式,在VPN GO SDK中使用HTTPS访问VPN服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +ENDPOINT := "https://bcc.bj.baidubce.com" //指明使用HTTPS协议 +AK, SK := , +vpnClient, _ := vpn.NewClient(AK, SK, ENDPOINT) +``` + +## 配置VPN Client + +如果用户需要配置VPN Client的一些细节的参数,可以在创建VPN Client对象之后,使用该对象的导出字段`Config`进行自定义配置,可以为客户端配置代理,最大连接数等参数。 + +### 使用代理 + +下面一段代码可以让客户端使用代理访问VPN服务: + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +//创建VPN Client对象 +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := vpn.NewClient(AK, SK, ENDPOINT) + +//代理使用本地的8080端口 +client.Config.ProxyUrl = "127.0.0.1:8080" +``` + +### 设置网络参数 + +用户可以通过如下的示例代码进行网络参数的设置: + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := vpn.NewClient(AK, SK, ENDPOINT) + +// 配置不进行重试,默认为Back Off重试 +client.Config.Retry = bce.NewNoRetryPolicy() + +// 配置连接超时时间为30秒 +client.Config.ConnectionTimeoutInMillis = 30 * 1000 +``` + +### 配置生成签名字符串选项 + +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +AK, SK := , +ENDPOINT := "bcc.bj.baidubce.com" +client, _ := vpn.NewClient(AK, SK, ENDPOINT) + +// 配置签名使用的HTTP请求头为`Host` +headersToSign := map[string]struct{}{"Host": struct{}{}} +client.Config.SignOption.HeadersToSign = HeadersToSign + +// 配置签名的有效期为30秒 +client.Config.SignOption.ExpireSeconds = 30 +``` + +**参数说明** + +用户使用GO SDK访问VPN时,创建的VPN Client对象的`Config`字段支持的所有参数如下表所示: + +配置项名称 | 类型 | 含义 +-----------|---------|-------- +Endpoint | string | 请求服务的域名 +ProxyUrl | string | 客户端请求的代理地址 +Region | string | 请求资源的区域 +UserAgent | string | 用户名称,HTTP请求的User-Agent头 +Credentials| \*auth.BceCredentials | 请求的鉴权对象,分为普通AK/SK与STS两种 +SignOption | \*auth.SignOptions | 认证字符串签名选项 +Retry | RetryPolicy | 连接重试策略 +ConnectionTimeoutInMillis| int | 连接超时时间,单位毫秒,默认20分钟 + +说明: + + 1. `Credentials`字段使用`auth.NewBceCredentials`与`auth.NewSessionBceCredentials`函数创建,默认使用前者,后者为使用STS鉴权时使用,详见“使用STS创建VPN Client”小节。 + 2. `SignOption`字段为生成签名字符串时的选项,详见下表说明: + +名称 | 类型 | 含义 +--------------|-------|----------- +HeadersToSign |map[string]struct{} | 生成签名字符串时使用的HTTP头 +Timestamp | int64 | 生成的签名字符串中使用的时间戳,默认使用请求发送时的值 +ExpireSeconds | int | 签名字符串的有效期 + + 其中,HeadersToSign默认为`Host`,`Content-Type`,`Content-Length`,`Content-MD5`;TimeStamp一般为零值,表示使用调用生成认证字符串时的时间戳,用户一般不应该明确指定该字段的值;ExpireSeconds默认为1800秒即30分钟。 + 3. `Retry`字段指定重试策略,目前支持两种:`NoRetryPolicy`和`BackOffRetryPolicy`。默认使用后者,该重试策略是指定最大重试次数、最长重试时间和重试基数,按照重试基数乘以2的指数级增长的方式进行重试,直到达到最大重试测试或者最长重试时间为止。 + + + +## 创建VPN + +使用以下代码可以申请一个VPN。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &vpn.CreateVpnGatewayArgs{ + VpnName: "TestSDK-VPN", + Description: "vpn test", + VpcId: "vpcId", + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_PREPAID, + Reservation: &Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + ClientToken: getClientToken(), +} +result, err := client.CreateVpnGateway(args) +if err != nil { + fmt.Printf("create vpn error: %+v\n", err) + return +} + +fmt.Println("create vpn success, vpn: ", result.VpnId) +``` + + +## 查询VPN 列表 + +使用以下代码可以查询VPN列表。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &vpn.ListVpnGatewayArgs{ + MaxKeys: 1000, + VpcId: "vpcId", + } + result, err := client.ListVpnGateway(args) + if err != nil { + fmt.Printf("list vpn error: %+v\n", err) + return + } + // 返回标记查询的起始位置 + fmt.Println("vpn list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("vpn list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("vpn list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("vpn list maxKeys: ", result.MaxKeys) + // 获取vpn的列表信息 + for _, e := range res.Vpns { + fmt.Println("vpn id: ", e.VpnId) + fmt.Println("vpn eip: ", e.Eip) + fmt.Println("vpn status: ", e.Status) + fmt.Println("vpn vpcId: ", e.VpcId) + fmt.Println("vpn description: ", e.Description) + fmt.Println("vpn expiredTime: ", e.ExpiredTime) + fmt.Println("vpn paymentTiming: ", e.ProductType) + fmt.Println("vpn vpnConnNum: ", e.VpnConnNum) + fmt.Println("vpn bandwidthInMbps: ", e.BandwidthInMbps) + fmt.Println("vpn vpnName: ", e.Name) + fmt.Println("vpn expireTime: ", e.ExpiredTime) + } +``` + +## 查询VPN详情 + +使用以下代码可以实现查询VPN的详情信息。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" +result,err:=vpn.GetVpnGatewayDetail("vpnId") + + if err != nil { + fmt.Printf("get vpn detail error: %+v\n", err) + return + } + fmt.Println("vpn id: ", result.VpnId) + fmt.Println("vpn eip: ", result.Eip) + fmt.Println("vpn status: ", result.Status) + fmt.Println("vpn vpcId: ", result.VpcId) + fmt.Println("vpn description: ", result.Description) + fmt.Println("vpn expiredTime: ", result.ExpiredTime) + fmt.Println("vpn paymentTiming: ", result.ProductType) + fmt.Println("vpn vpnConnNum: ", result.VpnConnNum) + fmt.Println("vpn bandwidthInMbps: ", result.BandwidthInMbps) + fmt.Println("vpn vpnName: ", result.Name) + fmt.Println("vpn expireTime: ", result.ExpiredTime) +} +``` + +## 更新VPN网关 + +使用以下代码可以实现VPN网关的更新。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" +args := &vpn.UpdateVpnGatewayArgs{ + ClientToken: getClientToken(), + Name: "vpnTest", + } + err := client.UpdateVpnGateway("vpnId", args) +if err != nil { + fmt.Printf("update vpn error: %+v\n", err) + return +} +fmt.Printf("update vpn success\n") +``` + + +## 释放VPN + +使用以下代码可以释放指定的VPN。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +err = client.DeleteVpn(vpnId, clientToken) +if err != nil { + fmt.Printf("delete vpn error: %+v\n", err) + return +} + +fmt.Printf("delete vpn success\n") +``` + +> 注意: +> - 释放指定VPN,被释放的VPN无法找回 +> - 预付费购买的VPN如需提前释放,请通过工单进行 + +## 绑定EIP + +使用以下代码可以将EIP绑定到VPN。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &vpn.BindEipArgs{ + ClientToken: ClientToken(), + Eip: Eip, + } +err := client.BindEip(vpnId, args) +if err != nil { + fmt.Printf("bind eip error: %+v\n", err) + return +} +``` + +> 注意: +> - 绑定EIP是一个异步过程,可以通过查询VPN的状态判断绑定是否成功 + + +## 解绑EIP + +使用以下代码可以将VPN的EIP进行解绑。 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" +if err := client.UnBindEip(vpnId, clientToken); err != nil { + fmt.Printf("unbind eip error: %+v\n", err) + return +} + +fmt.Printf("unbind eip success.") +``` + +> 注意: 解绑EIP是一个异步过程,可以通过查询VPN的状态判断绑定是否成功 + +## VPN网关续费 +使用以下代码可以延长VPN的到期时间 + ```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" +args := &vpn.RenewVpnGatewayArgs{ + ClientToken: ClientToken, + Billing: &Billing{ + Reservation: &Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, +} +if err := client.RenewVpnGateway(vpnId, args); err != nil { + fmt.Printf(" renew vpn error: %+v\n", err) + return +} + +fmt.Printf("renew vpn success.") +``` + +> 注意: +> - 仅预付费资源可以进行续费操作。 + +## 创建VPN隧道 +使用以下代码可以为指定的VPN创建隧道 + ```go + // import "github.com/baidubce/bce-sdk-go/services/vpn" + args := &vpn.CreateVpnConnArgs{ + VpnId: VpnId, + VpnConnName: VpnConnName, + LocalIp: LocalIp, + SecretKey: SecretKey, + LocalSubnets: []string{"subnet"}, + RemoteIp: RemoteIp, + RemoteSubnets: []string{"RemoteSubnet"}, + CreateIkeConfig: &CreateIkeConfig{ + IkeVersion: "v1", + IkeMode: "main", + IkeEncAlg: "aes", + IkeAuthAlg: "sha1", + IkePfs: "group2", + IkeLifeTime: 25500, + }, + CreateIpsecConfig: &CreateIpsecConfig{ + IpsecEncAlg: "aes", + IpsecAuthAlg: "sha1", + IpsecPfs: "group2", + IpsecLifetime: 25500, + }, + } + res, err := client.CreateVpnConn(args) + if err != nil { + fmt.Printf(" create vpnconn error: %+v\n", err) + return + } + fmt.Printf(" create vpnconn success,connId is: %+v",res.VpnConnId) + ``` +## 查询VPN隧道 +使用一下代码可以查询指定VPN的隧道信息 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + result,err:=vpn.ListVpnConn("vpnId") + if err != nil { + fmt.Printf("get vpn detail error: %+v\n", err) + return + } + for _, e := range result.VpnConns { + fmt.Println("vpnconn Id: ", e.VpnConnId) + fmt.Println("vpnconn LocalIp: ",e.LocalIp) + fmt.Println("vpnconn Description: ",e.Description) + fmt.Println("vpnconn CreatedTime: ",e.CreatedTime) + fmt.Println("vpnconn HealthStatus: ",e.HealthStatus) + fmt.Println("vpnconn LocalIp: ",e.LocalIp) + fmt.Println("vpnconn LocalSubnets: ",e.LocalSubnets) + fmt.Println("vpnconn RemoteSubnets: ",e.RemoteSubnets) + fmt.Println("vpnconn IkeConfig: ",e.IkeConfig) + fmt.Println("vpnconn IpsecConfig: ",e.IpsecConfig) + } +``` +## 更新VPN隧道 +使用以下代码可以修改指定的VPN隧道 + ```go + // import "github.com/baidubce/bce-sdk-go/services/vpn" + args := &vpn.UpdateVpnConnArgs{ + vpnConnId: vpnConnId, + updateVpnconn: &CreateVpnConnArgs{ + VpnId: VpnId, + VpnConnName: VpnConnName, + LocalIp: LocalIp, + SecretKey: SecretKey, + LocalSubnets: []string{"LocalSubnets"}, + RemoteIp: RemoteIp, + RemoteSubnets: []string{"RemoteSubnets"}, + CreateIkeConfig: &CreateIkeConfig{ + IkeVersion: "v1", + IkeMode: "main", + IkeEncAlg: "aes", + IkeAuthAlg: "sha1", + IkePfs: "group2", + IkeLifeTime: 25500, + }, + CreateIpsecConfig: &CreateIpsecConfig{ + IpsecEncAlg: "aes", + IpsecAuthAlg: "sha1", + IpsecPfs: "group2", + IpsecLifetime: 25500, + }, + }, + } + err := client.UpdateVpnConn(args) + if err != nil { + fmt.Printf(" uodate vpnconn error: %+v\n", err) + return + } + fmt.Printf(" update vpnconn success,connId is: %+v",res.VpnConnId) + ``` +## 删除VPN隧道 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +err = client.DeleteVpnConn(vpnconnId, clientToken) +if err != nil { + fmt.Printf("delete vpnconn error: %+v\n", err) + return +} + +fmt.Printf("delete vpnconn success\n") +``` +## 创建SSL-VPN服务端 +使用一下代码可以创建指定VPN的SSL-VPN服务端 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &vpn.CreateSslVpnServerArgs{ + ClientToken: ClientToken(), + VpnId: VpnId, + SslVpnServerName: SslVpnServerName, + InterfaceType: InterfaceType, + LocalSubnets: []string{"subnet"}, + RemoteSubnet: RemoteSubnet, + ClientDns: ClientDns, +} +res, err := client.CreateSslVpnServer(args) +ExpectEqual(t.Errorf, nil, err) +if err1 != nil { + fmt.Printf("create ssl-vpn server error: %+v\n", err) + return +} +fmt.Printf("create ssl-vpn server success,sslVpnServerId is: %+v",res.SslVpnServerId) +``` +> 一个vpn中已经存在的ssl-vpn server只能有一个,如果某个vpn已经存在ssl-vpn server,则再次创建会失败,只能先删除再创建 +## 查询SSL-VPN服务端 +使用一下代码可以查询指定VPN的SSL-VPN服务端 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +result,err := client.GetSslVpnServer(vpnId,clientToken) +if err != nil { + fmt.Printf("get ssl-vpn server error: %+v\n", err) + return +} + +// 查询得到vpn的id +fmt.Println("vpn id: ", result.VpnId) +// 查询得到SSL-VPN服务端的id +fmt.Println("SSL-VPN server id: ", result.SslVpnServerId) +// 查询得到SSL-VPN服务端的名称 +fmt.Println("SSL-VPN server name: ", result.SslVpnServerName) +// 查询得到SSL-VPN服务端的接口类型 +fmt.Println("SSL-VPN server interface type: ", result.InterfaceType) +// 查询得到SSL-VPN服务端状态 +fmt.Println("SSL-VPN server status: ", result.Status) +// 查询得到本端网络CIDR列表 +fmt.Println("SSL-VPN server local subnets: ", result.LocalSubnets) +// 查询得到客户端网络CIDR +fmt.Println("SSL-VPN server remote subnet: ", result.RemoteSubnet) +// 查询得到客户端的DNS地址 +fmt.Println("SSL-VPN server client dns: ", result.ClientDns) +// 查询得到SSL-VPN最大客户端连接数 +fmt.Println("SSL-VPN server max connection: ", result.MaxConnection) +``` +## 更新SSL-VPN服务端 +使用以下代码可以修改指定VPN的SSL-VPN服务端 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &vpn.UpdateSslVpnServerArgs{ + ClientToken: ClientToken(), + VpnId: VpnId, + SslVpnServerId: SslVpnServerId, + RemoteSubnets: []string{"subnet"}, + UpdateSslVpnServer: &UpdateSslVpnServer{ + SslVpnServerName: SslVpnServerName, + LocalSubnets: LocalSubnets, + RemoteSubnet: RemoteSubnet, + ClientDns: ClientDns, + }, +} +err := client.UpdateSslVpnServer(args) +if err != nil { + fmt.Printf("update ssl-vpn server error: %+v\n", err) + return +} +fmt.Printf("update ssl-vpn server success") +``` +## 删除SSL-VPN服务端 +使用以下代码可以删除指定VPN的SSL-VPN服务端 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +err := client.DeleteSslVpnServer(vpnId, sslVpnServerId, clientToken) +if err != nil { + fmt.Printf("delete ssl-vpn server error: %+v\n", err) + return +} + +fmt.Printf("delete ssl-vpn server success\n") +``` +> 删除SSL-VPN服务端需要保证这个server里面的用户全部删除之后,server才能删除成功 +## 批量创建SSL-VPN用户 +使用以下代码可以批量创建指定VPN的SSL-VPN用户 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &BatchCreateSslVpnUserArgs{ + ClientToken: ClientToken(), + VpnId: VpnId, + SslVpnUsers: []SslVpnUser{ + SslVpnUser{ + UserName: UserName, + Password: Password, + Description: Description, + }, + SslVpnUser{ + UserName: UserName + Password: UserName, + }, + }, +} +res, err := client.BatchCreateSslVpnUser(args) +ExpectEqual(t.Errorf, nil, err) +if err1 != nil { + fmt.Printf("batch create ssl-vpn user error: %+v\n", err) + return +} +fmt.Printf("batch create ssl-vpn user success,SslVpnUserIds are: %+v",res.SslVpnUserIds) +``` +## 查询SSL-VPN用户 +使用一下代码可以查询指定VPN的SSL-VPN用户列表 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &ListSslVpnUserArgs{ + MaxKeys: MaxKeys, + VpnId: VpnId, +} +result,err := client.ListSslVpnUser(args) +if err != nil { + fmt.Printf("get ssl-vpn user error: %+v\n", err) + return +} + +// 返回标记查询的起始位置 +fmt.Println("ssl-vpn user list marker: ", result.Marker) +// true表示后面还有数据,false表示已经是最后一页 +fmt.Println("ssl-vpn user list isTruncated: ", result.IsTruncated) +// 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 +fmt.Println("ssl-vpn user list nextMarker: ", result.NextMarker) +// 每页包含的最大数量 +fmt.Println("ssl-vpn user list maxKeys: ", result.MaxKeys) +// 获取ssl-vpn user的具体信息 +for _, v := range result.SslVpnUsers { + fmt.Println("ssl-vpn user id: ", v.UserId) + fmt.Println("ssl-vpn username: ", v.UserName) + fmt.Println("ssl-vpn user description: ", v.Description) +} +``` +## 更新SSL-VPN用户 +使用以下代码可以修改指定VPN的SSL-VPN用户信息 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +args := &UpdateSslVpnUserArgs{ + ClientToken: ClientToken(), + VpnId: VpnId, + UserId: UserId, + SslVpnUser: &UpdateSslVpnUser{ + Password: Password, + Description: Description, + }, +} +err := client.UpdateSslVpnUser(args) +if err != nil { + fmt.Printf("update ssl-vpn user error: %+v\n", err) + return +} +fmt.Printf("update ssl-vpn user success") +``` +> SSL-VPN用户的用户名不能更改,这个用户名一般是唯一不变的账户名称 +## 删除SSL-VPN用户 +```go +// import "github.com/baidubce/bce-sdk-go/services/vpn" + +err := client.DeleteSslVpnUser(vpnId, userId, clientToken) +if err != nil { + fmt.Printf("delete ssl-vpn user error: %+v\n", err) + return +} + +fmt.Printf("delete ssl-vpn user success\n") +``` +# 错误处理 + +GO语言以error类型标识错误,VPN支持两种错误见下表: + +错误类型 | 说明 +----------------|------------------- +BceClientError | 用户操作产生的错误 +BceServiceError | VPN服务返回的错误 + +用户使用SDK调用VPN相关接口,除了返回所需的结果之外还会返回错误,用户可以获取相关错误进行处理。实例如下: + +``` +// vpnClient 为已创建的VPN Client对象 +args := &vpn.ListVpnGatewayArgs{} +result, err := client.ListVpnGateway(args) +if err != nil { + switch realErr := err.(type) { + case *bce.BceClientError: + fmt.Println("client occurs error:", realErr.Error()) + case *bce.BceServiceError: + fmt.Println("service occurs error:", realErr.Error()) + default: + fmt.Println("unknown error:", err) + } +} +``` + +## 客户端异常 + +客户端异常表示客户端尝试向VPN发送请求以及数据传输时遇到的异常。例如,当发送请求时网络连接不可用时,则会返回BceClientError。 + +## 服务端异常 + +当VPN服务端出现异常时,VPN服务端会返回给用户相应的错误信息,以便定位问题。常见服务端异常可参见[VPN错误码](https://cloud.baidu.com/doc/VPC/s/sjwvyuhe7) + +## SDK日志 + +VPN GO SDK支持六个级别、三种输出(标准输出、标准错误、文件)、基本格式设置的日志模块,导入路径为`github.com/baidubce/bce-sdk-go/util/log`。输出为文件时支持设置五种日志滚动方式(不滚动、按天、按小时、按分钟、按大小),此时还需设置输出日志文件的目录。 + +### 默认日志 + +VPN GO SDK自身使用包级别的全局日志对象,该对象默认情况下不记录日志,如果需要输出SDK相关日志需要用户自定指定输出方式和级别,详见如下示例: + +``` +// import "github.com/baidubce/bce-sdk-go/util/log" + +// 指定输出到标准错误,输出INFO及以上级别 +log.SetLogHandler(log.STDERR) +log.SetLogLevel(log.INFO) + +// 指定输出到标准错误和文件,DEBUG及以上级别,以1GB文件大小进行滚动 +log.SetLogHandler(log.STDERR | log.FILE) +log.SetLogDir("/tmp/gosdk-log") +log.SetRotateType(log.ROTATE_SIZE) +log.SetRotateSize(1 << 30) + +// 输出到标准输出,仅输出级别和日志消息 +log.SetLogHandler(log.STDOUT) +log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_MSG}) +``` + +说明: + 1. 日志默认输出级别为`DEBUG` + 2. 如果设置为输出到文件,默认日志输出目录为`/tmp`,默认按小时滚动 + 3. 如果设置为输出到文件且按大小滚动,默认滚动大小为1GB + 4. 默认的日志输出格式为:`FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG` + +### 项目使用 + +该日志模块无任何外部依赖,用户使用GO SDK开发项目,可以直接引用该日志模块自行在项目中使用,用户可以继续使用GO SDK使用的包级别的日志对象,也可创建新的日志对象,详见如下示例: + +``` +// 直接使用包级别全局日志对象(会和GO SDK自身日志一并输出) +log.SetLogHandler(log.STDERR) +log.Debugf("%s", "logging message using the log package in the VPN go sdk") + +// 创建新的日志对象(依据自定义设置输出日志,与GO SDK日志输出分离) +myLogger := log.NewLogger() +myLogger.SetLogHandler(log.FILE) +myLogger.SetLogDir("/home/log") +myLogger.SetRotateType(log.ROTATE_SIZE) +myLogger.Info("this is my own logger from the VPN go sdk") +``` + + +# 版本变更记录 + +## v0.9.5 [2020-05-26] + +首次发布: + + - 支持创建VPN、查询VPN列表、查询VPN详情、更新VPN、释放VPN、绑定/解绑EIP、创建VPN隧道、查询VPN隧道、更新VPN隧道、删除VPN隧道。 \ No newline at end of file diff --git a/bce-sdk-go/examples/appblb/example_bind_enterprise_security_groups.go b/bce-sdk-go/examples/appblb/example_bind_enterprise_security_groups.go new file mode 100644 index 0000000..61c9361 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_bind_enterprise_security_groups.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func BindEnterpriseSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.UpdateEnterpriseSecurityGroupsArgs{ + // 设置要绑定的 enterprise security group 列表 + EnterpriseSecurityGroupIds: []string{"esg-djr0dtxxxxnx"}, // 替换为需要绑定的 enterprise security group 列表 + } + + if err := appblbClient.BindEnterpriseSecurityGroups(AppBlbID, args); err != nil { + fmt.Println("bind enterprise security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_bind_security_groups.go b/bce-sdk-go/examples/appblb/example_bind_security_groups.go new file mode 100644 index 0000000..813ce49 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_bind_security_groups.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func BindSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.UpdateSecurityGroupsArgs{ + // 设置要绑定的 security group 列表 + SecurityGroupIds: []string{"g-wrukksxxxxz5"}, // 替换为需要绑定的 security group 列表 + } + + if err := appblbClient.BindSecurityGroups(AppBlbID, args); err != nil { + fmt.Println("bind security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_http_listener.go b/bce-sdk-go/examples/appblb/example_create_app_http_listener.go new file mode 100644 index 0000000..a8b9363 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_http_listener.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateAppHTTPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createAppHTTPListenerArgs := &appblb.CreateAppHTTPListenerArgs{ + ListenerPort: 8080, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 创建appblb http监听器 + if err := appBlbClient.CreateAppHTTPListener(blbID, createAppHTTPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_https_listener.go b/bce-sdk-go/examples/appblb/example_create_app_https_listener.go new file mode 100644 index 0000000..5c027f6 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_https_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateAppHTTPSListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createAppHTTPSListenerArgs := &appblb.CreateAppHTTPSListenerArgs{ + ListenerPort: 8081, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, // 证书ID列表 + } + + // 创建appblb https监听器 + if err := appBlbClient.CreateAppHTTPSListener(blbID, createAppHTTPSListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_ip_group.go b/bce-sdk-go/examples/appblb/example_create_app_ip_group.go new file mode 100644 index 0000000..d3a74c3 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_ip_group.go @@ -0,0 +1,46 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func CreateAppIpGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + CreateAppIpGroupArgs := &appblb.CreateAppIpGroupArgs{ + Name: "test", + Desc: "test", + ClientToken: "your client token", + } + + result, err := blbClient.CreateAppIpGroup(BlbID, CreateAppIpGroupArgs) + if err != nil { + fmt.Println("create app ip group error : ", err) + return + } + + // 打印返回结果 + fmt.Println("id: ", result.Id) + fmt.Println("name: ", result.Name) +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_ip_group_backend_policy.go b/bce-sdk-go/examples/appblb/example_create_app_ip_group_backend_policy.go new file mode 100644 index 0000000..ee7436e --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_ip_group_backend_policy.go @@ -0,0 +1,50 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func CreateAppIpGroupBackendPolicy() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + CreateAppIpGroupBackendPolicyArgs := &appblb.CreateAppIpGroupBackendPolicyArgs{ + ClientToken: "your client token", + IpGroupId: "your ip group id", + Type: "TCP", + HealthCheckPort: 80, + HealthCheckTimeoutInSecond: 5, + HealthCheckIntervalInSecond: 5, + HealthCheckDownRetry: 3, + HealthCheckUpRetry: 3, + HealthCheckNormalStatus: "http_1xx|http_2xx", + HealthCheckUrlPath: "/", + UdpHealthCheckString: "", + } + + err := blbClient.CreateAppIpGroupBackendPolicy(BlbID, CreateAppIpGroupBackendPolicyArgs) + if err != nil { + fmt.Println("create app ip group backend policy error : ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_ip_group_member.go b/bce-sdk-go/examples/appblb/example_create_app_ip_group_member.go new file mode 100644 index 0000000..6565763 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_ip_group_member.go @@ -0,0 +1,47 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateAppIpGroupMember() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.CreateAppIpGroupMemberArgs{ + AppIpGroupMemberWriteOpArgs: appblb.AppIpGroupMemberWriteOpArgs{ + IpGroupId: "ip_group-4daxxxxx", // IP组ID + MemberList: []appblb.AppIpGroupMember{ + { + Ip: "127.0.0.1", // IP + Port: 80, // 端口 + Weight: 100, // 权重 + }, + }, + }, + } + //发起请求并处理返回或异常 + err = client.CreateAppIpGroupMember(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_server_group.go b/bce-sdk-go/examples/appblb/example_create_app_server_group.go new file mode 100644 index 0000000..5c6e390 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_server_group.go @@ -0,0 +1,46 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func CreateAppServerGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + CreateAppServerGroupArgs := &appblb.CreateAppServerGroupArgs{ + Name: "test_app_server_group", + Description: "test_app_server_group", + ClientToken: "test_token", + } + + result, err := blbClient.CreateAppServerGroup(BlbID, CreateAppServerGroupArgs) + if err != nil { + fmt.Println("create app server group error : ", err) + return + } + + // 打印返回结果 + fmt.Println("id: ", result.Id) + fmt.Println("name: ", result.Name) +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_server_group_port.go b/bce-sdk-go/examples/appblb/example_create_app_server_group_port.go new file mode 100644 index 0000000..9d50a35 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_server_group_port.go @@ -0,0 +1,56 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func CreateAppServerGroupPort() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + CreateAppServerGroupPortArgs := &appblb.CreateAppServerGroupPortArgs{ + ClientToken: "you client token", + SgId: "Your app server group id", + Port: 80, + Type: "TCP", + HealthCheck: "TCP", + HealthCheckPort: 80, + HealthCheckTimeoutInSecond: 5, + HealthCheckIntervalInSecond: 5, + HealthCheckDownRetry: 3, + HealthCheckUpRetry: 3, + HealthCheckNormalStatus: "http_2xx|http_3xx", + HealthCheckUrlPath: "/", + UdpHealthCheckString: "", + } + + result, err := blbClient.CreateAppServerGroupPort(BlbID, CreateAppServerGroupPortArgs) + if err != nil { + fmt.Println("create app server group port error : ", err) + return + } + + // 打印返回结果 + fmt.Println("id: ", result.Id) + fmt.Println("name: ", result.Name) +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_ssl_listener.go b/bce-sdk-go/examples/appblb/example_create_app_ssl_listener.go new file mode 100644 index 0000000..cae8672 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_ssl_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateAppSSLListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createAppSSLListenerArgs := &appblb.CreateAppSSLListenerArgs{ + ListenerPort: 8083, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, // 证书ID列表 + } + + // 创建appblb ssl监听器 + if err := appBlbClient.CreateAppSSLListener(blbID, createAppSSLListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_tcp_listener.go b/bce-sdk-go/examples/appblb/example_create_app_tcp_listener.go new file mode 100644 index 0000000..4c82cb0 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_tcp_listener.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateAppTCPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createAppTCPListenerArgs := &appblb.CreateAppTCPListenerArgs{ + ListenerPort: 80, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 创建appblb tcp监听器 + if err := appBlbClient.CreateAppTCPListener(blbID, createAppTCPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_app_udp_listener.go b/bce-sdk-go/examples/appblb/example_create_app_udp_listener.go new file mode 100644 index 0000000..6181183 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_app_udp_listener.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateAppUDPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createAppUDPListenerArgs := &appblb.CreateAppUDPListenerArgs{ + ListenerPort: 80, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 创建appblb udp监听器 + if err := appBlbClient.CreateAppUDPListener(blbID, createAppUDPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_blb_rs.go b/bce-sdk-go/examples/appblb/example_create_blb_rs.go new file mode 100644 index 0000000..c5b463c --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_blb_rs.go @@ -0,0 +1,46 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateBLBRs() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.CreateBlbRsArgs{ + BlbRsWriteOpArgs: appblb.BlbRsWriteOpArgs{ + SgId: "sg-328xxxxx", // 服务器组ID + BackendServerList: []appblb.AppBackendServer{ + { + InstanceId: "i-J54*****", // 服务器ID + Weight: 100, // 权重 + }, + }, + }, + } + //发起请求并处理返回或异常 + err = client.CreateBlbRs(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_loadbalancer.go b/bce-sdk-go/examples/appblb/example_create_loadbalancer.go new file mode 100644 index 0000000..051d180 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_loadbalancer.go @@ -0,0 +1,43 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func CreateLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + createBlbArgs := &appblb.CreateLoadBalancerArgs{ + ClientToken: "client token", // token + Name: "TestSDK-BLB", // blb名称 + VpcId: "vpc id", // VPC ID + SubnetId: "subnet id", // 子网ID + } + + response, err := BlbClient.CreateLoadBalancer(createBlbArgs) // 创建blb + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_create_policys_ip_group.go b/bce-sdk-go/examples/appblb/example_create_policys_ip_group.go new file mode 100644 index 0000000..d5c6449 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_policys_ip_group.go @@ -0,0 +1,54 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func CreatePolicysIpGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.CreatePolicysArgs{ + ListenerPort: 98, // 对应所在BLB下监听器端口号 + Type: "HTTP", // 对应所在BLB下监听器协议 + AppPolicyVos: []appblb.AppPolicy{ // 监听器绑定策略列表 + { + Description: "aa", // 策略描述 + Priority: 100, // 策略优先级 + AppIpGroupId: "ip_group-6c2xxxx9", // 策略绑定IP组标识符 + RuleList: []appblb.AppRule{ // 策略规则列表 + { + Key: "*", // 规则的类型 + Value: "*", // 通配符匹配字符串 + }, + }, + }, + }, + } + + if err := appblbClient.CreatePolicys(AppBlbID, args); err != nil { + fmt.Println("create policy with ip group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_create_policys_server_group.go b/bce-sdk-go/examples/appblb/example_create_policys_server_group.go new file mode 100644 index 0000000..20d2edd --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_create_policys_server_group.go @@ -0,0 +1,55 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func CreatePolicysServerGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.CreatePolicysArgs{ + ListenerPort: 98, // 对应所在BLB下监听器端口号 + Type: "HTTP", // 对应所在BLB下监听器协议 + AppPolicyVos: []appblb.AppPolicy{ // 监听器绑定策略列表 + { + Description: "bb", // 策略描述 + Priority: 90, // 策略优先级 + AppServerGroupId: "sg-8a8xxxx6", // 策略绑定服务器组标识符 + BackendPort: 80, // 目标端口号 + RuleList: []appblb.AppRule{ // 策略规则列表 + { + Key: "*", // 规则的类型 + Value: "*", // 通配符匹配字符串 + }, + }, + }, + }, + } + + if err := appblbClient.CreatePolicys(AppBlbID, args); err != nil { + fmt.Println("create policy with server group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_app_ip_group.go b/bce-sdk-go/examples/appblb/example_delete_app_ip_group.go new file mode 100644 index 0000000..a4f26da --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_app_ip_group.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DeleteAppIpGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + DeleteAppIpGroup := &appblb.DeleteAppIpGroupArgs{ + IpGroupId: "Your app ip group's id", + ClientToken: "Your client token", + } + + err := blbClient.DeleteAppIpGroup(BlbID, DeleteAppIpGroup) + if err != nil { + fmt.Println("delete app ip group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_app_ip_group_backend_policy.go b/bce-sdk-go/examples/appblb/example_delete_app_ip_group_backend_policy.go new file mode 100644 index 0000000..3ac3966 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_app_ip_group_backend_policy.go @@ -0,0 +1,42 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DeleteAppIpGroupBackendPolicy() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + DeleteAppIpGroupBackendPolicyArgs := &appblb.DeleteAppIpGroupBackendPolicyArgs{ + IpGroupId: "Your app ip group's id", + BackendPolicyIdList: []string{"Your backend policy's id"}, + ClientToken: "you client token", + } + + err := blbClient.DeleteAppIpGroupBackendPolicy(BlbID, DeleteAppIpGroupBackendPolicyArgs) + if err != nil { + fmt.Println("delete app ip group backend policy error : ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_app_ip_group_member.go b/bce-sdk-go/examples/appblb/example_delete_app_ip_group_member.go new file mode 100644 index 0000000..6f7a9cc --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_app_ip_group_member.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DeleteAppIpGroupMember() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.DeleteAppIpGroupMemberArgs{ + IpGroupId: "ip_group-4daxxxxx", // IP组ID + MemberIdList: []string{ + "ip_member-1cb8xxxx", // IP组成员ID + }, + } + //发起请求并处理返回或异常 + err = client.DeleteAppIpGroupMember(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_app_listeners.go b/bce-sdk-go/examples/appblb/example_delete_app_listeners.go new file mode 100644 index 0000000..5013bb1 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_app_listeners.go @@ -0,0 +1,40 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DeleteAppListeners() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.DeleteAppListenersArgs{ + PortList: []uint16{ + 8080, // 监听端口 + }, + } + //发起请求并处理返回或异常 + err = client.DeleteAppListeners(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_app_server_group.go b/bce-sdk-go/examples/appblb/example_delete_app_server_group.go new file mode 100644 index 0000000..666ff0d --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_app_server_group.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DeleteAppServerGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbId := "Your app blb's id" + deleteAppServerGroupArgs := &appblb.DeleteAppServerGroupArgs{ + SgId: "your app server group id", + ClientToken: "test_token", + } + + err := blbClient.DeleteAppServerGroup(blbId, deleteAppServerGroupArgs) + if err != nil { + fmt.Println("delete app server group error : ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_app_server_group_port.go b/bce-sdk-go/examples/appblb/example_delete_app_server_group_port.go new file mode 100644 index 0000000..cb30d9e --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_app_server_group_port.go @@ -0,0 +1,42 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DeleteAppServerGroupPort() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + DeleteAppServerGroupPortArgs := &appblb.DeleteAppServerGroupPortArgs{ + ClientToken: "you client token", + SgId: "Your app server group id", + PortIdList: []string{"Your app server group port id"}, + } + + err := blbClient.DeleteAppServerGroupPort(BlbID, DeleteAppServerGroupPortArgs) + if err != nil { + fmt.Println("delete app server group port error : ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_blb_rs.go b/bce-sdk-go/examples/appblb/example_delete_blb_rs.go new file mode 100644 index 0000000..8471cb4 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_blb_rs.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DeleteBLBRs() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.DeleteBlbRsArgs{ + SgId: "sg-328xxxxx", // 服务器组ID + BackendServerIdList: []string{ + "i-J54*****", // 服务器ID + }, + } + //发起请求并处理返回或异常 + err = client.DeleteBlbRs(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_loadbalancer.go b/bce-sdk-go/examples/appblb/example_delete_loadbalancer.go new file mode 100644 index 0000000..67d8445 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_loadbalancer.go @@ -0,0 +1,34 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DeleteLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // BLB实例ID + + err := BlbClient.DeleteLoadBalancer(BlbID) // 释放BLB实例 + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_delete_policys.go b/bce-sdk-go/examples/appblb/example_delete_policys.go new file mode 100644 index 0000000..148a300 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_delete_policys.go @@ -0,0 +1,44 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DeletePolicys() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.DeletePolicysArgs{ + Port: 98, + Type: "HTTP", + PolicyIdList: []string{ + "policy-c4bxxxx6", + }, + } + + if err := appblbClient.DeletePolicys(AppBlbID, args); err != nil { + fmt.Println("delete policy error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_all_listeners.go b/bce-sdk-go/examples/appblb/example_describe_app_all_listeners.go new file mode 100644 index 0000000..5b1907e --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_all_listeners.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// DescribeAppAllListeners 函数用于获取应用型监听器的列表 +func DescribeAppAllListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + BlbID := "your app blb id" + + client, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + args := &appblb.DescribeAppListenerArgs{} + + response, err := client.DescribeAppAllListeners(BlbID, args) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_http_listeners.go b/bce-sdk-go/examples/appblb/example_describe_app_http_listeners.go new file mode 100644 index 0000000..3e6961b --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_http_listeners.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeAppHTTPListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + + DescribeAppListenerArgs := &appblb.DescribeAppListenerArgs{ + ListenerPort: 80, // 要查询的监听器端口 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + + result, err := blbClient.DescribeAppHTTPListeners(BlbID, DescribeAppListenerArgs) + if err != nil { + fmt.Println("describe app http listeners error: ", err) + return + } + + // 打印返回结果 + for _, listener := range result.ListenerList { + fmt.Println("ListenerPort: ", listener.ListenerPort) + fmt.Println("Scheduler: ", listener.Scheduler) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_https_listeners.go b/bce-sdk-go/examples/appblb/example_describe_app_https_listeners.go new file mode 100644 index 0000000..754c9cd --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_https_listeners.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeAppHTTPSListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + DescribeAppListenerArgs := &appblb.DescribeAppListenerArgs{ + ListenerPort: 443, // 要查询的监听器端口 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + + result, err := blbClient.DescribeAppHTTPSListeners(BlbID, DescribeAppListenerArgs) + if err != nil { + fmt.Println("describe app https listeners error: ", err) + return + } + + // 打印结果 + for _, listener := range result.ListenerList { + fmt.Println("ListenerPort: ", listener.ListenerPort) + fmt.Println("Scheduler: ", listener.Scheduler) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_ip_group.go b/bce-sdk-go/examples/appblb/example_describe_app_ip_group.go new file mode 100644 index 0000000..4628c5d --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_ip_group.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeAppIpGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + + DescribeAppIpGroupArgs := &appblb.DescribeAppIpGroupArgs{ + Name: "", //名称 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + + result, err := blbClient.DescribeAppIpGroup(BlbID, DescribeAppIpGroupArgs) + if err != nil { + fmt.Println("describe app app ip group error: ", err) + return + } + + // 打印返回结果 + for _, appIpGroup := range result.AppIpGroupList { + fmt.Println("id: ", appIpGroup.Id) + fmt.Println("name: ", appIpGroup.Name) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_ip_group_member.go b/bce-sdk-go/examples/appblb/example_describe_app_ip_group_member.go new file mode 100644 index 0000000..7208899 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_ip_group_member.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeAppIpGroupMember() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.DescribeAppIpGroupMemberArgs{ + IpGroupId: "ip_group-4daxxxxx", // IP组ID + } + //发起请求并处理返回或异常 + resp, err := client.DescribeAppIpGroupMember(blbID, args) + if err != nil { + panic(err) + } + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_server_group.go b/bce-sdk-go/examples/appblb/example_describe_app_server_group.go new file mode 100644 index 0000000..00da362 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_server_group.go @@ -0,0 +1,50 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeAppServerGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + + DescribeAppServerGroupArgs := &appblb.DescribeAppServerGroupArgs{ + Name: "", // 名称 + ExactlyMatch: false, // 精确匹配 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + + result, err := blbClient.DescribeAppServerGroup(BlbID, DescribeAppServerGroupArgs) + if err != nil { + fmt.Println("describe app server group error: ", err) + return + } + + // 打印返回结果 + for _, servergroup := range result.AppServerGroupList { + fmt.Println("id: ", servergroup.Id) + fmt.Println("name: ", servergroup.Name) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_ssl_listeners.go b/bce-sdk-go/examples/appblb/example_describe_app_ssl_listeners.go new file mode 100644 index 0000000..efc1a4f --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_ssl_listeners.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// DescribeAppSSLListeners 函数用于获取应用型SSL监听器的详细信息 +func DescribeAppSSLListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + BlbID := "your app blb id" + sslListenerPort := uint16(80) + + client, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + args := &appblb.DescribeAppListenerArgs{ + ListenerPort: sslListenerPort, // SSL监听端口 + } + response, err := client.DescribeAppSSLListeners(BlbID, args) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_tcp_listeners.go b/bce-sdk-go/examples/appblb/example_describe_app_tcp_listeners.go new file mode 100644 index 0000000..03f7d51 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_tcp_listeners.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeAppTCPListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb id + describeTCPListenersArgs := &appblb.DescribeAppListenerArgs{ + ListenerPort: 53, // listener端口号 + } + + response, err := BlbClient.DescribeAppTCPListeners(BlbID, describeTCPListenersArgs) //查询TCP Listeners + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_app_udp_listeners.go b/bce-sdk-go/examples/appblb/example_describe_app_udp_listeners.go new file mode 100644 index 0000000..3e84ac0 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_app_udp_listeners.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeAppUDPListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb实例id + describeUDPListenersArgs := &appblb.DescribeAppListenerArgs{ + ListenerPort: 53, // listener端口号 + } + + response, err := BlbClient.DescribeAppUDPListeners(BlbID, describeUDPListenersArgs) //查询UDP Listeners + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_blb_rs.go b/bce-sdk-go/examples/appblb/example_describe_blb_rs.go new file mode 100644 index 0000000..7417951 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_blb_rs.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeBLBRs() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.DescribeBlbRsArgs{ + SgId: "sg-328xxxxx", // 服务器组ID + } + //发起请求并处理返回或异常 + resp, err := client.DescribeBlbRs(blbID, args) + if err != nil { + panic(err) + } + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_enterprise_security_groups.go b/bce-sdk-go/examples/appblb/example_describe_enterprise_security_groups.go new file mode 100644 index 0000000..60c5a17 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_enterprise_security_groups.go @@ -0,0 +1,44 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeEnterpriseSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + result, err := appblbClient.DescribeEnterpriseSecurityGroups(AppBlbID) + if err != nil { + fmt.Println("describe enterprise security group error: ", err) + return + } + + // 获取enterprise security group的列表信息 + for _, esg := range result.BlbEnterpriseSecurityGroups { + fmt.Println("enterpriseSecurityGroupId : ", esg.EnterpriseSecurityGroupId) + fmt.Println("enterpriseSecurityGroupName : ", esg.EnterpriseSecurityGroupName) + fmt.Println("enterpriseSecurityGroupDesc : ", esg.EnterpriseSecurityGroupDesc) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_loadbalancer_detail.go b/bce-sdk-go/examples/appblb/example_describe_loadbalancer_detail.go new file mode 100644 index 0000000..0b792c5 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_loadbalancer_detail.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeLoadBalancerDetail() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb实例ID + + response, err := BlbClient.DescribeLoadBalancerDetail(BlbID) //查询单个blb实例详情 + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_loadbalancers.go b/bce-sdk-go/examples/appblb/example_describe_loadbalancers.go new file mode 100644 index 0000000..81712a8 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_loadbalancers.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeLoadBalancers() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + describeBlbsArgs := &appblb.DescribeLoadBalancersArgs{} + + response, err := BlbClient.DescribeLoadBalancers(describeBlbsArgs) //查询blb实例列表 + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_policys_ip_group.go b/bce-sdk-go/examples/appblb/example_describe_policys_ip_group.go new file mode 100644 index 0000000..3608ac0 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_policys_ip_group.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribePolicysIpGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.DescribePolicysArgs{ + Port: 98, + Type: "HTTP", + } + + result, err := appblbClient.DescribePolicys(AppBlbID, args) + if err != nil { + fmt.Println("describe ploicy error: ", err) + return + } + + // 获取policy的列表信息 + for _, policy := range result.PolicyList { + fmt.Println("id : ", policy.Id) + fmt.Println("appIpGroupId : ", policy.AppIpGroupId) + fmt.Println("priority : ", policy.Priority) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_policys_server_group.go b/bce-sdk-go/examples/appblb/example_describe_policys_server_group.go new file mode 100644 index 0000000..8ce9c31 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_policys_server_group.go @@ -0,0 +1,50 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribePolicysServerGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.DescribePolicysArgs{ + Port: 98, + Type: "HTTP", + } + + result, err := appblbClient.DescribePolicys(AppBlbID, args) + if err != nil { + fmt.Println("describe ploicy error: ", err) + return + } + + // 获取policy的列表信息 + for _, policy := range result.PolicyList { + fmt.Println("id : ", policy.Id) + fmt.Println("appServerGroupId : ", policy.AppServerGroupId) + fmt.Println("appServerGroupName : ", policy.AppServerGroupName) + fmt.Println("priority : ", policy.Priority) + } +} diff --git a/bce-sdk-go/examples/appblb/example_describe_rs_mount.go b/bce-sdk-go/examples/appblb/example_describe_rs_mount.go new file mode 100644 index 0000000..ad41bd6 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_rs_mount.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeRsMount() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + sgID := "sg-328xxxxx" //服务器组ID + //发起请求并处理返回或异常 + resp, err := client.DescribeRsMount(blbID, sgID) + if err != nil { + panic(err) + } + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_rs_unmount.go b/bce-sdk-go/examples/appblb/example_describe_rs_unmount.go new file mode 100644 index 0000000..49a9249 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_rs_unmount.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func DescribeRsUnMount() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + sgID := "sg-328xxxxx" //服务器组ID + //发起请求并处理返回或异常 + resp, err := client.DescribeRsUnMount(blbID, sgID) + if err != nil { + panic(err) + } + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/appblb/example_describe_security_groups.go b/bce-sdk-go/examples/appblb/example_describe_security_groups.go new file mode 100644 index 0000000..fa43cb2 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_describe_security_groups.go @@ -0,0 +1,45 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + result, err := appblbClient.DescribeSecurityGroups(AppBlbID) + if err != nil { + fmt.Println("describe security group error: ", err) + return + } + + // 获取security group的列表信息 + for _, sg := range result.BlbSecurityGroups { + fmt.Println("securityGroupId : ", sg.SecurityGroupId) + fmt.Println("securityGroupName : ", sg.SecurityGroupName) + fmt.Println("securityGroupDesc : ", sg.SecurityGroupDesc) + fmt.Println("vpcName : ", sg.VpcName) + } +} diff --git a/bce-sdk-go/examples/appblb/example_unbind_enterprise_security_groups.go b/bce-sdk-go/examples/appblb/example_unbind_enterprise_security_groups.go new file mode 100644 index 0000000..551fa84 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_unbind_enterprise_security_groups.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UnbindEnterpriseSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.UpdateEnterpriseSecurityGroupsArgs{ + // 设置要解绑的 enterprise security group 列表 + EnterpriseSecurityGroupIds: []string{"esg-djr0dtxxxxnx"}, // 替换为需要解绑的 enterprise security group 列表 + } + + if err := appblbClient.UnbindEnterpriseSecurityGroups(AppBlbID, args); err != nil { + fmt.Println("unbind enterprise security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_unbind_security_groups.go b/bce-sdk-go/examples/appblb/example_unbind_security_groups.go new file mode 100644 index 0000000..ad4cb2b --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_unbind_security_groups.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UnbindSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appblbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + AppBlbID := "Your appblb's id" + + args := &appblb.UpdateSecurityGroupsArgs{ + // 设置要解绑的 security group 列表 + SecurityGroupIds: []string{"g-wrukksxxxxz5"}, // 替换为需要解绑的 security group 列表 + } + + if err := appblbClient.UnbindSecurityGroups(AppBlbID, args); err != nil { + fmt.Println("unbind security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_http_listener.go b/bce-sdk-go/examples/appblb/example_update_app_http_listener.go new file mode 100644 index 0000000..d37d74e --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_http_listener.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateAppHTTPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateAppHTTPListenerArgs := &appblb.UpdateAppHTTPListenerArgs{ + ListenerPort: 8080, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 更新appblb http监听器 + if err := appBlbClient.UpdateAppHTTPListener(blbID, updateAppHTTPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_https_listener.go b/bce-sdk-go/examples/appblb/example_update_app_https_listener.go new file mode 100644 index 0000000..b77e3ce --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_https_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateAppHTTPSListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateAppHTTPSListenerArgs := &appblb.UpdateAppHTTPSListenerArgs{ + ListenerPort: 8081, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, // 证书ID列表 + } + + // 更新appblb https监听器 + if err := appBlbClient.UpdateAppHTTPSListener(blbID, updateAppHTTPSListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_ip_group_backend_policy.go b/bce-sdk-go/examples/appblb/example_update_app_ip_group_backend_policy.go new file mode 100644 index 0000000..9c884d2 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_ip_group_backend_policy.go @@ -0,0 +1,50 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UpdateAppIpGroupBackendPolicy() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + UpdateAppIpGroupBackendPolicyArgs := &appblb.UpdateAppIpGroupBackendPolicyArgs{ + ClientToken: "your client token", + IpGroupId: "your ip group id", + Id: "your backend policy id", + HealthCheckPort: 80, + HealthCheckTimeoutInSecond: 5, + HealthCheckIntervalInSecond: 5, + HealthCheckDownRetry: 3, + HealthCheckUpRetry: 3, + HealthCheckNormalStatus: "http_1xx|http_2xx", + HealthCheckUrlPath: "/", + UdpHealthCheckString: "", + } + + err := blbClient.UpdateAppIpGroupBackendPolicy(BlbID, UpdateAppIpGroupBackendPolicyArgs) + if err != nil { + fmt.Println("update app ip group backend policy error : ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_ip_group_member.go b/bce-sdk-go/examples/appblb/example_update_app_ip_group_member.go new file mode 100644 index 0000000..998bac5 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_ip_group_member.go @@ -0,0 +1,47 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateAppIpGroupMember() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.UpdateAppIpGroupMemberArgs{ + AppIpGroupMemberWriteOpArgs: appblb.AppIpGroupMemberWriteOpArgs{ + IpGroupId: "ip_group-4dadxxxx", // IP组ID + MemberList: []appblb.AppIpGroupMember{ + { + MemberId: "ip_member-1cb8xxxx", // IP成员ID + Port: 80, // 端口 + Weight: 100, // 权重 + }, + }, + }, + } + //发起请求并处理返回或异常 + err = client.UpdateAppIpGroupMember(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_server_group.go b/bce-sdk-go/examples/appblb/example_update_app_server_group.go new file mode 100644 index 0000000..9973f24 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_server_group.go @@ -0,0 +1,43 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UpdateAppServerGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + UpdateAppServerGroupArgs := &appblb.UpdateAppServerGroupArgs{ + SgId: "Your app server group's id", + Name: "Your app server group's name", + Description: "Your app server group's description", + ClientToken: "Your client token", + } + + err := blbClient.UpdateAppServerGroup(BlbID, UpdateAppServerGroupArgs) + if err != nil { + fmt.Println("update app server group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_server_group_port.go b/bce-sdk-go/examples/appblb/example_update_app_server_group_port.go new file mode 100644 index 0000000..bd77755 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_server_group_port.go @@ -0,0 +1,51 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UpdateAppServerGroupPort() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + UpdateAppServerGroupPortArgs := &appblb.UpdateAppServerGroupPortArgs{ + ClientToken: "you client token", + SgId: "Your app server group id", + PortId: "port Id", + HealthCheck: "TCP", + HealthCheckPort: 80, + HealthCheckTimeoutInSecond: 5, + HealthCheckIntervalInSecond: 5, + HealthCheckDownRetry: 3, + HealthCheckUpRetry: 3, + HealthCheckNormalStatus: "http_1xx|http_2xx", + HealthCheckUrlPath: "/", + UdpHealthCheckString: "", + } + + err := blbClient.UpdateAppServerGroupPort(BlbID, UpdateAppServerGroupPortArgs) + if err != nil { + fmt.Println("update app server group port error : ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_ssl_listener.go b/bce-sdk-go/examples/appblb/example_update_app_ssl_listener.go new file mode 100644 index 0000000..2458d2f --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_ssl_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateAppSSLListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateAppSSLListenerArgs := &appblb.UpdateAppSSLListenerArgs{ + ListenerPort: 8082, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, // 证书ID列表 + } + + // 更新appblb ssl监听器 + if err := appBlbClient.UpdateAppSSLListener(blbID, updateAppSSLListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_tcp_listener.go b/bce-sdk-go/examples/appblb/example_update_app_tcp_listener.go new file mode 100644 index 0000000..8818f8a --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_tcp_listener.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateAppTCPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateAppTCPListenerArgs := &appblb.UpdateAppTCPListenerArgs{ + UpdateAppListenerArgs: appblb.UpdateAppListenerArgs{ + ListenerPort: 80, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + }, + } + + // 更新appblb tcp监听器 + if err := appBlbClient.UpdateAppTCPListener(blbID, updateAppTCPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_app_udp_listener.go b/bce-sdk-go/examples/appblb/example_update_app_udp_listener.go new file mode 100644 index 0000000..bdd9fad --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_app_udp_listener.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateAppUDPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + appBlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateAppUDPListenerArgs := &appblb.UpdateAppUDPListenerArgs{ + UpdateAppListenerArgs: appblb.UpdateAppListenerArgs{ + ListenerPort: 80, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + }, + } + + // 更新appblb udp监听器 + if err := appBlbClient.UpdateAppUDPListener(blbID, updateAppUDPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_blb_rs.go b/bce-sdk-go/examples/appblb/example_update_blb_rs.go new file mode 100644 index 0000000..75f2394 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_blb_rs.go @@ -0,0 +1,46 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateBLBRs() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := appblb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &appblb.UpdateBlbRsArgs{ + BlbRsWriteOpArgs: appblb.BlbRsWriteOpArgs{ + SgId: "sg-328xxxxx", // 服务器组ID + BackendServerList: []appblb.AppBackendServer{ + { + InstanceId: "i-J54*****", // 服务器ID + Weight: 50, // 权重 + }, + }, + }, + } + //发起请求并处理返回或异常 + err = client.UpdateBlbRs(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_ip_group.go b/bce-sdk-go/examples/appblb/example_update_ip_group.go new file mode 100644 index 0000000..5b33f75 --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_ip_group.go @@ -0,0 +1,43 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UpdateAppIpGroup() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your app blb's id" + UpdateAppIpGroupArgs := &appblb.UpdateAppIpGroupArgs{ + IpGroupId: "Your app ip group's id", + Name: "Your app app ip group's name", + Desc: "Your app app ip group's description", + ClientToken: "Your client token", + } + + err := blbClient.UpdateAppIpGroup(BlbID, UpdateAppIpGroupArgs) + if err != nil { + fmt.Println("update app ip group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/appblb/example_update_loadbalancer.go b/bce-sdk-go/examples/appblb/example_update_loadbalancer.go new file mode 100644 index 0000000..a957e6f --- /dev/null +++ b/bce-sdk-go/examples/appblb/example_update_loadbalancer.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 appblbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/appblb" +) + +func UpdateLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := appblb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb ID + updateBlbArgs := &appblb.UpdateLoadBalancerArgs{ + ClientToken: "client token", // token + Name: "Test-BLB", // blb名称 + Description: "blb description", // blb描述 + } + + err := BlbClient.UpdateLoadBalancer(BlbID, updateBlbArgs) // 更新blb + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_authorize_securitygrouprule.go b/bce-sdk-go/examples/bcc/securitygroup/example_authorize_securitygrouprule.go new file mode 100644 index 0000000..f56e6ac --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_authorize_securitygrouprule.go @@ -0,0 +1,38 @@ +package bccsgexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bcc" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// AuthorizeSecurityGroupRule - authorize a security group rule +// +// PARAMS: +// - securityGroupId: the specific securityGroup ID +// - args: the arguments to authorize a security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error + +func AuthorizeSecurityGroupRule() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建bcc client + args := &api.AuthorizeSecurityGroupArgs{ + Rule: &api.SecurityGroupRuleModel{ + Remark: "备注", // 规则备注 + Protocol: "tcp", // 协议 + PortRange: "1-65535", // 端口范围 + Direction: "ingress", // 方向 + SourceIp: "", // 源IP + SourceGroupId: "", // 源SGID + }, + } + err := client.AuthorizeSecurityGroupRule("Your SecurityGroupRuleID", args) // 授权安全组规则 + if err != nil { + panic(err) + } + fmt.Print("AuthorizeSecurityGroupRule success!") +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_create_securitygroup.go b/bce-sdk-go/examples/bcc/securitygroup/example_create_securitygroup.go new file mode 100644 index 0000000..e391261 --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_create_securitygroup.go @@ -0,0 +1,54 @@ +package bccsgexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/bcc" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// securityGroup sdk +// CreateSecurityGroup - create a security group +// +// PARAMS: +// - args: the arguments to create security group +// +// RETURNS: +// - *api.CreateSecurityGroupResult: the result of create security group +// - error: nil if success otherwise the specific error +// +// CreateSecurityGroup 创建安全组 +func CreateSecurityGroup() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建BCC Client + args := &api.CreateSecurityGroupArgs{ + Name: "testSecurityGroup", // 创建的SG名称 + VpcId: "Your VPCID", // 创建的SG所属VPCID + Desc: "vpc1 sdk test create security group", // 创建的SG描述 + Rules: []api.SecurityGroupRuleModel{ + { + Remark: "备注", // 规则备注 + Protocol: "tcp", // 协议 + PortRange: "1-65535", // 端口范围 + Direction: "ingress", // 方向 + SourceIp: "", // 源IP + SourceGroupId: "", // 源SGID + }, + }, + Tags: []model.TagModel{ + { + TagKey: "tagKey", // 标签key + TagValue: "tagValue", // 标签value + }, + }, + } + + response, err := client.CreateSecurityGroup(args) // 创建SG + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_delete_securitygroup.go b/bce-sdk-go/examples/bcc/securitygroup/example_delete_securitygroup.go new file mode 100644 index 0000000..b98872d --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_delete_securitygroup.go @@ -0,0 +1,25 @@ +package bccsgexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bcc" +) + +// DeleteSecurityGroup - delete a security group +// +// PARAMS: +// - securityGroupId: the specific securityGroup ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteSecurityGroup() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建BCC Client + err := client.DeleteSecurityGroup("Your SecurityGroupID") // 删除安全组 + if err != nil { + panic(err) + } + fmt.Print("Delete SecurityGroup Success!") +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_delete_securitygrouprule.go b/bce-sdk-go/examples/bcc/securitygroup/example_delete_securitygrouprule.go new file mode 100644 index 0000000..cfd0435 --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_delete_securitygrouprule.go @@ -0,0 +1,29 @@ +package bccsgexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bcc" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// DeleteSecurityGroupRule - delete a security group rule +// +// PARAMS: +// - securityGroupRuleId: the id of the specific security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteSecurityGroupRule() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建bcc client + args := &api.DeleteSecurityGroupRuleArgs{ // 创建参数 + SecurityGroupRuleId: "Your SecurityGroupRuleID", // 指定要删除的规则id + } + err := client.DeleteSecurityGroupRule(args) // 删除安全组规则 + if err != nil { + panic(err) + } + fmt.Printf("Delete SecurityGroupRule %s success\n", args.SecurityGroupRuleId) +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_get_securitygrouplist.go b/bce-sdk-go/examples/bcc/securitygroup/example_get_securitygrouplist.go new file mode 100644 index 0000000..b091e86 --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_get_securitygrouplist.go @@ -0,0 +1,32 @@ +package bccsgexamples + +import ( + "encoding/json" + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bcc" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// ListSecurityGroup - list all security group +// +// PARAMS: +// - args: the arguments to list all security group +// +// RETURNS: +// - *api.ListSecurityGroupResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func ListSecurityGroup() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建bcc client + queryArgs := &api.ListSecurityGroupArgs{ + VpcId: "Your VPCID", // vpc id + } + result, err := client.ListSecurityGroup(queryArgs) // 查询所有的普通安全组 + if err != nil { + panic(err) + } + r, _ := json.Marshal(result) + fmt.Println(string(r)) +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_revoke_securitygrouprule.go b/bce-sdk-go/examples/bcc/securitygroup/example_revoke_securitygrouprule.go new file mode 100644 index 0000000..24c8b06 --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_revoke_securitygrouprule.go @@ -0,0 +1,37 @@ +package bccsgexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bcc" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// RevokeSecurityGroupRule - revoke a security group rule +// +// PARAMS: +// - securityGroupId: the specific securityGroup ID +// - args: the arguments to revoke security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RevokeSecurityGroupRule() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建BCC Client + args := &api.RevokeSecurityGroupArgs{ + Rule: &api.SecurityGroupRuleModel{ + Remark: "备注", // 规则备注 + Protocol: "tcp", // 协议 + PortRange: "1-65535", // 端口范围 + Direction: "ingress", // 方向 + SourceIp: "", // 源IP + SourceGroupId: "", // 源SGID + }, + } + err := client.RevokeSecurityGroupRule("Your SecurityGroupID", args) + if err != nil { + panic(err) + } + fmt.Print("RevokeSecurityGroupRule Success!\n") +} diff --git a/bce-sdk-go/examples/bcc/securitygroup/example_update_securitygrouprule.go b/bce-sdk-go/examples/bcc/securitygroup/example_update_securitygrouprule.go new file mode 100644 index 0000000..8d9e48d --- /dev/null +++ b/bce-sdk-go/examples/bcc/securitygroup/example_update_securitygrouprule.go @@ -0,0 +1,31 @@ +package bccsgexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bcc" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// UpdateSecurityGroupRule - update security group rule with the specific parameters +// +// PARAMS: +// - args: the arguments to update the specific security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateSecurityGroupRule() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := bcc.NewClient(ak, sk, endpoint) // 创建bcc client + remark := "test" // 描述备注 + args := &api.UpdateSecurityGroupRuleArgs{ + SecurityGroupRuleId: "Your SecurityGroupRuleId", // 安全组规则ID + Remark: &remark, + } + err := client.UpdateSecurityGroupRule(args) // 更新安全组规则 + if err != nil { + panic(err) + } + fmt.Print("The security group rule has been updated successfully.\n") +} diff --git a/bce-sdk-go/examples/blb/example_add_backend_servers.go b/bce-sdk-go/examples/blb/example_add_backend_servers.go new file mode 100644 index 0000000..1f82d28 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_add_backend_servers.go @@ -0,0 +1,43 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func AddBackendServers() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := blb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &blb.AddBackendServersArgs{ + BackendServerList: []blb.BackendServerModel{ + { + InstanceId: "i-J54*****", //服务器ID + Weight: 100, //权重 + }, + }, + } + //发起请求并处理返回或异常 + err = client.AddBackendServers(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_bind_enterprise_security_groups.go b/bce-sdk-go/examples/blb/example_bind_enterprise_security_groups.go new file mode 100644 index 0000000..53b43a9 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_bind_enterprise_security_groups.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func BindEnterpriseSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + args := &blb.UpdateEnterpriseSecurityGroupsArgs{ + // 设置要绑定的 enterprise security group 列表 + EnterpriseSecurityGroupIds: []string{"esg-djr0dtxxxxnx"}, // 替换为需要绑定的 enterprise security group 列表 + } + + if err := blbClient.BindEnterpriseSecurityGroups(BlbID, args); err != nil { + fmt.Println("bind enterprise security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/blb/example_bind_security_groups.go b/bce-sdk-go/examples/blb/example_bind_security_groups.go new file mode 100644 index 0000000..04a59c5 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_bind_security_groups.go @@ -0,0 +1,42 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func BindSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + args := &blb.UpdateSecurityGroupsArgs{ + // 设置要绑定的 security group 列表 + SecurityGroupIds: []string{"Your sg's id"}, // 替换为需要绑定的 security group 列表 + } + + if err := blbClient.BindSecurityGroups(BlbID, args); err != nil { + fmt.Println("bind security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/blb/example_create_http_listenere.go b/bce-sdk-go/examples/blb/example_create_http_listenere.go new file mode 100644 index 0000000..6a96b54 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_create_http_listenere.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateHTTPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createHTTPListenerArgs := &blb.CreateHTTPListenerArgs{ + ListenerPort: 8080, // 监听端口 + BackendPort: 8080, // 后端端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 创建blb http监听器 + if err := blbClient.CreateHTTPListener(blbID, createHTTPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_create_https_listener.go b/bce-sdk-go/examples/blb/example_create_https_listener.go new file mode 100644 index 0000000..0c3805a --- /dev/null +++ b/bce-sdk-go/examples/blb/example_create_https_listener.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateHTTPSListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createHTTPSListenerArgs := &blb.CreateHTTPSListenerArgs{ + ListenerPort: 8081, // 监听端口 + BackendPort: 8081, // 后端端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, // 证书ID列表 + } + + // 创建blb https监听器 + if err := blbClient.CreateHTTPSListener(blbID, createHTTPSListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_create_loadbalancer.go b/bce-sdk-go/examples/blb/example_create_loadbalancer.go new file mode 100644 index 0000000..b107b2f --- /dev/null +++ b/bce-sdk-go/examples/blb/example_create_loadbalancer.go @@ -0,0 +1,43 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + createBlbArgs := &blb.CreateLoadBalancerArgs{ + ClientToken: "client token", // token + Name: "TestSDK-BLB", // blb名称 + VpcId: "vpc id", // VPC ID + SubnetId: "subnet id", // 子网ID + } + + response, err := BlbClient.CreateLoadBalancer(createBlbArgs) // 创建blb + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/blb/example_create_ssl_listener.go b/bce-sdk-go/examples/blb/example_create_ssl_listener.go new file mode 100644 index 0000000..314285b --- /dev/null +++ b/bce-sdk-go/examples/blb/example_create_ssl_listener.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateSSLListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createSSLListenerArgs := &blb.CreateSSLListenerArgs{ + ListenerPort: 8082, // 监听端口 + BackendPort: 8082, // 后端端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, //证书ID列表 + } + + // 创建blb ssl监听器 + if err := blbClient.CreateSSLListener(blbID, createSSLListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_create_tcp_listener.go b/bce-sdk-go/examples/blb/example_create_tcp_listener.go new file mode 100644 index 0000000..eec3737 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_create_tcp_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateTCPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createTCPListenerArgs := &blb.CreateTCPListenerArgs{ + ListenerPort: 80, // 监听端口 + BackendPort: 80, // 后端端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 创建blb tcp监听器 + if err := blbClient.CreateTCPListener(blbID, createTCPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_create_udp_listener.go b/bce-sdk-go/examples/blb/example_create_udp_listener.go new file mode 100644 index 0000000..7799247 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_create_udp_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateUDPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + createUDPListenerArgs := &blb.CreateUDPListenerArgs{ + ListenerPort: 53, // 监听端口 + BackendPort: 53, // 后端端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 创建blb udp监听器 + if err := blbClient.CreateUDPListener(blbID, createUDPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_delete_listeners.go b/bce-sdk-go/examples/blb/example_delete_listeners.go new file mode 100644 index 0000000..9a1cc3e --- /dev/null +++ b/bce-sdk-go/examples/blb/example_delete_listeners.go @@ -0,0 +1,40 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DeleteListeners() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := blb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &blb.DeleteListenersArgs{ + PortList: []uint16{ + 8080, // 监听端口 + }, + } + //发起请求并处理返回或异常 + err = client.DeleteListeners(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_delete_loadbalancer.go b/bce-sdk-go/examples/blb/example_delete_loadbalancer.go new file mode 100644 index 0000000..acc669d --- /dev/null +++ b/bce-sdk-go/examples/blb/example_delete_loadbalancer.go @@ -0,0 +1,34 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DeleteLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb实例ID + + err := BlbClient.DeleteLoadBalancer(BlbID) // 释放BLB实例 + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_describe_all_listeners.go b/bce-sdk-go/examples/blb/example_describe_all_listeners.go new file mode 100644 index 0000000..a5428a2 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_all_listeners.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// DescribeAllListeners 函数用于获取指定BlbID下所有监听器的信息 +func DescribeAllListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + BlbID := "your blb id" + + client, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + args := &blb.DescribeListenerArgs{} + + response, err := client.DescribeAllListeners(BlbID, args) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/blb/example_describe_backend_servers.go b/bce-sdk-go/examples/blb/example_describe_backend_servers.go new file mode 100644 index 0000000..9756e81 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_backend_servers.go @@ -0,0 +1,35 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeBackendServers() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" //LB实例ID + args := &blb.DescribeBackendServersArgs{} + resp, err := client.DescribeBackendServers(blbID, args) + if err != nil { + panic(err) + } + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/blb/example_describe_enterprise_security_groups.go b/bce-sdk-go/examples/blb/example_describe_enterprise_security_groups.go new file mode 100644 index 0000000..04fedc9 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_enterprise_security_groups.go @@ -0,0 +1,44 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeEnterpriseSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + result, err := blbClient.DescribeEnterpriseSecurityGroups(BlbID) + if err != nil { + fmt.Println("describe enterprise security group error: ", err) + return + } + + // 获取enterprise security group的列表信息 + for _, esg := range result.BlbEnterpriseSecurityGroups { + fmt.Println("enterpriseSecurityGroupId : ", esg.EnterpriseSecurityGroupId) + fmt.Println("enterpriseSecurityGroupName : ", esg.EnterpriseSecurityGroupName) + fmt.Println("enterpriseSecurityGroupDesc : ", esg.EnterpriseSecurityGroupDesc) + } +} diff --git a/bce-sdk-go/examples/blb/example_describe_health_status.go b/bce-sdk-go/examples/blb/example_describe_health_status.go new file mode 100644 index 0000000..57737cc --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_health_status.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeHealthStatus() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := blb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + blbID := "Your BlbID" //LB实例ID + args := &blb.DescribeHealthStatusArgs{ + ListenerPort: 80, //监听端口 + } + //发起请求并处理返回或异常 + resp, err := client.DescribeHealthStatus(blbID, args) + if err != nil { + panic(err) + } + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/blb/example_describe_http_listeners.go b/bce-sdk-go/examples/blb/example_describe_http_listeners.go new file mode 100644 index 0000000..df3601e --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_http_listeners.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeHTTPListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + DescribeListenerArgs := &blb.DescribeListenerArgs{ + ListenerPort: 80, // 要查询的监听器端口 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + + result, err := blbClient.DescribeHTTPListeners(BlbID, DescribeListenerArgs) + if err != nil { + fmt.Println("describe http listeners error: ", err) + return + } + + // 获取listener的列表信息 + for _, listener := range result.ListenerList { + fmt.Println("ListenerPort: ", listener.ListenerPort) + fmt.Println("Scheduler: ", listener.Scheduler) + } +} diff --git a/bce-sdk-go/examples/blb/example_describe_https_listeners.go b/bce-sdk-go/examples/blb/example_describe_https_listeners.go new file mode 100644 index 0000000..599fd81 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_https_listeners.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeHTTPSListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + DescribeListenerArgs := &blb.DescribeListenerArgs{ + ListenerPort: 80, // 要查询的监听器端口 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + + result, err := blbClient.DescribeHTTPSListeners(BlbID, DescribeListenerArgs) + if err != nil { + fmt.Println("describe https listeners error: ", err) + return + } + + // 获取listener的列表信息 + for _, listener := range result.ListenerList { + fmt.Println("ListenerPort: ", listener.ListenerPort) + fmt.Println("Scheduler: ", listener.Scheduler) + } +} diff --git a/bce-sdk-go/examples/blb/example_describe_loadbalancer_detail.go b/bce-sdk-go/examples/blb/example_describe_loadbalancer_detail.go new file mode 100644 index 0000000..e93da90 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_loadbalancer_detail.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeLoadBalancerDetail() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" //blb实例ID + + response, err := BlbClient.DescribeLoadBalancerDetail(BlbID) //查询单个blb实例详情 + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/blb/example_describe_loadbalancers.go b/bce-sdk-go/examples/blb/example_describe_loadbalancers.go new file mode 100644 index 0000000..5c5701b --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_loadbalancers.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeLoadBalancers() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + describeBlbsArgs := &blb.DescribeLoadBalancersArgs{} + + response, err := BlbClient.DescribeLoadBalancers(describeBlbsArgs) //查询blb实例列表 + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/blb/example_describe_security_groups.go b/bce-sdk-go/examples/blb/example_describe_security_groups.go new file mode 100644 index 0000000..f79047c --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_security_groups.go @@ -0,0 +1,45 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func DescribeSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + result, err := blbClient.DescribeSecurityGroups(BlbID) + if err != nil { + fmt.Println("describe security group error: ", err) + return + } + + // 获取security group的列表信息 + for _, sg := range result.BlbSecurityGroups { + fmt.Println("securityGroupId : ", sg.SecurityGroupId) + fmt.Println("securityGroupName : ", sg.SecurityGroupName) + fmt.Println("securityGroupDesc : ", sg.SecurityGroupDesc) + fmt.Println("vpcName : ", sg.VpcName) + } +} diff --git a/bce-sdk-go/examples/blb/example_describe_ssl_listeners.go b/bce-sdk-go/examples/blb/example_describe_ssl_listeners.go new file mode 100644 index 0000000..1b149ed --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_ssl_listeners.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// DescribeSSLListeners 函数用于获取指定负载均衡实例的SSL监听列表 +func DescribeSSLListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "blb.bj.baidubce.com" + BlbID := "your blb id" + sslListenerPort := uint16(80) + + client, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + args := &blb.DescribeListenerArgs{ + ListenerPort: sslListenerPort, // SSL监听端口 + } + response, err := client.DescribeSSLListeners(BlbID, args) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/blb/example_describe_tcp_listeners.go b/bce-sdk-go/examples/blb/example_describe_tcp_listeners.go new file mode 100644 index 0000000..4b4cde7 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_tcp_listeners.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeTCPListeners() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbId := "blb id" + args := &blb.DescribeListenerArgs{ + ListenerPort: 80, + } + res, err := client.DescribeTCPListeners(blbId, args) // 获取listener详情 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/blb/example_describe_udp_listeners.go b/bce-sdk-go/examples/blb/example_describe_udp_listeners.go new file mode 100644 index 0000000..791e835 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_describe_udp_listeners.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeUDPListeners() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" + describeUDPListenersArgs := &blb.DescribeListenerArgs{ + ListenerPort: 53, // listener端口号 + } + + response, err := BlbClient.DescribeUDPListeners(BlbID, describeUDPListenersArgs) //查询UDP Listeners + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/blb/example_remove_backend_servers.go b/bce-sdk-go/examples/blb/example_remove_backend_servers.go new file mode 100644 index 0000000..4f08611 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_remove_backend_servers.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import "github.com/baidubce/bce-sdk-go/services/blb" + +func RemoveBackendServers() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := blb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + + blbID := "Your BlbID" //LB实例ID + args := &blb.RemoveBackendServersArgs{ + BackendServerList: []string{ + "i-J54*****", // 服务器ID + }, + } + err = client.RemoveBackendServers(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_unbind_enterprise_security_groups.go b/bce-sdk-go/examples/blb/example_unbind_enterprise_security_groups.go new file mode 100644 index 0000000..7b6f1e6 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_unbind_enterprise_security_groups.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 +func UnbindEnterpriseSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + args := &blb.UpdateEnterpriseSecurityGroupsArgs{ + // 设置要解绑的 enterprise security group 列表 + EnterpriseSecurityGroupIds: []string{"esg-djr0dtxxxxnx"}, // 替换为需要解绑的 enterprise security group 列表 + } + + if err := blbClient.UnbindEnterpriseSecurityGroups(BlbID, args); err != nil { + fmt.Println("unbind enterprise security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/blb/example_unbind_security_groups.go b/bce-sdk-go/examples/blb/example_unbind_security_groups.go new file mode 100644 index 0000000..0ce333d --- /dev/null +++ b/bce-sdk-go/examples/blb/example_unbind_security_groups.go @@ -0,0 +1,42 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UnbindSecurityGroups() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "Your blb's id" + + args := &blb.UpdateSecurityGroupsArgs{ + // 设置要解绑的 security group 列表 + SecurityGroupIds: []string{"Your sg's id"}, // 替换为需要解绑的 security group 列表 + } + + if err := blbClient.UnbindSecurityGroups(BlbID, args); err != nil { + fmt.Println("unbind security group error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/blb/example_update_backend_servers.go b/bce-sdk-go/examples/blb/example_update_backend_servers.go new file mode 100644 index 0000000..50f5dc4 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_backend_servers.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import "github.com/baidubce/bce-sdk-go/services/blb" + +func UpdateBackendServers() { + //设置您的ak、sk和要访问的地域 + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + client, err := blb.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + panic(err) + } + + blbID := "Your BlbID" //LB实例ID + args := &blb.UpdateBackendServersArgs{ + BackendServerList: []blb.BackendServerModel{ + { + InstanceId: "i-J54*****", // 服务器ID + Weight: 50, // 权重 + }, + }, + } + err = client.UpdateBackendServers(blbID, args) + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_http_listener.go b/bce-sdk-go/examples/blb/example_update_http_listener.go new file mode 100644 index 0000000..ce85456 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_http_listener.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateHTTPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateHTTPListenerArgs := &blb.UpdateHTTPListenerArgs{ + ListenerPort: 8080, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 更新blb http监听器 + if err := blbClient.UpdateHTTPListener(blbID, updateHTTPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_https_listener.go b/bce-sdk-go/examples/blb/example_update_https_listener.go new file mode 100644 index 0000000..70950ee --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_https_listener.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateHTTPSListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateHTTPSListenerArgs := &blb.UpdateHTTPSListenerArgs{ + ListenerPort: 8081, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, //证书ID列表 + } + + // 更新blb https监听器 + if err := blbClient.UpdateHTTPSListener(blbID, updateHTTPSListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_loadbalancer.go b/bce-sdk-go/examples/blb/example_update_loadbalancer.go new file mode 100644 index 0000000..71f6e7b --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_loadbalancer.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb ID + updateBlbArgs := &blb.UpdateLoadBalancerArgs{ + ClientToken: "client token", // token + Name: "Test-BLB", // blb名称 + Description: "blb description", // blb描述 + } + + err := BlbClient.UpdateLoadBalancer(BlbID, updateBlbArgs) // 更新blb + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_loadbalancer_acl.go b/bce-sdk-go/examples/blb/example_update_loadbalancer_acl.go new file mode 100644 index 0000000..0142f37 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_loadbalancer_acl.go @@ -0,0 +1,41 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateLoadBalancerAcl() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + BlbID := "blb id" // blb实例ID + supportAcl := new(bool) // 是否支持ACL + *supportAcl = true + + updateBlbAclArgs := &blb.UpdateLoadBalancerAclArgs{ + ClientToken: "client token", // token + SupportAcl: supportAcl, // 是否支持ACL + } + + err := BlbClient.UpdateLoadBalancerAcl(BlbID, updateBlbAclArgs) // 修改blb Acl开关 + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_ssl_listener.go b/bce-sdk-go/examples/blb/example_update_ssl_listener.go new file mode 100644 index 0000000..b56a08b --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_ssl_listener.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateSSLListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateSSLListenerArgs := &blb.UpdateSSLListenerArgs{ + ListenerPort: 8082, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + CertIds: []string{"cert-xxxxxxxxxxxx"}, //证书ID列表 + } + + // 更新blb ssl监听器 + if err := blbClient.UpdateSSLListener(blbID, updateSSLListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_tcp_listener.go b/bce-sdk-go/examples/blb/example_update_tcp_listener.go new file mode 100644 index 0000000..414bb77 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_tcp_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateTCPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateTCPListenerArgs := &blb.UpdateTCPListenerArgs{ + ListenerPort: 80, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 更新blb tcp监听器 + if err := blbClient.UpdateTCPListener(blbID, updateTCPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/blb/example_update_udp_listener.go b/bce-sdk-go/examples/blb/example_update_udp_listener.go new file mode 100644 index 0000000..75af853 --- /dev/null +++ b/bce-sdk-go/examples/blb/example_update_udp_listener.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 blbexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func UpdateUDPListener() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + blbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + blbID := "Your BlbID" // blb实例ID + updateUDPListenerArgs := &blb.UpdateUDPListenerArgs{ + ListenerPort: 53, // 监听端口 + Scheduler: "RoundRobin", // 调度算法 + } + + // 更新blb udp监听器 + if err := blbClient.UpdateUDPListener(blbID, updateUDPListenerArgs); err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/csn/example_attach_instance.go b/bce-sdk-go/examples/csn/example_attach_instance.go new file mode 100644 index 0000000..edd7027 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_attach_instance.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.AttachInstanceRequest{ + InstanceType: "vpc", // 加载的实例类型,取值 [ vpc | channel | bec_vpc ],分别表示私有网络、专线通道、边缘网络 + InstanceId: "Your vpcId", // 加载的实例ID + InstanceRegion: "bj", // 加载的实例所属的region + InstanceAccountId: nil, // 跨账号加载网络实例场景下,网络实例所属账号的ID + } + if err = client.AttachInstance("Your csnId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to attach instance, err: %v.\n", err) + return + } + fmt.Println("Successfully attached instance.") +} diff --git a/bce-sdk-go/examples/csn/example_bind_csn_bp.go b/bce-sdk-go/examples/csn/example_bind_csn_bp.go new file mode 100644 index 0000000..d6d1a57 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_bind_csn_bp.go @@ -0,0 +1,24 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func BindCsnBp() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.BindCsnBpRequest{ + CsnId: "csnId", + } + if err = client.BindCsnBp("csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to bind Csn Bp, err: %v.\n", err) + return + } + fmt.Println("Successfully bind csn bp.") +} diff --git a/bce-sdk-go/examples/csn/example_create_association.go b/bce-sdk-go/examples/csn/example_create_association.go new file mode 100644 index 0000000..67b09bb --- /dev/null +++ b/bce-sdk-go/examples/csn/example_create_association.go @@ -0,0 +1,26 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreateAssociation() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + description := "csn_test description" + request := &csn.CreateAssociationRequest{ + Name: "attachId", + Description: &description, + } + if err = client.CreateAssociation("csnRtId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to create csn route association, err: %v.\n", err) + return + } + fmt.Println("Successfully creat csn route association.") +} diff --git a/bce-sdk-go/examples/csn/example_create_csn.go b/bce-sdk-go/examples/csn/example_create_csn.go new file mode 100644 index 0000000..2449653 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_create_csn.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + description := "csn_test description" + request := &csn.CreateCsnRequest{ + Name: "csn_test", // 云智能网的名称 + Description: &description, // 云智能网的描述 + } + response, err := client.CreateCsn(request, util.NewUUID()) + if err != nil { + fmt.Printf("Failed to create csn, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_create_csn_bp.go b/bce-sdk-go/examples/csn/example_create_csn_bp.go new file mode 100644 index 0000000..bbf057b --- /dev/null +++ b/bce-sdk-go/examples/csn/example_create_csn_bp.go @@ -0,0 +1,37 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + interworkType := "center" + request := &csn.CreateCsnBpRequest{ + Name: "csn_bp_test", // 带宽包的名称,不能为空 + InterworkType: &interworkType, // 带宽包的互通类型,取值 [ center | center-edge | edge-edge ],分别表示云间互通、云边互通、边边互通,默认为云间互通 + Bandwidth: 10, // 带宽包的带宽值,最大值为10000 + GeographicA: "China", // 网络实例所属的区域。取值 [ China | Asia-Pacific ],分别表示中国大陆、亚太区域 + GeographicB: "China", // 另一个网络实例所属的区域。取值 [ China | Asia-Pacific ],分别表示中国大陆、亚太区域 + Billing: csn.Billing{ // 计费信息 + PaymentTiming: "Prepaid", // 付款时间,预支付(Prepaid)和后支付(Postpaid) + Reservation: &csn.Reservation{ // 保留信息,支付方式为后支付时不需要设置,预支付时必须设置 + ReservationLength: 1, // 时长,[1,2,3,4,5,6,7,8,9,12,24,36] + ReservationTimeUnit: "month", // 时间单位,当前仅支持按月,取值month + }, + }, + } + response, err := client.CreateCsnBp(request, util.NewUUID()) + if err != nil { + fmt.Printf("Failed to create csn bp, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_create_csn_bp_limit.go b/bce-sdk-go/examples/csn/example_create_csn_bp_limit.go new file mode 100644 index 0000000..85b807f --- /dev/null +++ b/bce-sdk-go/examples/csn/example_create_csn_bp_limit.go @@ -0,0 +1,26 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreateCsnBpLimit() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.CreateCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "cn-hangzhou-cm", + Bandwidth: 10, + } + if err = client.CreateCsnBpLimit("csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to create csn bp limit, err: %v.\n", err) + return + } + fmt.Println("Successfully create csn bp limit.") +} diff --git a/bce-sdk-go/examples/csn/example_create_propagation.go b/bce-sdk-go/examples/csn/example_create_propagation.go new file mode 100644 index 0000000..78bce30 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_create_propagation.go @@ -0,0 +1,28 @@ +package csnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreatePropagation() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxxx" //云智能网路由表的ID + clientToken := util.NewUUID() //幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 + desc := "desc" + args := &csn.CreatePropagationRequest{ + AttachId: "tgwAttach-uff0gvjkis95f6xg", + Description: &desc, + } + err := client.CreatePropagation(csnRtId, args, clientToken) // 创建学习关系 + + if err != nil { + fmt.Println(err) + } + + fmt.Print("create propagation success.") +} diff --git a/bce-sdk-go/examples/csn/example_create_route_rule.go b/bce-sdk-go/examples/csn/example_create_route_rule.go new file mode 100644 index 0000000..92dc8ef --- /dev/null +++ b/bce-sdk-go/examples/csn/example_create_route_rule.go @@ -0,0 +1,27 @@ +package csnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreateRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxxx" //云智能网路由表的ID + clientToken := util.NewUUID() //幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 + args := &csn.CreateRouteRuleRequest{ + AttachId: "tgwAttach-rvu8tkaubphb78eg", + DestAddress: "0.0.0.0/0", + RouteType: "custom", + } + + err := client.CreateRouteRule(csnRtId, args, clientToken) // 创建路由规则 + if err != nil { + fmt.Println(err) + } + fmt.Println("create route rule success.") +} diff --git a/bce-sdk-go/examples/csn/example_delete_association.go b/bce-sdk-go/examples/csn/example_delete_association.go new file mode 100644 index 0000000..c1e97a9 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_delete_association.go @@ -0,0 +1,21 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func DeleteAssociation() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + if err = client.DeleteAssociation("csnRtId", "attachId", util.NewUUID()); err != nil { + fmt.Printf("Failed to delete csn route association, err: %v.\n", err) + return + } + fmt.Println("Successfully deleted csn route association.") +} diff --git a/bce-sdk-go/examples/csn/example_delete_csn.go b/bce-sdk-go/examples/csn/example_delete_csn.go new file mode 100644 index 0000000..5d15f9b --- /dev/null +++ b/bce-sdk-go/examples/csn/example_delete_csn.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + if err = client.DeleteCsn("Your csnId", util.NewUUID()); err != nil { + fmt.Printf("Failed to delete csn, err: %v.\n", err) + return + } + fmt.Println("Successfully deleted csn.") +} diff --git a/bce-sdk-go/examples/csn/example_delete_csn_bp.go b/bce-sdk-go/examples/csn/example_delete_csn_bp.go new file mode 100644 index 0000000..fbd7879 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_delete_csn_bp.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + if err = client.DeleteCsnBp("Your csnBpId", util.NewUUID()); err != nil { + fmt.Printf("Failed to delete csn bp, err: %v.\n", err) + return + } + fmt.Println("Successfully deleted csn bp.") +} diff --git a/bce-sdk-go/examples/csn/example_delete_csn_bp_limit.go b/bce-sdk-go/examples/csn/example_delete_csn_bp_limit.go new file mode 100644 index 0000000..4318d1b --- /dev/null +++ b/bce-sdk-go/examples/csn/example_delete_csn_bp_limit.go @@ -0,0 +1,25 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func DeleteCsnBpLimit() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.DeleteCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "cn-hangzhou-cm", + } + if err = client.DeleteCsnBpLimit("csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to delete csn bp limit, err: %v.\n", err) + return + } + fmt.Println("Successfully deleted csn bp limit.") +} diff --git a/bce-sdk-go/examples/csn/example_delete_propagation.go b/bce-sdk-go/examples/csn/example_delete_propagation.go new file mode 100644 index 0000000..ef1411b --- /dev/null +++ b/bce-sdk-go/examples/csn/example_delete_propagation.go @@ -0,0 +1,24 @@ +package csnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func DeletePropagation() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxx" //云智能网路由表的ID + attachId := "tgwAttach-xxxx" //网络实例在云智能网中的身份ID + clientToken := util.NewUUID() //幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 + + err := client.DeletePropagation(csnRtId, attachId, clientToken) // 删除学习关系 + + if err != nil { + fmt.Println(err) + } + fmt.Println("delete propagation success.") +} diff --git a/bce-sdk-go/examples/csn/example_delete_routerule.go b/bce-sdk-go/examples/csn/example_delete_routerule.go new file mode 100644 index 0000000..8742fa1 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_delete_routerule.go @@ -0,0 +1,32 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +// DeleteRouteRule - 删除云智能网路由表的指定路由条目。 +// +// PARAMS: +// - csnRtId: 路由表的ID +// - csnRtRuleId: 路由条目的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs + +func DeleteRouteRule() { + ak, sk, endpoint := "Your AK", "Your SK", "csn.baidubce.com" + client, err := csn.NewClient(ak, sk, endpoint) + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + if err = client.DeleteRouteRule("csnRtId", // 路由表的ID + "csnRtRuleId", "clientToken"); err != nil { + fmt.Printf("Failed to delete RouteRule, err: %v.\n", err) + return + } + fmt.Println("Successfully deleted RouteRule.") +} diff --git a/bce-sdk-go/examples/csn/example_detach_instance.go b/bce-sdk-go/examples/csn/example_detach_instance.go new file mode 100644 index 0000000..86d92cb --- /dev/null +++ b/bce-sdk-go/examples/csn/example_detach_instance.go @@ -0,0 +1,27 @@ +package csnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func DetachInstance() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.DetachInstanceRequest{ + InstanceType: "vpc", // 加载的实例类型,取值 [ vpc | channel | bec_vpc ],分别表示私有网络、专线通道、边缘网络 + InstanceId: "Your vpcId", // 加载的实例ID + InstanceRegion: "bj", // 加载的实例所属的region + InstanceAccountId: nil, // 跨账号加载网络实例场景下,网络实例所属账号的ID + } + if err = client.DetachInstance("Your csnId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to detach instance, err: %v.\n", err) + return + } + fmt.Println("Successfully detached instance.") +} diff --git a/bce-sdk-go/examples/csn/example_dettach_instance.go b/bce-sdk-go/examples/csn/example_dettach_instance.go new file mode 100644 index 0000000..d0a2327 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_dettach_instance.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.DetachInstanceRequest{ + InstanceType: "vpc", // 加载的实例类型,取值 [ vpc | channel | bec_vpc ],分别表示私有网络、专线通道、边缘网络 + InstanceId: "Your vpcId", // 加载的实例ID + InstanceRegion: "bj", // 加载的实例所属的region + InstanceAccountId: nil, // 跨账号加载网络实例场景下,网络实例所属账号的ID + } + if err = client.DetachInstance("Your csnId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to detach instance, err: %v.\n", err) + return + } + fmt.Println("Successfully detached instance.") +} diff --git a/bce-sdk-go/examples/csn/example_get_csn.go b/bce-sdk-go/examples/csn/example_get_csn.go new file mode 100644 index 0000000..588faac --- /dev/null +++ b/bce-sdk-go/examples/csn/example_get_csn.go @@ -0,0 +1,21 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + response, err := client.GetCsn("Your csnId") + if err != nil { + fmt.Printf("Failed to get csn, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_get_csn_bp.go b/bce-sdk-go/examples/csn/example_get_csn_bp.go new file mode 100644 index 0000000..d140596 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_get_csn_bp.go @@ -0,0 +1,21 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func GetCsnBp() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + response, err := client.GetCsnBp("csnBpId") + if err != nil { + fmt.Printf("Failed to get csn Bp, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_get_tgwlist.go b/bce-sdk-go/examples/csn/example_get_tgwlist.go new file mode 100644 index 0000000..e0f08b0 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_get_tgwlist.go @@ -0,0 +1,38 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +// ListTgw - 查询云智能网TGW列表。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// RETURNS: +// - *ListTgwResponse: +// - error: the return error if any occurs + +func ListTgw() { + ak, sk, endpoint := "Your AK", "Your SK", "csn.baidubce.com" + client, err := csn.NewClient(ak, sk, endpoint) + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + args := &csn.ListTgwArgs{ + Marker: "", + MaxKeys: 1000, + } + response, err := client.ListTgw("csnid", args) // 云智能网csn的ID + if err != nil { + fmt.Printf("Failed to list tgw, err: %v.\n", err) + panic(err) + } + if response != nil { + fmt.Printf("%+v\n", *response) + } +} diff --git a/bce-sdk-go/examples/csn/example_get_tgwrule.go b/bce-sdk-go/examples/csn/example_get_tgwrule.go new file mode 100644 index 0000000..0d3ca12 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_get_tgwrule.go @@ -0,0 +1,39 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +// ListTgwRule - 查询指定TGW的路由条目。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - tgwId: TGW的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// RETURNS: +// - *ListTgwRuleResponse: +// - error: the return error if any occurs + +func ListTgwRule() { + ak, sk, endpoint := "Your AK", "Your SK", "csn.baidubce.com" + client, err := csn.NewClient(ak, sk, endpoint) + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + args := &csn.ListTgwRuleArgs{ + MaxKeys: 1000, + } + // csnId: 云智能网的ID tgwId: TGW的ID + response, err := client.ListTgwRule("csnid", "tgwid", args) + if err != nil { + panic(err) + } + if response != nil { + fmt.Printf("%+v\n", *response) + } + fmt.Println("Successfully get TGW Rules.") +} diff --git a/bce-sdk-go/examples/csn/example_list_association.go b/bce-sdk-go/examples/csn/example_list_association.go new file mode 100644 index 0000000..0794ad0 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_association.go @@ -0,0 +1,21 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListAssociation() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + response, err := client.ListAssociation("csnRtId") + if err != nil { + fmt.Printf("Failed to list csn route association, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_list_csn.go b/bce-sdk-go/examples/csn/example_list_csn.go new file mode 100644 index 0000000..5f2a47f --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_csn.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + args := &csn.ListCsnArgs{ + Marker: "", // 批量获取列表的查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000,缺省值为1000 + } + response, err := client.ListCsn(args) + if err != nil { + fmt.Printf("Failed to list csn, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_list_csn_bp.go b/bce-sdk-go/examples/csn/example_list_csn_bp.go new file mode 100644 index 0000000..6be1466 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_csn_bp.go @@ -0,0 +1,25 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListCsnBp() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.ListCsnBpArgs{ + Marker: "", // 批量获取列表的查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000,缺省值为1000 + } + response, err := client.ListCsnBp(request) + if err != nil { + fmt.Printf("Failed to list csn bp, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_list_csn_bp_limit.go b/bce-sdk-go/examples/csn/example_list_csn_bp_limit.go new file mode 100644 index 0000000..07ce337 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_csn_bp_limit.go @@ -0,0 +1,21 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListCsnBpLimit() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + response, err := client.ListCsnBpLimit("csnBpId") + if err != nil { + fmt.Printf("Failed to list csn bp limit, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_list_csn_bp_limit_by_csn_id.go b/bce-sdk-go/examples/csn/example_list_csn_bp_limit_by_csn_id.go new file mode 100644 index 0000000..a72ecb5 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_csn_bp_limit_by_csn_id.go @@ -0,0 +1,21 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListCsnBpLimitByCsnId() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + response, err := client.ListCsnBpLimitByCsnId("cnsId") + if err != nil { + fmt.Printf("Failed to list csn limit by csnid, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_list_instance.go b/bce-sdk-go/examples/csn/example_list_instance.go new file mode 100644 index 0000000..b47f6b7 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_instance.go @@ -0,0 +1,25 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + args := &csn.ListInstanceArgs{ + Marker: "", // 批量获取列表的查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000,缺省值为1000 + } + response, err := client.ListInstance("Your csnId", args) + if err != nil { + fmt.Printf("Failed to list instance, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_list_propagation.go b/bce-sdk-go/examples/csn/example_list_propagation.go new file mode 100644 index 0000000..e1bfca3 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_propagation.go @@ -0,0 +1,21 @@ +package csnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListPropagation() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxx" //云智能网路由表的ID + + response, err := client.ListPropagation(csnRtId) + if err != nil { + fmt.Println(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/csn/example_list_route_rule.go b/bce-sdk-go/examples/csn/example_list_route_rule.go new file mode 100644 index 0000000..cbe89d5 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_route_rule.go @@ -0,0 +1,22 @@ +package csnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxx" //云智能网路由表的ID + args := &csn.ListRouteRuleArgs{} + + response, err := client.ListRouteRule(csnRtId, args) + if err != nil { + fmt.Println(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/csn/example_list_routetable.go b/bce-sdk-go/examples/csn/example_list_routetable.go new file mode 100644 index 0000000..049d9bf --- /dev/null +++ b/bce-sdk-go/examples/csn/example_list_routetable.go @@ -0,0 +1,26 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func ListRouteTable() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + args := &csn.ListRouteTableArgs{ + Marker: "", // 批量获取列表的查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000,缺省值为1000 + } + response, err := client.ListRouteTable("csnId", args) + if err != nil { + fmt.Printf("Failed to list csn route table, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/csn/example_resize_csn_bp.go b/bce-sdk-go/examples/csn/example_resize_csn_bp.go new file mode 100644 index 0000000..c1b1889 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_resize_csn_bp.go @@ -0,0 +1,24 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func ResizeCsnBp() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.ResizeCsnBpRequest{ + Bandwidth: 1000, // 带宽包带宽 + } + if err = client.ResizeCsnBp("csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to resize csn bp, err: %v.\n", err) + return + } + fmt.Println("Successfully resize csn bp.") +} diff --git a/bce-sdk-go/examples/csn/example_unbind_csn_bp.go b/bce-sdk-go/examples/csn/example_unbind_csn_bp.go new file mode 100644 index 0000000..3a68994 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_unbind_csn_bp.go @@ -0,0 +1,24 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func UnbindCsnBp() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.UnbindCsnBpRequest{ + CsnId: "csnId", + } + if err = client.UnbindCsnBp("csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to unbind csn bp, err: %v.\n", err) + return + } + fmt.Println("Successfully unbind csn bp.") +} diff --git a/bce-sdk-go/examples/csn/example_update_csn.go b/bce-sdk-go/examples/csn/example_update_csn.go new file mode 100644 index 0000000..9199ebd --- /dev/null +++ b/bce-sdk-go/examples/csn/example_update_csn.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + name := "csn_test_update" + description := "csn_test_update description" + request := &csn.UpdateCsnRequest{ + Name: &name, // 云智能网的名称 + Description: &description, // 云智能网的描述 + } + if err = client.UpdateCsn("Your csnId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to update csn, err: %v.\n", err) + return + } + fmt.Println("Successfully updated csn.") +} diff --git a/bce-sdk-go/examples/csn/example_update_csn_bp.go b/bce-sdk-go/examples/csn/example_update_csn_bp.go new file mode 100644 index 0000000..e3c2e26 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_update_csn_bp.go @@ -0,0 +1,24 @@ +package main + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func main() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.UpdateCsnBpRequest{ + Name: "csn_bp_test_update", // 带宽包名称 + } + if err = client.UpdateCsnBp("Your csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to update csn bp, err: %v.\n", err) + return + } + fmt.Println("Successfully updated csn bp.") +} diff --git a/bce-sdk-go/examples/csn/example_update_csn_bp_limit.go b/bce-sdk-go/examples/csn/example_update_csn_bp_limit.go new file mode 100644 index 0000000..7ff799e --- /dev/null +++ b/bce-sdk-go/examples/csn/example_update_csn_bp_limit.go @@ -0,0 +1,26 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func UpdateCsnBpLimit() { + client, err := csn.NewClient("Your AK", "Your SK", "csn.baidubce.com") + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + request := &csn.CreateCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "cn-hangzhou-cm", + Bandwidth: 10, + } + if err = client.UpdateCsnBpLimit("csnBpId", request, util.NewUUID()); err != nil { + fmt.Printf("Failed to update csn bp limit, err: %v.\n", err) + return + } + fmt.Println("Successfully update csn bp limit.") +} diff --git a/bce-sdk-go/examples/csn/example_update_tgw.go b/bce-sdk-go/examples/csn/example_update_tgw.go new file mode 100644 index 0000000..99c7cc1 --- /dev/null +++ b/bce-sdk-go/examples/csn/example_update_tgw.go @@ -0,0 +1,37 @@ +package csnexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +// UpdateTgw - 更新TGW的名称、描述。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - tgwId: TGW实例的ID +// - body: body参数 +// RETURNS: +// - error: the return error if any occurs + +func UpdateTgw() { + ak, sk, endpoint := "Your AK", "Your SK", "csn.baidubce.com" + client, err := csn.NewClient(ak, sk, endpoint) + if err != nil { + fmt.Printf("Failed to new csn client, err: %v.\n", err) + return + } + name := "tgw_1" + desc := "desc" + args := &csn.UpdateTgwRequest{ + Name: &name, // TGW名称 + Description: &desc, // TGW描述 + } + // csnId: 云智能网的ID tgwId: TGW的ID + if err := client.UpdateTgw("csnId", "tgwId", args, "clientToken"); err != nil { + fmt.Printf("Failed to update TGW, err: %v.\n", err) + panic(err) + } + fmt.Println("Successfully updated TGW.") +} diff --git a/bce-sdk-go/examples/eip/example_conf.go b/bce-sdk-go/examples/eip/example_conf.go new file mode 100644 index 0000000..2da370e --- /dev/null +++ b/bce-sdk-go/examples/eip/example_conf.go @@ -0,0 +1,30 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/eip" +) + +var ( + eipClient *eip.Client + AK = "ak" + SK = "sk" + HOST = "endpoint" +) + +func Init() { + eipClient, _ = eip.NewClient(AK, SK, HOST) +} diff --git a/bce-sdk-go/examples/eip/example_eip_bind_eip.go b/bce-sdk-go/examples/eip/example_eip_bind_eip.go new file mode 100644 index 0000000..4e8813a --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_bind_eip.go @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func BindEip() { + Init() + + // 绑定EIP地址 + eip := "x.x.x.x" + + // 绑定实例 + bindEipArgs := &EIP.BindEipArgs{ + InstanceId: "lb-xxxxxxxx", //实例ID + InstanceType: "BLB", //实例类型 + } + + err := eipClient.BindEip(eip, bindEipArgs) + if err != nil { + panic(err) + } + + fmt.Println("Bind EIP successfully") +} diff --git a/bce-sdk-go/examples/eip/example_eip_create_eip.go b/bce-sdk-go/examples/eip/example_eip_create_eip.go new file mode 100644 index 0000000..2ff5fff --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_create_eip.go @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func CreateEip() { + Init() + // 创建后付费EIP + billing := &EIP.Billing{ + PaymentTiming: "Postpaid", //后付费 + BillingMethod: "ByBandwidth", //按带宽计费 + } + args := &EIP.CreateEipArgs{ + Name: "test-eip", //EIP名称 + BandWidthInMbps: 10, //带宽,单位Mbps + Billing: billing, //订单信息 + } + resp, err := eipClient.CreateEip(args) + + if err != nil { + panic(err) + } + + fmt.Println(resp) +} diff --git a/bce-sdk-go/examples/eip/example_eip_delete_eip.go b/bce-sdk-go/examples/eip/example_eip_delete_eip.go new file mode 100644 index 0000000..eec5585 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_delete_eip.go @@ -0,0 +1,31 @@ +/* + * 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 eipexamples + +import ( + "fmt" +) + +func DeleteEip() { + Init() + + // 被删除EIP的ID + eip := "x.x.x.x" + + err := eipClient.DeleteEip(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("Delete eip success!") +} diff --git a/bce-sdk-go/examples/eip/example_eip_delete_recycle_eip.go b/bce-sdk-go/examples/eip/example_eip_delete_recycle_eip.go new file mode 100644 index 0000000..63bf2bc --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_delete_recycle_eip.go @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func DeleteRecycleEip() { + Init() + + // 从回收站内删除的EIP + eip := "x.x.x.x" + // 删除回收站内的EIP + err := eipClient.DeleteRecycleEip(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("Delete Recycle EIP Success") +} diff --git a/bce-sdk-go/examples/eip/example_eip_direct_eip.go b/bce-sdk-go/examples/eip/example_eip_direct_eip.go new file mode 100644 index 0000000..3ca51ee --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_direct_eip.go @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func DirectEip() { + Init() + + // 开启直通的EIP + eip := "x.x.x.x" + err := eipClient.DirectEip(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("Direct EIP successfully") +} diff --git a/bce-sdk-go/examples/eip/example_eip_list_eips.go b/bce-sdk-go/examples/eip/example_eip_list_eips.go new file mode 100644 index 0000000..e9cd6bf --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_list_eips.go @@ -0,0 +1,47 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ListEip() { + Init() + + listEipArgs := &EIP.ListEipArgs{ + Eip: "", // 指定EIP + InstanceType: "", // 指定实例类型 + InstanceId: "", // 指定实例ID + Marker: "", // 分页查询起始位置标识符 + MaxKeys: 1000, // 分页查询每页最大数量 + Status: "", // 指定EIP状态 + } + listEipResult, err := eipClient.ListEip(listEipArgs) + + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(listEipResult, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eip_list_recycle_eip.go b/bce-sdk-go/examples/eip/example_eip_list_recycle_eip.go new file mode 100644 index 0000000..54dfe54 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_list_recycle_eip.go @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ListRecycleEip() { + Init() + + listRecycleEipArgs := &EIP.ListRecycleEipArgs{ + Eip: "", // 指定EIP + Name: "", // 指定EIP名称 + Marker: "", // 分页查询的起始地址 + MaxKeys: 1000, // 分页查询的记录数 + } + listRecycleEipResult, err := eipClient.ListRecycleEip(listRecycleEipArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(listRecycleEipResult, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eip_optional_delete_eip.go b/bce-sdk-go/examples/eip/example_eip_optional_delete_eip.go new file mode 100644 index 0000000..d87445d --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_optional_delete_eip.go @@ -0,0 +1,35 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func OptionalDeleteEip() { + Init() + + // 被删除的EIP + eip := "x.x.x.x" + // 放到回收站内 + releaseToRecycle := true + // 删除EIP + err := eipClient.OptionalDeleteEip(eip, "", releaseToRecycle) + if err != nil { + panic(err) + } + + fmt.Println("OptionalDeleteEip success") +} diff --git a/bce-sdk-go/examples/eip/example_eip_purchase_reserved_eip.go b/bce-sdk-go/examples/eip/example_eip_purchase_reserved_eip.go new file mode 100644 index 0000000..310439b --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_purchase_reserved_eip.go @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func PurchaseReservedEip() { + Init() + + // 续费的EIP + eip := "x.x.x.x" + + purchaseReservedEipArgs := &EIP.PurchaseReservedEipArgs{ + Billing: &EIP.Billing{ + Reservation: &EIP.Reservation{ + ReservationLength: 2, //续费两个周期 + ReservationTimeUnit: "Month", //续费周期 + }, + }, + ClientToken: "", + } + err := eipClient.PurchaseReservedEip(eip, purchaseReservedEipArgs) + if err != nil { + panic(err) + } + + fmt.Println("PurchaseReservedEip success!") +} diff --git a/bce-sdk-go/examples/eip/example_eip_resize_eip.go b/bce-sdk-go/examples/eip/example_eip_resize_eip.go new file mode 100644 index 0000000..63ddd5b --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_resize_eip.go @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ResizeEip() { + Init() + + // eip地址 + eip := "x.x.x.x" + + resizeEipArgs := &EIP.ResizeEipArgs{ + NewBandWidthInMbps: 10, // 新的带宽 + } + + // 调用ResizeEip + err := eipClient.ResizeEip(eip, resizeEipArgs) + + if err != nil { + panic(err) + } + + fmt.Println("ResizeEip success") +} diff --git a/bce-sdk-go/examples/eip/example_eip_restore_recycle_eip.go b/bce-sdk-go/examples/eip/example_eip_restore_recycle_eip.go new file mode 100644 index 0000000..05a4bcd --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_restore_recycle_eip.go @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import "fmt" + +func RestoreRecycleEip() { + Init() + + // 从回收站恢复的EIP + eip := "x.x.x.x" + + // 恢复EIP + err := eipClient.RestoreRecycleEip(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("RestoreRecycleEip success") +} diff --git a/bce-sdk-go/examples/eip/example_eip_start_auto_renew.go b/bce-sdk-go/examples/eip/example_eip_start_auto_renew.go new file mode 100644 index 0000000..3fe31e8 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_start_auto_renew.go @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func StartAutoRenew() { + Init() + + // 开启自动续费的EIP + eip := "x.x.x.x" + startAutoRenewArgs := &EIP.StartAutoRenewArgs{ + AutoRenewTimeUnit: "month", // 续费周期 + AutoRenewTime: 1, // 续费周期数 + ClientToken: "", + } + err := eipClient.StartAutoRenew(eip, startAutoRenewArgs) + if err != nil { + panic(err) + } + + fmt.Println("StartAutoRenew success") +} diff --git a/bce-sdk-go/examples/eip/example_eip_stop_auto_renew.go b/bce-sdk-go/examples/eip/example_eip_stop_auto_renew.go new file mode 100644 index 0000000..1e39a38 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_stop_auto_renew.go @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func StopAutoRenew() { + Init() + + // 关闭自动续费的EIP + eip := "x.x.x.x" + err := eipClient.StopAutoRenew(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("Stop auto renew eip success") +} diff --git a/bce-sdk-go/examples/eip/example_eip_unbind_eip.go b/bce-sdk-go/examples/eip/example_eip_unbind_eip.go new file mode 100644 index 0000000..c76ff69 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_unbind_eip.go @@ -0,0 +1,33 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func UnBindEip() { + Init() + + // 解绑EIP的地址 + eip := "x.x.x.x" + + err := eipClient.UnBindEip(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("Unbind eip success!") +} diff --git a/bce-sdk-go/examples/eip/example_eip_undirect_eip.go b/bce-sdk-go/examples/eip/example_eip_undirect_eip.go new file mode 100644 index 0000000..21d208f --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eip_undirect_eip.go @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func UnDirectEip() { + Init() + + // 关闭直通的EIP + eip := "x.x.x.x" + err := eipClient.UnDirectEip(eip, "") + if err != nil { + panic(err) + } + + fmt.Println("UnDirect EIP successfully") +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_create_eipbp.go b/bce-sdk-go/examples/eip/example_eipbp_create_eipbp.go new file mode 100644 index 0000000..706b47d --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_create_eipbp.go @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func CreateEipBp() { + Init() + + createEipBpArgs := &EIP.CreateEipBpArgs{ + Name: "test-eipbp", // EipBp的名称 + Eip: "x.x.x.x", // EipBp绑定的EIP地址 + EipGroupId: "eg-xxxxxxxx", // EipBp绑定的EIPGroup ID,EIP和EIPGroup不能同时存在,如果同时存在,则EIP的优先级更高 + BandwidthInMbps: 200, // EipBp的带宽,单位Mbps,该值与所绑定资源的带宽总和不大于200Mbps + Type: "BandwidthPackage", // EipBp的类型 + AutoReleaseTime: "2023-12-13T20:38:43Z", // EipBp的自动释放时间,格式为UTC时间,如不填写则随所绑定资源的到期一并释放 + } + createEipBpResult, err := eipClient.CreateEipBp(createEipBpArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(createEipBpResult, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_delete_eipbp.go b/bce-sdk-go/examples/eip/example_eipbp_delete_eipbp.go new file mode 100644 index 0000000..f4f1f22 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_delete_eipbp.go @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func DeleteEipBp() { + Init() + + // 被删除eipbp的id + id := "bw-xxxxxxxx" + err := eipClient.DeleteEipBp(id, "") + if err != nil { + panic(err) + } + + fmt.Println("DeleteEipBp success") +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_get_eipbp.go b/bce-sdk-go/examples/eip/example_eipbp_get_eipbp.go new file mode 100644 index 0000000..b513560 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_get_eipbp.go @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" +) + +func GetEipBp() { + Init() + + // 要查询eipbp详情的id + id := "bw-xxxxxxxx" + eipBpDetail, err := eipClient.GetEipBp(id, "") + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(eipBpDetail, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_list_eipbp.go b/bce-sdk-go/examples/eip/example_eipbp_list_eipbp.go new file mode 100644 index 0000000..7199013 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_list_eipbp.go @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ListEipBp() { + Init() + + listEipBpArgs := &EIP.ListEipBpArgs{ + Id: "", + Name: "", + Marker: "", + MaxKeys: 1000, + BindType: "", + Type: "", + } + listEipBpResult, err := eipClient.ListEipBp(listEipBpArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(listEipBpResult, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_resize_eipbp.go b/bce-sdk-go/examples/eip/example_eipbp_resize_eipbp.go new file mode 100644 index 0000000..9cd44ab --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_resize_eipbp.go @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ResizeEipBp() { + Init() + + // 重设带宽的eipbp的id + id := "bw-xxxxxxxx" + resizeEipBpArgs := &EIP.ResizeEipBpArgs{ + BandwidthInMbps: 400, + } + err := eipClient.ResizeEipBp(id, resizeEipBpArgs) + if err != nil { + panic(err) + } + + fmt.Println("ResizeEipBp success") + +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_update_eipbp_autoreleasetime.go b/bce-sdk-go/examples/eip/example_eipbp_update_eipbp_autoreleasetime.go new file mode 100644 index 0000000..9fc855c --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_update_eipbp_autoreleasetime.go @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func UpdateEipBpAutoReleaseTime() { + Init() + + // 更新eipbp的自动释放时间的id + id := "bw-xxxxxxxx" + updateEipBpAutoReleaseTimeArgs := &EIP.UpdateEipBpAutoReleaseTimeArgs{ + AutoReleaseTime: "2024-01-28T16:45:00Z", + } + err := eipClient.UpdateEipBpAutoReleaseTime(id, updateEipBpAutoReleaseTimeArgs) + if err != nil { + panic(err) + } + + fmt.Println("UpdateEipBpAutoReleaseTime success") +} diff --git a/bce-sdk-go/examples/eip/example_eipbp_update_eipbp_name.go b/bce-sdk-go/examples/eip/example_eipbp_update_eipbp_name.go new file mode 100644 index 0000000..81ffb1a --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipbp_update_eipbp_name.go @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func UpdateEipBpName() { + Init() + + // 更新eipbp name的id + id := "bw-xxxxxxxx" + updateEipBpNameArgs := &EIP.UpdateEipBpNameArgs{ + Name: "new-name", + } + err := eipClient.UpdateEipBpName(id, updateEipBpNameArgs) + if err != nil { + panic(err) + } + + fmt.Println("Update eipbp name success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_add_eip_count.go b/bce-sdk-go/examples/eip/example_eipgroup_add_eip_count.go new file mode 100644 index 0000000..8d4f6f3 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_add_eip_count.go @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func EipGroupAddEipCount() { + Init() + + // 增加EIP数量的eipgroup id + id := "eg-xxxxxxxx" + groupAddEipCountArgs := &EIP.GroupAddEipCountArgs{ + EipAddCount: 1, + } + err := eipClient.EipGroupAddEipCount(id, groupAddEipCountArgs) + if err != nil { + panic(err) + } + + fmt.Println("EipGroupAddEipCount success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_create_eipgroup.go b/bce-sdk-go/examples/eip/example_eipgroup_create_eipgroup.go new file mode 100644 index 0000000..2091baa --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_create_eipgroup.go @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func CreateEipGroup() { + Init() + + createEipGroupArgs := &EIP.CreateEipGroupArgs{ + Name: "test-eipgroup-go", // 共享带宽名称 + EipCount: 5, // 共享带宽的IP数量 + BandWidthInMbps: 100, // 共享带宽的带宽 + Billing: &EIP.Billing{ + PaymentTiming: "Prepaid", // 后付费 + Reservation: &EIP.Reservation{ + ReservationLength: 1, // 预付费的周期数 + ReservationTimeUnit: "month", // 预付费的周期单位 + }, + }, + } + eipGroupResult, err := eipClient.CreateEipGroup(createEipGroupArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(eipGroupResult, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_delete_eipgroup.go b/bce-sdk-go/examples/eip/example_eipgroup_delete_eipgroup.go new file mode 100644 index 0000000..cc16fff --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_delete_eipgroup.go @@ -0,0 +1,32 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" +) + +func DeleteEipGroup() { + Init() + + // 被删除的eipgroup的id + id := "eg-xxxxxxxx" + err := eipClient.DeleteEipGroup(id, "") + if err != nil { + panic(err) + } + + fmt.Println("Delete eipgroup success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_detail.go b/bce-sdk-go/examples/eip/example_eipgroup_detail.go new file mode 100644 index 0000000..95db31e --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_detail.go @@ -0,0 +1,39 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" +) + +func EipGroupDetail() { + Init() + + // 详细信息的eipgroup id + id := "eg-xxxxxxxx" + // 获取eipgroup详情 + eipGroupDetail, err := eipClient.EipGroupDetail(id) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(eipGroupDetail, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_list_eipgroup.go b/bce-sdk-go/examples/eip/example_eipgroup_list_eipgroup.go new file mode 100644 index 0000000..b1d5910 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_list_eipgroup.go @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ListEipGroup() { + Init() + + listEipGroupArgs := &EIP.ListEipGroupArgs{ + Id: "", // 指定ID查询 + Name: "", // 指定名称查询 + Marker: "", // 分页查询的起始位置 + MaxKeys: 1000, // 分页查询的个数 + Status: "", // 指定状态查询 + } + eipGroupList, err := eipClient.ListEipGroup(listEipGroupArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(eipGroupList, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_move_in.go b/bce-sdk-go/examples/eip/example_eipgroup_move_in.go new file mode 100644 index 0000000..f33cdb3 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_move_in.go @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func EipGroupMoveIn() { + Init() + + // 移入eip的eipgroup id + id := "eg-xxxxxxxx" + eipGroupMoveInArgs := &EIP.EipGroupMoveInArgs{ + Eips: []string{"x.x.x.x"}, // 待移入eipgroup的eip列表 + } + err := eipClient.EipGroupMoveIn(id, eipGroupMoveInArgs) + if err != nil { + panic(err) + } + + fmt.Println("move in eipgroup success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_move_out.go b/bce-sdk-go/examples/eip/example_eipgroup_move_out.go new file mode 100644 index 0000000..ed3cd1c --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_move_out.go @@ -0,0 +1,49 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func EipGroupMoveOut() { + Init() + + // 移出EIP的eipgroup id + id := "eg-xxxxxxxx" + eipGroupMoveOutArgs := &EIP.EipGroupMoveOutArgs{ + MoveOutEips: []EIP.MoveOutEip{ + { + Eip: "x.x.x.x", // 非原生EIP的eip + }, + { + Eip: "x.x.x.x", //原生EIP的eip,需要指定计费方式 + BandWidthInMbps: 10, //eip的带宽 + Billing: &EIP.Billing{ + PaymentTiming: "PostPaid", //后付费 + BillingMethod: "ByBandwidth", //计费方式 + }, + }, + }, + } + err := eipClient.EipGroupMoveOut(id, eipGroupMoveOutArgs) + if err != nil { + panic(err) + } + + fmt.Println("EipGroupMoveOut success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_purchase_reserved.go b/bce-sdk-go/examples/eip/example_eipgroup_purchase_reserved.go new file mode 100644 index 0000000..b694f87 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_purchase_reserved.go @@ -0,0 +1,42 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func EipGroupPurchaseReserved() { + Init() + + // 续费的eipgroup的id + id := "eg-xxxxxxxx" + eipGroupPurchaseReservedArgs := &EIP.EipGroupPurchaseReservedArgs{ + Billing: &EIP.Billing{ + Reservation: &EIP.Reservation{ + ReservationLength: 1, // 续费周期数量 + ReservationTimeUnit: "Month", // 续费周期单位 + }, + }, + } + err := eipClient.EipGroupPurchaseReserved(id, eipGroupPurchaseReservedArgs) + if err != nil { + panic(err) + } + + fmt.Println("EipGroupPurchaseReserved success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_rename_eipgroup.go b/bce-sdk-go/examples/eip/example_eipgroup_rename_eipgroup.go new file mode 100644 index 0000000..f5212be --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_rename_eipgroup.go @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func RenameEipGroup() { + Init() + + // 重命名的eipgroup的id + id := "eg-xxxxxxxx" + renameEipGroupArgs := &EIP.RenameEipGroupArgs{ + Name: "new_name", + } + err := eipClient.RenameEipGroup(id, renameEipGroupArgs) + if err != nil { + panic(err) + } + + fmt.Println("Rename eip group success") +} diff --git a/bce-sdk-go/examples/eip/example_eipgroup_resize_eipgroup_bandwidth.go b/bce-sdk-go/examples/eip/example_eipgroup_resize_eipgroup_bandwidth.go new file mode 100644 index 0000000..c5fb5ae --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eipgroup_resize_eipgroup_bandwidth.go @@ -0,0 +1,37 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ResizeEipGroupBandWidth() { + Init() + + // 修改带宽的id + id := "eg-xxxxxxxx" + resizeEipGroupArgs := &EIP.ResizeEipGroupArgs{ + BandWidthInMbps: 50, + } + err := eipClient.ResizeEipGroupBandWidth(id, resizeEipGroupArgs) + if err != nil { + panic(err) + } + + fmt.Println("ResizeEipGroupBandWidth success") +} diff --git a/bce-sdk-go/examples/eip/example_eiptp_create_eiptp.go b/bce-sdk-go/examples/eip/example_eiptp_create_eiptp.go new file mode 100644 index 0000000..5a468f1 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eiptp_create_eiptp.go @@ -0,0 +1,44 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func CreateEipTp() { + Init() + + createEipTpArgs := &EIP.CreateEipTpArgs{ + ReservationLength: 6, + Capacity: "300G", + DeductPolicy: "FullTimeDurationPackage", + PackageType: "WebOutBytes", + } + eiptp, err := eipClient.CreateEipTp(createEipTpArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(eiptp, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eiptp_get_eiptp.go b/bce-sdk-go/examples/eip/example_eiptp_get_eiptp.go new file mode 100644 index 0000000..b54ad39 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eiptp_get_eiptp.go @@ -0,0 +1,38 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" +) + +func GetEipTp() { + Init() + + // 指定查询的eiptp id + id := "tp-xxxxxxxxxx" + eipTpDetail, err := eipClient.GetEipTp(id) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(eipTpDetail, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/eip/example_eiptp_list_eiptp.go b/bce-sdk-go/examples/eip/example_eiptp_list_eiptp.go new file mode 100644 index 0000000..533ef36 --- /dev/null +++ b/bce-sdk-go/examples/eip/example_eiptp_list_eiptp.go @@ -0,0 +1,45 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eipexamples + +import ( + "encoding/json" + "fmt" + + EIP "github.com/baidubce/bce-sdk-go/services/eip" +) + +func ListEipTp() { + Init() + + listEipTpArgs := &EIP.ListEipTpArgs{ + Id: "", // 指定ID查询 + DeductPolicy: "", // 指定扣费策略查询 + Status: "", // 指定状态查询 + Marker: "", // 分页查询起始位置 + MaxKeys: 1000, // 分页查询的个数 + } + listEipTpResult, err := eipClient.ListEipTp(listEipTpArgs) + if err != nil { + panic(err) + } + + jsonData, err := json.MarshalIndent(listEipTpResult, "", " ") + if err != nil { + panic(err) + } + + fmt.Println(string(jsonData)) +} diff --git a/bce-sdk-go/examples/endpoint/example_create_endpoint.go b/bce-sdk-go/examples/endpoint/example_create_endpoint.go new file mode 100644 index 0000000..efad192 --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_create_endpoint.go @@ -0,0 +1,42 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func CreateEndpoint() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + args := &endpoint.CreateEndpointArgs{ + VpcId: "vpc id", + SubnetId: "subnet id", + Name: "name", + Service: "service", + Description: "desc", + Billing: &endpoint.Billing{ + PaymentTiming: "Postpaid", + }, + } + result, err := client.CreateEndpoint(args) // 创建endpoint + if err != nil { + fmt.Println(err) + } + fmt.Println(result) +} diff --git a/bce-sdk-go/examples/endpoint/example_delete_endpoint.go b/bce-sdk-go/examples/endpoint/example_delete_endpoint.go new file mode 100644 index 0000000..17618a0 --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_delete_endpoint.go @@ -0,0 +1,33 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func DeleteEndpoint() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + // 删除endpoint + endpointId := "endpoint id" + err := client.DeleteEndpoint(endpointId, "") // 删除endpoint + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/endpoint/example_get_endpoint_detail.go b/bce-sdk-go/examples/endpoint/example_get_endpoint_detail.go new file mode 100644 index 0000000..0bf379f --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_get_endpoint_detail.go @@ -0,0 +1,33 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func GetEndpointDetail() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + endpointId := "endpoint id" + res, err := client.GetEndpointDetail(endpointId) // 获取endpoint详情 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/endpoint/example_get_services.go b/bce-sdk-go/examples/endpoint/example_get_services.go new file mode 100644 index 0000000..9339d77 --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_get_services.go @@ -0,0 +1,32 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func GetServices() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + res, err := client.GetServices() // 获取service列表 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/endpoint/example_list_endpoints.go b/bce-sdk-go/examples/endpoint/example_list_endpoints.go new file mode 100644 index 0000000..edf425d --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_list_endpoints.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func ListEndpoints() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + args := &endpoint.ListEndpointArgs{ + VpcId: "vpc id", + SubnetId: "subnet id", + } + res, err := client.ListEndpoints(args) // 获取endpoint列表 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/endpoint/example_update_endpoint.go b/bce-sdk-go/examples/endpoint/example_update_endpoint.go new file mode 100644 index 0000000..7b91111 --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_update_endpoint.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func UpdateEndpoint() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + endpointId := "endpoint id" + args := &endpoint.UpdateEndpointArgs{ + Name: "UpdateName", + Description: "UpdateDescription", + } + + err := client.UpdateEndpoint(endpointId, args) // 更新endpoint + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/endpoint/example_update_endpoint_enterprise_security_group.go b/bce-sdk-go/examples/endpoint/example_update_endpoint_enterprise_security_group.go new file mode 100644 index 0000000..d86dc79 --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_update_endpoint_enterprise_security_group.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func UpdateEndpointEnterpriseSecurityGroup() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + endpointId := "endpoint id" + args := &endpoint.UpdateEndpointESGArgs{ + EnterpriseSecurityGroupIds: []string{"esg-nhwrebdqi4q2"}, // 替换为需要绑定的 enterprise security group 列表 + } + + err := client.UpdateEndpointEnterpriseSecurityGroup(endpointId, args) // 更新endpoint绑定的企业安全组 + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/endpoint/example_update_endpoint_normal_security_group.go b/bce-sdk-go/examples/endpoint/example_update_endpoint_normal_security_group.go new file mode 100644 index 0000000..4b3f6da --- /dev/null +++ b/bce-sdk-go/examples/endpoint/example_update_endpoint_normal_security_group.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 endpointexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/endpoint" +) + +func UpdateEndpointNormalSecurityGroup() { + ak, sk, Endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := endpoint.NewClient(ak, sk, Endpoint) // 初始化client + + endpointId := "endpoint id" + args := &endpoint.UpdateEndpointNSGArgs{ + SecurityGroupIds: []string{"g-wmxijt06y5um"}, // 替换为需要绑定的 enterprise security group 列表 + } + + err := client.UpdateEndpointNormalSecurityGroup(endpointId, args) // 更新endpoint绑定的普通安全组 + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/eni/example_add_private_ip.go b/bce-sdk-go/examples/eni/example_add_private_ip.go new file mode 100644 index 0000000..0c4d408 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_add_private_ip.go @@ -0,0 +1,30 @@ +package eniexamples + +import ( + "encoding/json" + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func AddPrivateIp() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.EniPrivateIpArgs{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + PrivateIpAddress: "10.0.1.108", // 私有IP地址 + } + response, err := ENI_CLIENT.AddPrivateIp(args) // 添加私有IP地址 + if err != nil { + panic(err) + } + r, err := json.Marshal(response) + fmt.Println(string(r)) +} diff --git a/bce-sdk-go/examples/eni/example_attach_eni_instance.go b/bce-sdk-go/examples/eni/example_attach_eni_instance.go new file mode 100644 index 0000000..11e27cb --- /dev/null +++ b/bce-sdk-go/examples/eni/example_attach_eni_instance.go @@ -0,0 +1,29 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func AttachEniInstance() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.EniInstance{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + InstanceId: "i-Dqf1k9ul", // 云主机ID + } + err := ENI_CLIENT.AttachEniInstance(args) // 弹性网卡挂载云主机 + if err != nil { + panic(err) + } + fmt.Println("AttachEniInstance success!") +} diff --git a/bce-sdk-go/examples/eni/example_batch_add_private_ip.go b/bce-sdk-go/examples/eni/example_batch_add_private_ip.go new file mode 100644 index 0000000..f17650b --- /dev/null +++ b/bce-sdk-go/examples/eni/example_batch_add_private_ip.go @@ -0,0 +1,34 @@ +package eniexamples + +import ( + "encoding/json" + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func BatchAddPrivateIp() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.EniBatchPrivateIpArgs{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + PrivateIpAddresses: []string{ // 弹性网卡私有IP列表 + "10.0.1.201", + "10.0.1.202", + }, + } + response, err := ENI_CLIENT.BatchAddPrivateIp(args) //批量添加弹性网卡私有IP + if err != nil { + panic(err) + } + r, err := json.Marshal(response) + fmt.Println(string(r)) +} diff --git a/bce-sdk-go/examples/eni/example_batch_delete_private_ip.go b/bce-sdk-go/examples/eni/example_batch_delete_private_ip.go new file mode 100644 index 0000000..dc8c64d --- /dev/null +++ b/bce-sdk-go/examples/eni/example_batch_delete_private_ip.go @@ -0,0 +1,32 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func BatchDeletePrivateIp() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.EniBatchPrivateIpArgs{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + PrivateIpAddresses: []string{ // 弹性网卡私有IP地址列表 + "10.0.1.201", + "10.0.1.202", + }, + } + err := ENI_CLIENT.BatchDeletePrivateIp(args) // 批量删除弹性网卡私有IP地址 + if err != nil { + panic(err) + } + fmt.Println("BatchDeletePrivateIp success!") +} diff --git a/bce-sdk-go/examples/eni/example_bind_eni_public_ip.go b/bce-sdk-go/examples/eni/example_bind_eni_public_ip.go new file mode 100644 index 0000000..3f1509f --- /dev/null +++ b/bce-sdk-go/examples/eni/example_bind_eni_public_ip.go @@ -0,0 +1,30 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func BindEniPublicIp() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.BindEniPublicIpArgs{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + PrivateIpAddress: "10.0.1.100", // 弹性网卡内网IP地址 + PublicIpAddress: "120.48.142.121", // 弹性网卡绑定的EIP地址 + } + err := ENI_CLIENT.BindEniPublicIp(args) // 弹性网卡绑定EIP + if err != nil { + panic(err) + } + fmt.Println("Bind eni public ip success") +} diff --git a/bce-sdk-go/examples/eni/example_create_eni.go b/bce-sdk-go/examples/eni/example_create_eni.go new file mode 100644 index 0000000..59a3454 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_create_eni.go @@ -0,0 +1,46 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func CreateEni() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + createEniArgs := &eni.CreateEniArgs{ + ClientToken: getClientToken(), + Name: "GO_SDK_TEST_CREATE", // 弹性网卡名称 + SubnetId: "sbn-d63m7t0bbwt5", // 子网ID + SecurityGroupIds: []string{ // 安全组ID列表 + "g-92600fd1grhr", // 安全组ID + }, + PrivateIpSet: []eni.PrivateIp{ // 弹性网卡内网IP列表 + { + Primary: true, // 弹性网卡内网IP是否为主IP + PrivateIpAddress: "10.0.1.108", // 弹性网卡内网IP + }, + }, + Ipv6PrivateIpSet: []eni.PrivateIp{ // 弹性网卡内网IPv6列表 + { + Primary: false, // 弹性网卡内网IPv6是否为主IP + PrivateIpAddress: "", // 弹性网卡内网IPv6 + }, + }, + Description: "go sdk test: create eni", // 弹性网卡描述 + } + + response, err := ENI_CLIENT.CreateEni(createEniArgs) // 创建eni + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/eni/example_delete_eni.go b/bce-sdk-go/examples/eni/example_delete_eni.go new file mode 100644 index 0000000..0b809a6 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_delete_eni.go @@ -0,0 +1,27 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func DeleteEni() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.DeleteEniArgs{ + EniId: "eni-efeq0vm3pu6e", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + } + err := ENI_CLIENT.DeleteEni(args) // 删除弹性网卡 + if err != nil { + panic(err) + } + fmt.Printf("Delete eni %s success\n", args.EniId) +} diff --git a/bce-sdk-go/examples/eni/example_delete_private_ip.go b/bce-sdk-go/examples/eni/example_delete_private_ip.go new file mode 100644 index 0000000..627e551 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_delete_private_ip.go @@ -0,0 +1,29 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func DeletePrivateIp() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.EniPrivateIpArgs{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + PrivateIpAddress: "10.0.1.108", // 私有IP地址 + } + err := ENI_CLIENT.DeletePrivateIp(args) // 删除弹性网卡私有IP地址 + if err != nil { + panic(err) + } + fmt.Println("DeletePrivateIp success") +} diff --git a/bce-sdk-go/examples/eni/example_detach_eni_instance.go b/bce-sdk-go/examples/eni/example_detach_eni_instance.go new file mode 100644 index 0000000..f49d439 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_detach_eni_instance.go @@ -0,0 +1,29 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func DetachEniInstance() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.EniInstance{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + InstanceId: "i-Dqf1k9ul", // 云主机ID + } + err := ENI_CLIENT.DetachEniInstance(args) // 弹性网卡卸载云主机 + if err != nil { + panic(err) + } + fmt.Println("DetachEniInstance success!") +} diff --git a/bce-sdk-go/examples/eni/example_get_eni_detail.go b/bce-sdk-go/examples/eni/example_get_eni_detail.go new file mode 100644 index 0000000..9121233 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_get_eni_detail.go @@ -0,0 +1,27 @@ +package eniexamples + +import ( + "encoding/json" + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func GetEniDetail() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + response, err := ENI_CLIENT.GetEniDetail("eni-477g9akswgjv") // 查询指定的弹性网卡 + if err != nil { + panic(err) + } + r, err := json.Marshal(response) + fmt.Println(string(r)) + +} diff --git a/bce-sdk-go/examples/eni/example_get_eni_status.go b/bce-sdk-go/examples/eni/example_get_eni_status.go new file mode 100644 index 0000000..96fbc8f --- /dev/null +++ b/bce-sdk-go/examples/eni/example_get_eni_status.go @@ -0,0 +1,20 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" +) + +func GetEniStatus() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + EniId := "eni-efeq0vm3pu6e" // 弹性网卡ID + response, err := ENI_CLIENT.GetEniStatus(EniId) // 获取弹性网卡状态 + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/eni/example_list_eni.go b/bce-sdk-go/examples/eni/example_list_eni.go new file mode 100644 index 0000000..9f776e3 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_list_eni.go @@ -0,0 +1,29 @@ +package eniexamples + +import ( + "encoding/json" + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" +) + +func ListEni() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.ListEniArgs{ + VpcId: "vpc-jm7h2j497ut7", // VPC ID + Name: "GO_SDK_TEST_CREATE", // 弹性网卡实例名称 + } + response, err := ENI_CLIENT.ListEni(args) // 查询弹性网卡列表 + if err != nil { + panic(err) + } + r, err := json.Marshal(response) + if err != nil { + panic(err) + } + fmt.Println(string(r)) +} diff --git a/bce-sdk-go/examples/eni/example_unbind_public_ip.go b/bce-sdk-go/examples/eni/example_unbind_public_ip.go new file mode 100644 index 0000000..66612d7 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_unbind_public_ip.go @@ -0,0 +1,29 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func UnBindEniPublicIp() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.UnBindEniPublicIpArgs{ + EniId: "eni-477g9akswgjv", // 弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + PublicIpAddress: "120.48.142.121", // 弹性网卡绑定的EIP + } + err := ENI_CLIENT.UnBindEniPublicIp(args) // 弹性网卡解绑EIP + if err != nil { + panic(err) + } + fmt.Println("UnBind eni public ip success") +} diff --git a/bce-sdk-go/examples/eni/example_update_eni.go b/bce-sdk-go/examples/eni/example_update_eni.go new file mode 100644 index 0000000..fc908c5 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_update_eni.go @@ -0,0 +1,30 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func UpdateEni() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.UpdateEniArgs{ + EniId: "eni-477g9akswgjv", // 待更新的eni id + ClientToken: getClientToken(), // 客户端Token + Name: "GO_SDK_TEST_UPDATE", // 更新后的名称 + Description: "go sdk test: update eni", // 更新后的描述 + } + err := ENI_CLIENT.UpdateEni(args) // 更新eni + if err != nil { + panic(err) + } + fmt.Printf("update eni %s success\n", args.EniId) +} diff --git a/bce-sdk-go/examples/eni/example_update_eni_esg.go b/bce-sdk-go/examples/eni/example_update_eni_esg.go new file mode 100644 index 0000000..f86575b --- /dev/null +++ b/bce-sdk-go/examples/eni/example_update_eni_esg.go @@ -0,0 +1,31 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func UpdateEniEnterpriseSecurityGroup() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.UpdateEniEnterpriseSecurityGroupArgs{ + EniId: "eni-477g9akswgjv", // 待更新的弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + EnterpriseSecurityGroupIds: []string{ // 待更新的企业安全组列表 + "esg-1atxb1iqd1e2", + }, + } + err := ENI_CLIENT.UpdateEniEnterpriseSecurityGroup(args) // 更新弹性网卡关联的企业安全组 + if err != nil { + panic(err) + } + fmt.Println("UpdateEniEnterpriseSecurityGroup success") +} diff --git a/bce-sdk-go/examples/eni/example_update_eni_sg.go b/bce-sdk-go/examples/eni/example_update_eni_sg.go new file mode 100644 index 0000000..e681522 --- /dev/null +++ b/bce-sdk-go/examples/eni/example_update_eni_sg.go @@ -0,0 +1,32 @@ +package eniexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/eni" + "github.com/baidubce/bce-sdk-go/util" +) + +func getClientToken() string { + return util.NewUUID() +} +func UpdateEniSecurityGroup() { + // 初始化AK/SK/Endpoint + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + ENI_CLIENT, _ := eni.NewClient(ak, sk, endpoint) // 初始化client + + args := &eni.UpdateEniSecurityGroupArgs{ + EniId: "eni-477g9akswgjv", // 待更新安全组的弹性网卡ID + ClientToken: getClientToken(), // 客户端Token + SecurityGroupIds: []string{ // 待更新的安全组ID列表 + "g-jpppuref4vbh", + "g-f8u628jzeq84", + }, + } + err := ENI_CLIENT.UpdateEniSecurityGroup(args) // 更新弹性网卡关联的安全组 + if err != nil { + panic(err) + } + fmt.Println("UpdateEniSecurityGroup success") +} diff --git a/bce-sdk-go/examples/esg/example_authorize_esgrule.go b/bce-sdk-go/examples/esg/example_authorize_esgrule.go new file mode 100644 index 0000000..31ae54a --- /dev/null +++ b/bce-sdk-go/examples/esg/example_authorize_esgrule.go @@ -0,0 +1,34 @@ +package esgexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/esg" +) + +// AuthorizeEsgRule 函数用于授权企业安全组规则。 +func AuthorizeEsgRule() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := esg.NewClient(ak, sk, endpoint) // 创建esg client + args := &esg.CreateEsgRuleArgs{ + Rules: []esg.EnterpriseSecurityGroupRule{ + { + Action: "deny", // 允许为allow, 不允许为deny + Direction: "ingress", // 方向 + Ethertype: "IPv4", // IP协议类型 + PortRange: "1-65535", // 端口范围 + Priority: 1000, // 优先级 + Protocol: "udp", // 传输协议 + Remark: "go sdk test", // 备注 + SourceIp: "all", // 源ip + }, + }, + EnterpriseSecurityGroupId: "Your EnterpriseSecurityGroupId", + ClientToken: "ClientToken", + } + err := client.CreateEsgRules(args) + if err != nil { + panic(err) + } + fmt.Print("AuthorizeEsgRule success!\n") +} diff --git a/bce-sdk-go/examples/esg/example_create_esg.go b/bce-sdk-go/examples/esg/example_create_esg.go new file mode 100644 index 0000000..a388b4e --- /dev/null +++ b/bce-sdk-go/examples/esg/example_create_esg.go @@ -0,0 +1,52 @@ +package esgexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/esg" +) + +// CreateESG函数用于创建企业安全组 +func CreateESG() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := esg.NewClient(ak, sk, endpoint) // 创建esg client + args := &esg.CreateEsgArgs{ + Name: "esgGoSdkTest", + Rules: []esg.EnterpriseSecurityGroupRule{ // 企业安全组规则 + { + Action: "deny", // 规则“允许”或者“拒绝”,取值‘allow’或者‘deny’,必填 + Direction: "ingress", // 指定方向,“出向”或者“入向”,取值“egress”或者“ingress”,必填 + Ethertype: "IPv4", // 指定IP协议类型v4/v6 + PortRange: "1-65535", // 指定端口范围 1-65535 + Priority: 1000, // 指定优先级 1-1000 + Protocol: "udp", // 指定协议,取值“udp”/"tcp"/"icmp"/"all",必填 + Remark: "go sdk test", // 指定备注 + SourceIp: "all", // 源(目的)IP地址,"all"代表全部地址,必填 + }, + { + Action: "allow", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "icmp", + Remark: "go sdk test", + SourceIp: "all", + }, + }, + Desc: "go sdk test", // 描述 + ClientToken: "ClientToken", + Tags: []model.TagModel{ // 标签 + { + TagKey: "test", + TagValue: "", + }, + }, + } + response, err := client.CreateEsg(args) // 创建企业安全组 + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/esg/example_delete_esg.go b/bce-sdk-go/examples/esg/example_delete_esg.go new file mode 100644 index 0000000..5caf81a --- /dev/null +++ b/bce-sdk-go/examples/esg/example_delete_esg.go @@ -0,0 +1,22 @@ +package esgexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/esg" +) + +// DeleteEsg 函数用于删除企业安全组(ESG)。 +func DeleteEsg() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := esg.NewClient(ak, sk, endpoint) // 创建esg client + args := &esg.DeleteEsgArgs{ + EnterpriseSecurityGroupId: "Your EnterpriseSecurityGroupId", // 企业安全组的id + ClientToken: "ClientToken", + } + err := client.DeleteEsg(args) // 删除esg + if err != nil { + panic(err) + } + fmt.Print("Delete Esg Success!") +} diff --git a/bce-sdk-go/examples/esg/example_delete_esgrule.go b/bce-sdk-go/examples/esg/example_delete_esgrule.go new file mode 100644 index 0000000..11748a2 --- /dev/null +++ b/bce-sdk-go/examples/esg/example_delete_esgrule.go @@ -0,0 +1,17 @@ +package esgexample + +import "github.com/baidubce/bce-sdk-go/services/esg" + +// DeleteESGRule 删除指定企业安全组规则 +func DeleteESGRule() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := esg.NewClient(ak, sk, endpoint) // 创建esg client + args := &esg.DeleteEsgRuleArgs{ + EnterpriseSecurityGroupRuleId: "Your EnterpriseSecurityGroupRuleId", // 企业安全组规则ID + } + err := client.DeleteEsgRule(args) + if err != nil { + panic(err) + } + println("DeleteESGRule success") +} diff --git a/bce-sdk-go/examples/esg/example_get_esglist.go b/bce-sdk-go/examples/esg/example_get_esglist.go new file mode 100644 index 0000000..1072bd8 --- /dev/null +++ b/bce-sdk-go/examples/esg/example_get_esglist.go @@ -0,0 +1,23 @@ +package esgexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/esg" +) + +// GetEsgList 函数用于查询企业安全组列表 +func GetEsgList() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := esg.NewClient(ak, sk, endpoint) // 创建esg client + args := &esg.ListEsgArgs{ + InstanceId: "instanceID", // 实例ID, 可查询实例关联的企业安全组列表。如需查询所有创建的企业安全组信息,不填写此参数 + Marker: "", // 批量获取列表的查询的起始位置,是一个由系统生成的字符串 + MaxKeys: 10, // 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 + } + response, err := client.ListEsg(args) // 查询企业安全组列表 + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/esg/example_update_esgrule.go b/bce-sdk-go/examples/esg/example_update_esgrule.go new file mode 100644 index 0000000..55fd364 --- /dev/null +++ b/bce-sdk-go/examples/esg/example_update_esgrule.go @@ -0,0 +1,24 @@ +package esgexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/esg" +) + +// UpdateESGRule 函数用于更新ESG规则 +func UpdateESGRule() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + client, _ := esg.NewClient(ak, sk, endpoint) // 创建esg client + args := &esg.UpdateEsgRuleArgs{ + Priority: 900, // 优先级 + Remark: "go sdk test update", // 备注 + ClientToken: "ClientToken", // token + EnterpriseSecurityGroupRuleId: "Your EnterpriseSecurityGroupRuleId", // 企业安全组规则ID + } + err := client.UpdateEsgRule(args) + if err != nil { + panic(err) + } + fmt.Print("UpdateESGRule success\n") +} diff --git a/bce-sdk-go/examples/et/example_create_et_channel_route_rule.go b/bce-sdk-go/examples/et/example_create_et_channel_route_rule.go new file mode 100644 index 0000000..3e0c5bf --- /dev/null +++ b/bce-sdk-go/examples/et/example_create_et_channel_route_rule.go @@ -0,0 +1,37 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +func CreateEtChannelRouteRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + CLIENT, _ := et.NewClient(ak, sk, endpoint) // 初始化client + + createEtChannelRouteRuleArgs := &et.CreateEtChannelRouteRuleArgs{ + EtId: "dcphy-gq65bz9ip712", // 专线ID + EtChannelId: "dedicatedconn-zy9t7n91k0iq", // 专线通道ID + ClientToken: getClientToken(), // 幂等性Token + IpVersion: 4, // IP协议类型 + DestAddress: "192.168.0.7/32", // 目标网段 + NextHopType: "etGateWay", // 下一跳类型 + NextHopId: "etGateWayId", // 下一跳实例ID + Description: "Your description", // 描述 + } + response, err := CLIENT.CreateEtChannelRouteRule(createEtChannelRouteRuleArgs) // 创建专线通道路由规则 + + if err != nil { + fmt.Printf("Failed to create et channel route rule, err: %v.\n", err) + return + } + fmt.Printf("Successfully create et channel route rule, response: %+v\n", *response) +} diff --git a/bce-sdk-go/examples/et/example_delete_et_channel_route_rule.go b/bce-sdk-go/examples/et/example_delete_et_channel_route_rule.go new file mode 100644 index 0000000..9d72eea --- /dev/null +++ b/bce-sdk-go/examples/et/example_delete_et_channel_route_rule.go @@ -0,0 +1,33 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +func DeleteEtChannelRouteRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + CLIENT, _ := et.NewClient(ak, sk, endpoint) // 初始化client + + deleteEtChannelRouteRuleArgs := &et.DeleteEtChannelRouteRuleArgs{ + ClientToken: getClientToken(), // 幂等性Token + EtId: "dcphy-gq65bz9ip712", // 专线ID + EtChannelId: "dedicatedconn-zy9t7n91k0iq", // 专线通道ID + RouteRuleId: "dcrr-5afcf643-94e", // 专线通道路由规则ID + } + err := CLIENT.DeleteEtChannelRouteRule(deleteEtChannelRouteRuleArgs) // 删除专线通道路由规则 + + if err != nil { + fmt.Printf("Failed to delete et channel route rule, err: %+v.\n", err) + return + } + fmt.Println("Successfully delete et channel route rule.") +} diff --git a/bce-sdk-go/examples/et/example_disable_et_channel_ipv6.go b/bce-sdk-go/examples/et/example_disable_et_channel_ipv6.go new file mode 100644 index 0000000..ed08bd2 --- /dev/null +++ b/bce-sdk-go/examples/et/example_disable_et_channel_ipv6.go @@ -0,0 +1,32 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +func DisableEtChannelIPv6() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + CLIENT, _ := et.NewClient(ak, sk, endpoint) // 初始化client + + disableEtChannelIPv6Args := &et.DisableEtChannelIPv6Args{ + ClientToken: getClientToken(), // 幂等性Token + EtId: "dcphy-gq65bz9ip712", // 专线ID + EtChannelId: "dedicatedconn-zy9t7n91k0iq", // 专线通道ID + } + err := CLIENT.DisableEtChannelIPv6(disableEtChannelIPv6Args) // 关闭专线通道IPv6功能 + + if err != nil { + fmt.Printf("Failed to enable et channel IPv6, err: %v.\n", err) + return + } + fmt.Println("Successfully disable et channel IPv6.") +} diff --git a/bce-sdk-go/examples/et/example_list_et_channel_route_rules.go b/bce-sdk-go/examples/et/example_list_et_channel_route_rules.go new file mode 100644 index 0000000..ff799a0 --- /dev/null +++ b/bce-sdk-go/examples/et/example_list_et_channel_route_rules.go @@ -0,0 +1,25 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" +) + +func ListEtChannelRouteRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + CLIENT, _ := et.NewClient(ak, sk, endpoint) // 初始化client + + listEtChannelRouteRuleArgs := &et.ListEtChannelRouteRuleArgs{ + EtId: "dcphy-gq65bz9ip712", // 专线ID + EtChannelId: "dedicatedconn-zy9t7n91k0iq", // 专线通道ID + } + response, err := CLIENT.ListEtChannelRouteRule(listEtChannelRouteRuleArgs) // 查询专线通道路由规则 + + if err != nil { + fmt.Printf("Failed to list et channel route rule, err: %v.\n", err) + return + } + fmt.Printf("Successfully list et channel route rule, response: %+v.\n", *response) +} diff --git a/bce-sdk-go/examples/et/example_update_et_channel_route_rule.go b/bce-sdk-go/examples/et/example_update_et_channel_route_rule.go new file mode 100644 index 0000000..bf1f5aa --- /dev/null +++ b/bce-sdk-go/examples/et/example_update_et_channel_route_rule.go @@ -0,0 +1,35 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +func UpdateEtChannelRouteRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + CLIENT, _ := et.NewClient(ak, sk, endpoint) // 初始化client + + updateEtChannelRouteRuleArgs := &et.UpdateEtChannelRouteRuleArgs{ + ClientToken: getClientToken(), // 幂等性Token + EtId: "dcphy-gq65bz9ip712", // 专线ID + EtChannelId: "dedicatedconn-zy9t7n91k0iq", // 专线通道ID + RouteRuleId: "dcrr-5afcf643-94e", // 专线通道路由规则ID + Description: "route_2", // 描述信息 + + } + err := CLIENT.UpdateEtChannelRouteRule(updateEtChannelRouteRuleArgs) // 修改专线通道路由规则 + + if err != nil { + fmt.Printf("Failed to update et channel route rule, err: %+v.\n", err) + return + } + fmt.Println("Successfully update et channel route rule.") +} diff --git a/bce-sdk-go/examples/et/examples_create_et.go b/bce-sdk-go/examples/et/examples_create_et.go new file mode 100644 index 0000000..666a9b6 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_create_et.go @@ -0,0 +1,42 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// CreateEtDcphy +func CreateEtDcphy() { + client, err := et.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &CreateEtDcphyArgs { + ClientToken: getClientToken(), // 请求标识 + Name: "Your Et name", // 专线名称 + Description: "Your Et description" // 描述 + Isp: "ISP_CMCC", // 运营商 + IntfType: "1G", // 物理端口规格 + ApType: "SINGLE", // 线路类型 + ApAddr: "BJYZ", // 接入点 + UserName: "Your name", // 用户名称 + UserPhone: "Your Phone", // 用户手机号码 + UserEmail: "Your Email", // 用户邮箱 + UserIdc: "Your Idc", // 对端地址 + } + + if err = client.CreateEtDcphy(args); err != nil { + fmt.Printf("Failed to create a new et, err: %v.\n", err) + return + } + fmt.Println("Successfully create a new et.") +} \ No newline at end of file diff --git a/bce-sdk-go/examples/et/examples_create_et_channel.go b/bce-sdk-go/examples/et/examples_create_et_channel.go new file mode 100644 index 0000000..8674dc4 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_create_et_channel.go @@ -0,0 +1,47 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// CreateEtChannel +func CreateEtChannel() { + client, err := et.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &CreateEtChannelArgs{ + ClientToken: getClientToken(), + EtId: "Your EtId", // 专线ID + AuthorizedUsers: []string{"Your AuthorizedUsers"}, // 分配对象 + Description: "Your Description", // 描述 + BaiduAddress: "Your BaiduAddress", // 云端网络互联IP + Name: "Your Channel Name", // 通道名称 + Networks: []string{"Your Networks"}, // 路由参数 + CustomerAddress: "Your CustomerAddress", // IDC互联IP + RouteType: "Your RouteType", // 路由协议 + VlanId: "Your Vlan ID", // VLAN ID + BgpAsn: "Your Bgp Asn", // BGP ASN + BgpKey: "Your Bgp Key", // BGP 密钥 + EnableIpv6: 0, // IPv6功能是否开启 + BaiduIpv6Address: "Your BaiduIpv6Address", // 云端网络侧IPv6互联地址 + CustomerIpv6Address: "Your CustomerIpv6Address", // IDC侧IPv6互联地址 + Ipv6Networks: []string{"Your Ipv6Networks"}, // IPv6路由参数 + } + + if err = client.CreateEtChannel(args); err != nil { + fmt.Printf("Failed to create et channel, err: %v.\n", err) + return + } + fmt.Println("Successfully create et channel.") +} diff --git a/bce-sdk-go/examples/et/examples_delete_et_channel.go b/bce-sdk-go/examples/et/examples_delete_et_channel.go new file mode 100644 index 0000000..e0cf692 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_delete_et_channel.go @@ -0,0 +1,33 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// DeleteEtChannel +func DeleteEtChannel() { + client, err := et.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + args := &et.DeleteEtChannelArgs{ + ClientToken: getClientToken(), // client token + EtId: "Your EtId", // et id + EtChannelId: "Your EtChannelId", // et channel id + } + + if err = client.DeleteEtChannel(args); err != nil { + fmt.Printf("Failed to delete et channel, err: %v.\n", err) + return + } + fmt.Println("Successfully delete et channel.") +} diff --git a/bce-sdk-go/examples/et/examples_enable_channel_ipv6.go b/bce-sdk-go/examples/et/examples_enable_channel_ipv6.go new file mode 100644 index 0000000..ce9a253 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_enable_channel_ipv6.go @@ -0,0 +1,39 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// EnableEtChannelIPv6 +func EnableEtChannelIPv6() { + client, err := et.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &et.EnableEtChannelIPv6Args{ + ClientToken: getClientToken(), // client token + EtId: "Your EtId", // et id + EtChannelId: "Your EtChannelId", // et channel id + Result: et.EnableEtChannelIPv6Result{ // enable et channel ipv6 result + BaiduIpv6Address: "Your BaiduIpv6Address", // baidu ipv6 address + Ipv6Networks: []string{"Your Ipv6Networks"}, // ipv6 networks + CustomerIpv6Address: "Your CustomerIpv6Address", // customer ipv6 address + }, + } + + if err := client.EnableEtChannelIPv6(args); err != nil { + fmt.Printf("Failed to enable et channel IPv6, err: %v.\n", err) + return + } + fmt.Println("Successfully enable et channel IPv6.") +} diff --git a/bce-sdk-go/examples/et/examples_get_et_channel.go b/bce-sdk-go/examples/et/examples_get_et_channel.go new file mode 100644 index 0000000..f14523e --- /dev/null +++ b/bce-sdk-go/examples/et/examples_get_et_channel.go @@ -0,0 +1,32 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// GetEtChannel +func GetEtChannel() { + client, err := et.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + args := &et.GetEtChannelArgs{ + ClientToken: getClientToken(), // client token + EtId: "Your Et ID", // et id + } + response, err := client.GetEtChannel(args) + if err != nil { + fmt.Printf("Failed to get et channel, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/et/examples_list_et.go b/bce-sdk-go/examples/et/examples_list_et.go new file mode 100644 index 0000000..36be906 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_list_et.go @@ -0,0 +1,35 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// ListEtDcphy +func ListEtDcphy() { + client, err := et.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &ListEtDcphyArgs{ + Marker: "", // 批量获取列表的查询的起始位置 + MaxKeys: 1000, // 每页包含的最大数量,最大数量不超过1000,缺省值为1000 + Status: "", // 专线状态 + } + + response, err := client.ListEtDcphy(args) + if err != nil { + fmt.Printf("Failed to get ets, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/et/examples_list_et_detail.go b/bce-sdk-go/examples/et/examples_list_et_detail.go new file mode 100644 index 0000000..ed77306 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_list_et_detail.go @@ -0,0 +1,33 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// ListEtDcphyDetail +func ListEtDcphyDetail() { + client, err := et.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &ListEtDcphyDetailArgs{ + DcphyId: "Your Et Id", // 专线ID + } + + response, err := client.ListEtDcphyDetail(args) + if err != nil { + fmt.Printf("Failed to get et's detail, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/et/examples_recommit_et_channel.go b/bce-sdk-go/examples/et/examples_recommit_et_channel.go new file mode 100644 index 0000000..34d4b72 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_recommit_et_channel.go @@ -0,0 +1,49 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// RecommitEtChannel +func RecommitEtChannel() { + client, err := et.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &et.RecommitEtChannelArgs{ + ClientToken: getClientToken(), // client token + EtId: "Your EtId", // et id + EtChannelId: "Your EtChannelId", // et channel id + Result: et.RecommitEtChannelResult{ // recommit et channel result + AuthorizedUsers: []string{"Your AuthorizedUsers"}, // authorized users + Description: "Your Description", // description + BaiduAddress: "Your BaiduAddress", // baidu address + Name: "Your Name", // name + Networks: []string{"Your Networks"}, // networks + CustomerAddress: "Your CustomerAddress", // customer address + RouteType: "Your RouteType", // route type + VlanId: "Your Vlan ID", // vlan id + Status: "Your Status", // status + EnableIpv6: 0, // enable ipv6 + BaiduIpv6Address: "Your BaiduIpv6Address", // baidu ipv6 address + Ipv6Networks: []string{"Your Ipv6Networks"}, // ipv6 networks + CustomerIpv6Address: "Your CustomerIpv6Address", // customer ipv6 address + }, + } + + if err := client.RecommitEtChannel(args); err != nil { + fmt.Printf("Failed to recommit et channel, err: %v.\n", err) + return + } + fmt.Println("Successfully recommit et channel.") +} diff --git a/bce-sdk-go/examples/et/examples_update_et.go b/bce-sdk-go/examples/et/examples_update_et.go new file mode 100644 index 0000000..d184e96 --- /dev/null +++ b/bce-sdk-go/examples/et/examples_update_et.go @@ -0,0 +1,36 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// UpdateEtDcphy +func UpdateEtDcphy() { + client, err := et.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + + args := &UpdateEtDcphyArgs { + Name: "Your Et name", // 专线名称 + Description: "Your Et description" // 描述 + UserName: "Your name", // 用户名称 + UserPhone: "Your Phone", // 用户手机号码 + UserEmail: "Your Email", // 用户邮箱 + } + + if err = client.UpdateEtDcphy("Your Et Id", args); err != nil { + fmt.Printf("Failed to update et, err: %v.\n", err) + return + } + fmt.Println("Successfully update et.") +} \ No newline at end of file diff --git a/bce-sdk-go/examples/et/examples_update_et_channel.go b/bce-sdk-go/examples/et/examples_update_et_channel.go new file mode 100644 index 0000000..b3d801a --- /dev/null +++ b/bce-sdk-go/examples/et/examples_update_et_channel.go @@ -0,0 +1,37 @@ +package etexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/et" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// UpdateEtChannel +func UpdateEtChannel() { + client, err := et.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + args := &et.UpdateEtChannelArgs{ + ClientToken: getClientToken(), // client token + EtId: "Your EtId", // et id + EtChannelId: "Your EtChannelId", // et channel id + Result: et.UpdateEtChannelResult{ // update et channel result + Name: "Your Name", // et channel name + Description: "Your Description", // et channel description + }, + } + + if err = client.UpdateEtChannel(args); err != nil { + fmt.Printf("Failed to update et channel, err: %v.\n", err) + return + } + fmt.Println("Successfully update et channel.") +} diff --git a/bce-sdk-go/examples/etGateway/examples_bind_et.go b/bce-sdk-go/examples/etGateway/examples_bind_et.go new file mode 100644 index 0000000..bc34c16 --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_bind_et.go @@ -0,0 +1,35 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// BindEt 函数用于绑定ET网关 +func BindEt() { + client, err := etGateway.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et gateway client, err: %v.\n", err) + return + } + + args := etGateway.BindEtArgs{ + EtId: "et-aaccd", + ClientToken: getClientToken(), + EtGatewayId: "dcgw-iiyc0ers2qx4", + ChannelId: "sdxs", + LocalCidrs: []string{"10.240.0.0/16", "192.168.3.0/24"}, + } + err = client.BindEt(&args) + if err != nil { + fmt.Printf("Failed to bind et, err: %v.\n", err) + return + } + fmt.Println("Successfully bind et.") +} diff --git a/bce-sdk-go/examples/etGateway/examples_create_et_gateway.go b/bce-sdk-go/examples/etGateway/examples_create_et_gateway.go new file mode 100644 index 0000000..c3ced05 --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_create_et_gateway.go @@ -0,0 +1,39 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// CreateEtGateway 函数用于创建ET网关 +func CreateEtGateway() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := etGateway.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &etGateway.CreateEtGatewayArgs{ + Name: "test-et-gateway", + VpcId: "vpc-2pa2x0bjt26i", + Description: "test create et gateway", + Speed: 100, + EtId: "et-aaccd", + ChannelId: "sdxs", + LocalCidrs: []string{"10.240.0.0/16", "192.168.3.0/24"}, + ClientToken: getClientToken(), + } + result, err := client.CreateEtGateway(args) + if err != nil { + fmt.Println("create et gateway error: ", err) + return + } + + fmt.Println("create et gateway success, et gateway id: ", result.EtGatewayId) +} diff --git a/bce-sdk-go/examples/etGateway/examples_create_health_check.go b/bce-sdk-go/examples/etGateway/examples_create_health_check.go new file mode 100644 index 0000000..9ca98bd --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_create_health_check.go @@ -0,0 +1,40 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// CreateHealthCheck 函数用于创建健康检查 +func CreateHealthCheck() { + client, err := etGateway.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et gateway client, err: %v.\n", err) + return + } + auto := true + args := &etGateway.CreateHealthCheckArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-iiyc0ers2qx4", + HealthCheckSourceIp: "192.168.0.1", + HealthCheckType: etGateway.HEALTH_CHECK_ICMP, + HealthCheckPort: 80, + HealthCheckInterval: 3, + HealthThreshold: 2, + UnhealthThreshold: 2, + AutoGenerateRouteRule: &auto, + } + + err = client.CreateHealthCheck(args) + if err != nil { + fmt.Printf("Failed to create health check, err: %v.\n", err) + return + } + fmt.Printf("Create health check success.\n") +} diff --git a/bce-sdk-go/examples/etGateway/examples_delete_et_gateway.go b/bce-sdk-go/examples/etGateway/examples_delete_et_gateway.go new file mode 100644 index 0000000..fc9eb08 --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_delete_et_gateway.go @@ -0,0 +1,27 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// DeleteEtGateway 删除指定网关 +func DeleteEtGateway() { + client, err := etGateway.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et gateway client, err: %v.\n", err) + return + } + + if err = client.DeleteEtGateway("dcgw-iiyc0ers2qx4", getClientToken()); err != nil { + fmt.Printf("Failed to delete et gateway, err: %v.\n", err) + return + } + fmt.Println("Successfully delete et gateway.") +} diff --git a/bce-sdk-go/examples/etGateway/examples_get_et_gateway_detail.go b/bce-sdk-go/examples/etGateway/examples_get_et_gateway_detail.go new file mode 100644 index 0000000..4bf9b7f --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_get_et_gateway_detail.go @@ -0,0 +1,23 @@ +package etgatewayexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/etGateway" +) + +// GetEtGatewayDetail get et gateway detail. +func GetEtGatewayDetail() { + client, err := etGateway.NewClient("Your AK", "Your SK", "bcc.bj.baidubce.com") + if err != nil { + fmt.Printf("Failed to new et client, err: %v.\n", err) + return + } + etGatewayId := "dcgw-iiyc0ers2qx4" + response, err := client.GetEtGatewayDetail(etGatewayId) + if err != nil { + fmt.Printf("Failed to get et channel, err: %v.\n", err) + return + } + fmt.Printf("%+v\n", *response) +} diff --git a/bce-sdk-go/examples/etGateway/examples_list_et_gateway_entry.go b/bce-sdk-go/examples/etGateway/examples_list_et_gateway_entry.go new file mode 100644 index 0000000..5d80bdd --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_list_et_gateway_entry.go @@ -0,0 +1,51 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" +) + +// ListEtGatewayDetail 函数用于获取指定VPC下的ET网关列表 +func ListEtGatewayDetail() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := etGateway.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &etGateway.ListEtGatewayArgs{ + VpcId: "vpc-2pa2x0bjt26i", // vpc id + EtGatewayId: "dcgw-iiyc0ers2qx4", // et gateway id + Name: "test-et-gateway", // et gateway name + Status: "running", // et gateway status + Marker: "20", // 起始偏移量 + MaxKeys: 1000, // 最大返回数量 + } + result, err := client.ListEtGateway(args) + if err != nil { + fmt.Println("list et gateway error: ", err) + return + } + + // 返回标记查询的起始位置 + fmt.Println("et gateway list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("et gateway list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("et gateway list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("et gateway list maxKeys: ", result.MaxKeys) + // 获取et gateway列表 + for _, etGateway := range result.EtGateways { + fmt.Println("et gateway id: ", etGateway.EtGatewayId) + fmt.Println("et gateway name: ", etGateway.Name) + fmt.Println("et gateway status: ", etGateway.Status) + fmt.Println("et gateway vpc id: ", etGateway.VpcId) + fmt.Println("et gateway create time: ", etGateway.CreateTime) + fmt.Println("et gateway etGateway description: ", etGateway.Description) + fmt.Println("et gateway etGateway et id: ", etGateway.EtId) + fmt.Println("et gateway etGateway speed: ", etGateway.Speed) + fmt.Println("et gateway etGateway channel id: ", etGateway.ChannelId) + fmt.Println("et gateway etGateway channel local cidrs: ", etGateway.LocalCidrs) + } +} diff --git a/bce-sdk-go/examples/etGateway/examples_unbind_et.go b/bce-sdk-go/examples/etGateway/examples_unbind_et.go new file mode 100644 index 0000000..e7bd466 --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_unbind_et.go @@ -0,0 +1,28 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// UnBindEt 函数用于解绑ET。 +func UnBindEt() { + client, err := etGateway.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et gateway client, err: %v.\n", err) + return + } + + err = client.UnBindEt("dcgw-iiyc0ers2qx4", getClientToken()) + if err != nil { + fmt.Printf("Failed to unbind et, err: %v.\n", err) + return + } + fmt.Printf("Unbind et success.\n") +} diff --git a/bce-sdk-go/examples/etGateway/examples_update_et_gateway.go b/bce-sdk-go/examples/etGateway/examples_update_et_gateway.go new file mode 100644 index 0000000..68c4e64 --- /dev/null +++ b/bce-sdk-go/examples/etGateway/examples_update_et_gateway.go @@ -0,0 +1,36 @@ +package etgatewayexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/etGateway" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +// updateEtGateway 更新etGateway的函数 +func updateEtGateway() { + client, err := etGateway.NewClient("Your AK", "Your SK", "Your endpoint") // 初始化ak、sk和endpoint + if err != nil { + fmt.Printf("Failed to new et gateway client, err: %v.\n", err) + return + } + + // 更新etGateway + args := &etGateway.UpdateEtGatewayArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-iiyc0ers2qx4", + Name: "test-et-gateway", + Description: "test update et gateway", + Speed: 10, + LocalCidrs: []string{"10.240.0.0/16", "192.168.3.0/24"}, + } + if err = client.UpdateEtGateway(args); err != nil { + fmt.Printf("Failed to update et gateway, err: %v.\n", err) + return + } + fmt.Println("Successfully update et gateway.") +} diff --git a/bce-sdk-go/examples/havip/example_create_havip.go b/bce-sdk-go/examples/havip/example_create_havip.go new file mode 100644 index 0000000..7fa039d --- /dev/null +++ b/bce-sdk-go/examples/havip/example_create_havip.go @@ -0,0 +1,24 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func CreateHaVip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + createHaVipArgs := &havip.CreateHaVipArgs{ + PrivateIpAddress: "0.0.0.0", // 指定的IP地址,为""表示自动分配IP地址 + Name: "havip_sdk_test", // 高可用虚拟IP的名称 + SubnetId: "sbn-id", // 高可用虚拟IP所属的子网ID + } + response, err := HAVIP_CLIENT.CreateHaVip(createHaVipArgs) // 创建havip + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_delete_havip.go b/bce-sdk-go/examples/havip/example_delete_havip.go new file mode 100644 index 0000000..30f5889 --- /dev/null +++ b/bce-sdk-go/examples/havip/example_delete_havip.go @@ -0,0 +1,22 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func DeleteHaVip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + deleteHaVipArgs := &havip.DeleteHaVipArgs{ + HaVipId: "havip_id", // 高可用虚拟IP的ID + } + response, err := HAVIP_CLIENT.DeleteHaVip(deleteHaVipArgs) // 删除havip + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_get_havip_detail.go b/bce-sdk-go/examples/havip/example_get_havip_detail.go new file mode 100644 index 0000000..c72aa45 --- /dev/null +++ b/bce-sdk-go/examples/havip/example_get_havip_detail.go @@ -0,0 +1,22 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func GetHaVipDetail() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + haVipArgs := &havip.HaVip{ + HaVipId: "havip_id", // 高可用虚拟IP的ID + } + response, err := HAVIP_CLIENT.GetHaVipDetail(haVipArgs) // 查询指定的高可用虚拟IP + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_havip_attach_instance.go b/bce-sdk-go/examples/havip/example_havip_attach_instance.go new file mode 100644 index 0000000..2fc5591 --- /dev/null +++ b/bce-sdk-go/examples/havip/example_havip_attach_instance.go @@ -0,0 +1,24 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func HaVipAttachInstance() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + haVipInstanceArgs := &havip.HaVipInstanceArgs{ + haVipId: "havip_id", // 高可用虚拟IP的ID + instanceIds: []string{"Your instance ids"}, // 绑定的实例ID列表,列表长度不大于5 + instanceType: "bcc", // 绑定的实例类型,"SERVER"表示云服务器(BCC/BBC/DCC),"ENI"表示弹性网卡 + } + response, err := HAVIP_CLIENT.HaVipAttachInstance(haVipInstanceArgs) // 高可用虚拟IP绑定实例 + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_havip_bind_public_ip.go b/bce-sdk-go/examples/havip/example_havip_bind_public_ip.go new file mode 100644 index 0000000..de6eb7c --- /dev/null +++ b/bce-sdk-go/examples/havip/example_havip_bind_public_ip.go @@ -0,0 +1,23 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func HaVipBindPublicIp() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + haVipBindPublicIpArgs := &havip.HaVipBindPublicIpArgs{ + haVipId: "havip_id", // 高可用虚拟IP的ID + publicIpAddress: "0.0.0.0", // 弹性公网IP的地址 + } + response, err := HAVIP_CLIENT.HaVipBindPublicIp(haVipBindPublicIpArgs) // 高可用虚拟IP绑定EIP + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_havip_detach_instance.go b/bce-sdk-go/examples/havip/example_havip_detach_instance.go new file mode 100644 index 0000000..771e083 --- /dev/null +++ b/bce-sdk-go/examples/havip/example_havip_detach_instance.go @@ -0,0 +1,24 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func HaVipDetachInstance() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + haVipInstanceArgs := &havip.HaVipInstanceArgs{ + haVipId: "havip_id", // 高可用虚拟IP的ID + instanceIds: []string{"Your instance ids"}, // 绑定的实例ID列表,列表长度不大于5 + instanceType: "bcc", // 绑定的实例类型,"SERVER"表示云服务器(BCC/BBC/DCC),"ENI"表示弹性网卡 + } + response, err := HAVIP_CLIENT.HaVipDetachhInstance(haVipInstanceArgs) // 高可用虚拟IP解绑实例 + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_havip_unbind_public_ip copy.go b/bce-sdk-go/examples/havip/example_havip_unbind_public_ip copy.go new file mode 100644 index 0000000..dc8ed20 --- /dev/null +++ b/bce-sdk-go/examples/havip/example_havip_unbind_public_ip copy.go @@ -0,0 +1,22 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func HaVipUnbindPublicIp() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + haVipUnbindPublicIpArgs := &havip.HaVipUnbindPublicIpArgs{ + haVipId: "havip_id", // 高可用虚拟IP的ID + } + response, err := HAVIP_CLIENT.HaVipUnbindPublicIp(haVipUnbindPublicIpArgs) // 高可用虚拟IP解绑EIP + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_list_havip.go b/bce-sdk-go/examples/havip/example_list_havip.go new file mode 100644 index 0000000..7a464b2 --- /dev/null +++ b/bce-sdk-go/examples/havip/example_list_havip.go @@ -0,0 +1,22 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func ListHaVip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + listHaVipArgs := &havip.ListHaVipArgs{ + VpcId: "vpc_id", // 高可用虚拟IP所属的VPC ID + } + response, err := HAVIP_CLIENT.ListHaVip(listHaVipArgs) // 查询高可用虚拟IP列表 + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/havip/example_update_havip.go b/bce-sdk-go/examples/havip/example_update_havip.go new file mode 100644 index 0000000..a023a6b --- /dev/null +++ b/bce-sdk-go/examples/havip/example_update_havip.go @@ -0,0 +1,23 @@ +package havipexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/havip" +) + +func UpdateHaVip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + HAVIP_CLIENT, _ := havip.NewClient(ak, sk, endpoint) // 初始化client + + updateHaVipArgs := &havip.UpdateHaVipArgs{ + HaVipId: "havip_id", // 高可用虚拟IP的ID + Name: "havip_name", // 高可用虚拟IP的名称 + } + response, err := HAVIP_CLIENT.UpdateHaVip(updateHaVipArgs) // 更新高可用虚拟IP + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/ipv6blb/example_create_loadbalancer.go b/bce-sdk-go/examples/ipv6blb/example_create_loadbalancer.go new file mode 100644 index 0000000..59a854a --- /dev/null +++ b/bce-sdk-go/examples/ipv6blb/example_create_loadbalancer.go @@ -0,0 +1,44 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 ipv6blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func CreateLoadBalancer() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + createBlbArgs := &blb.CreateLoadBalancerArgs{ + ClientToken: "client token", // token + Name: "TestSDK-BLB", // blb名称 + VpcId: "vpc id", // VPC ID + SubnetId: "subnet id", // 子网ID + Type: "ipv6", // Ipv6类型 + } + + response, err := BlbClient.CreateLoadBalancer(createBlbArgs) // 创建blb + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/ipv6blb/example_describe_loadbalancers.go b/bce-sdk-go/examples/ipv6blb/example_describe_loadbalancers.go new file mode 100644 index 0000000..7ed6205 --- /dev/null +++ b/bce-sdk-go/examples/ipv6blb/example_describe_loadbalancers.go @@ -0,0 +1,40 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 ipv6blbexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/blb" +) + +func DescribeLoadBalancers() { + ak, sk, endpoint := "Your AK", "Your SK", "Your endpoint" + + BlbClient, _ := blb.NewClient(ak, sk, endpoint) // 初始化client + + describeBlbsArgs := &blb.DescribeLoadBalancersArgs{ + Type: "ipv6", // Ipv6类型 + } + + response, err := BlbClient.DescribeLoadBalancers(describeBlbsArgs) //查询blb实例列表 + + if err != nil { + panic(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/lbdc/example_create_lbdc.go b/bce-sdk-go/examples/lbdc/example_create_lbdc.go new file mode 100644 index 0000000..f898dba --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_create_lbdc.go @@ -0,0 +1,43 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func CreateLbdc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + args := &lbdc.CreateLbdcArgs{ + Name: "name", + Type: "4Layer", + CcuCount: 4, + Billing: &lbdc.Billing{ + PaymentTiming: "Prepaid", + Reservation: &lbdc.Reservation{ + ReservationLength: 1, + }, + }, + } + res, err := client.CreateLbdc(args) // 创建lbdc + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/lbdc/example_get_bound_blb_list_of_lbdc.go b/bce-sdk-go/examples/lbdc/example_get_bound_blb_list_of_lbdc.go new file mode 100644 index 0000000..e7966ea --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_get_bound_blb_list_of_lbdc.go @@ -0,0 +1,33 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func GetBoundBlbListOfLbdc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + lbdcId := "lbdc id" + res, err := client.GetBoundBlBListOfLbdc(lbdcId) // 获取lbdc绑定的lb列表 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/lbdc/example_get_lbdc_detail.go b/bce-sdk-go/examples/lbdc/example_get_lbdc_detail.go new file mode 100644 index 0000000..7e74173 --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_get_lbdc_detail.go @@ -0,0 +1,33 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func GetLbdcDetail() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + lbdcId := "lbdc id" + res, err := client.GetLbdcDetail(lbdcId) // 获取lbdc详情 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/lbdc/example_list_lbdc.go b/bce-sdk-go/examples/lbdc/example_list_lbdc.go new file mode 100644 index 0000000..0910d3c --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_list_lbdc.go @@ -0,0 +1,35 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func ListLbdc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + args := &lbdc.ListLbdcArgs{ + Id: "lbdc id", + } + res, err := client.ListLbdc(args) // 获取lbdc列表 + if err != nil { + fmt.Println(err) + } + fmt.Println(res) +} diff --git a/bce-sdk-go/examples/lbdc/example_renew_lbdc.go b/bce-sdk-go/examples/lbdc/example_renew_lbdc.go new file mode 100644 index 0000000..c1c57a9 --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_renew_lbdc.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func RenewLbdc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + args := &lbdc.RenewLbdcArgs{ + Id: "lbdc id", + Billing: &lbdc.BillingForRenew{ + Reservation: &lbdc.Reservation{ + ReservationLength: 3, + }, + }, + } + err := client.RenewLbdc(args) // 续费lbdc + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/lbdc/example_update_lbdc.go b/bce-sdk-go/examples/lbdc/example_update_lbdc.go new file mode 100644 index 0000000..e92685f --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_update_lbdc.go @@ -0,0 +1,39 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func UpdateLbdc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + name, description := "update_name", "desc" + args := &lbdc.UpdateLbdcArgs{ + Id: "lbdc id", + UpdateLbdcBody: &lbdc.UpdateLbdcBody{ + Name: &name, + Description: &description, + }, + } + err := client.UpdateLbdc(args) // 更新lbdc + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/lbdc/example_upgrade_lbdc.go b/bce-sdk-go/examples/lbdc/example_upgrade_lbdc.go new file mode 100644 index 0000000..0b9d208 --- /dev/null +++ b/bce-sdk-go/examples/lbdc/example_upgrade_lbdc.go @@ -0,0 +1,35 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 lbdcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/lbdc" +) + +func UpgradeLbdc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := lbdc.NewClient(ak, sk, endpoint) // 初始化client + + args := lbdc.UpgradeLbdcArgs{ + Id: "lbdc id", + CcuCount: 1, + } + err := client.UpgradeLbdc(&args) // 升级lbdc + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/examples/localDns/example_add_record.go b/bce-sdk-go/examples/localDns/example_add_record.go new file mode 100644 index 0000000..6acc234 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_add_record.go @@ -0,0 +1,42 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func AddRecord() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + zoneId := "Your Zone Id" + args := &localDns.AddRecordRequest{ + ClientToken: getClientToken(), // 幂等性 token + Rr: "Your record name, such as www.test.com", // 记录名称 + Value: "Your record value, such as 192.168.0.1", // 记录值 + Type: "Your record type, such as A", // 解析记录类型,目前支持A, AAAA,CNAME, TXT, MX, PTR, SRV + Ttl: 60, // 生存时间,值为[5,24*3600],默认为60 + Priority: 0, // MX记录的优先级,取值范围:[0,100]。记录类型为MX记录时,此参数必选。 + Description: "You record description", // 描述 + } + result, err := client.AddRecord(zoneId, args) + if err != nil { + fmt.Println("create record err:", err) + return + } + + fmt.Println("record id: ", result.RecordId) + fmt.Println("create record success") +} diff --git a/bce-sdk-go/examples/localDns/example_bind_vpcs.go b/bce-sdk-go/examples/localDns/example_bind_vpcs.go new file mode 100644 index 0000000..7496159 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_bind_vpcs.go @@ -0,0 +1,36 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func BindVpcs() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + zoneId := "Your Zone Id" + args := &localDns.BindVpcRequest{ + ClientToken: getClientToken(), // 客户端 token + Region: "Your vpc region", // region + VpcIds: []string{"Your vpc1", "Your vpc2"}, // 该 region 下需要绑定的 vpc 列表 + } + if err := client.BindVpc(zoneId, args); err != nil { + fmt.Println("bind vpcs err:", err) + return + } + + fmt.Println("bind vpcs success") +} diff --git a/bce-sdk-go/examples/localDns/example_create_private_zone.go b/bce-sdk-go/examples/localDns/example_create_private_zone.go new file mode 100644 index 0000000..08625e2 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_create_private_zone.go @@ -0,0 +1,36 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func CreatePrivateZone() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + args := &localDns.CreatePrivateZoneRequest{ + ClientToken: getClientToken(), // 请求标识 + ZoneName: "Your Zone Name", // 私有域名称 + } + result, err := client.CreatePrivateZone(args) + if err != nil { + fmt.Println("create private zone err:", err) + return + } + + fmt.Println("private zone id: ", result.ZoneId) // 创建 private zone 的 id + fmt.Println("create private zone success") +} diff --git a/bce-sdk-go/examples/localDns/example_delete_private_zone.go b/bce-sdk-go/examples/localDns/example_delete_private_zone.go new file mode 100644 index 0000000..aded707 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_delete_private_zone.go @@ -0,0 +1,32 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func DeletePrivateZone() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + zoneId := "Your private zone id" // 创建 private zone 的 id + clientToken := getClientToken() + if err := client.DeletePrivateZone(zoneId, clientToken); err != nil { + fmt.Println("delete private zone err:", err) + return + } + + fmt.Println("delete private zone success") +} diff --git a/bce-sdk-go/examples/localDns/example_delete_record.go b/bce-sdk-go/examples/localDns/example_delete_record.go new file mode 100644 index 0000000..5b5019d --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_delete_record.go @@ -0,0 +1,32 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func DeleteRecord() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + recordId := "Your record Id" + clientToken := getClientToken() + if err := client.DeleteRecord(recordId, clientToken); err != nil { + fmt.Println("delete record err:", err) + return + } + + fmt.Println("delete record success") +} diff --git a/bce-sdk-go/examples/localDns/example_disable_record.go b/bce-sdk-go/examples/localDns/example_disable_record.go new file mode 100644 index 0000000..fca4407 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_disable_record.go @@ -0,0 +1,32 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func DisableRecord() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + recordId := "Your record Id" + clientToken := getClientToken() + if err := client.DisableRecord(recordId, clientToken); err != nil { + fmt.Println("disable record err:", err) + return + } + + fmt.Println("disable record success") +} diff --git a/bce-sdk-go/examples/localDns/example_enable_record.go b/bce-sdk-go/examples/localDns/example_enable_record.go new file mode 100644 index 0000000..84de8c6 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_enable_record.go @@ -0,0 +1,32 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func EnableRecord() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + recordId := "Your record Id" + clientToken := getClientToken() + if err := client.EnableRecord(recordId, clientToken); err != nil { + fmt.Println("enable record err:", err) + return + } + + fmt.Println("enable record success") +} diff --git a/bce-sdk-go/examples/localDns/example_get_private_zone.go b/bce-sdk-go/examples/localDns/example_get_private_zone.go new file mode 100644 index 0000000..72b1ed5 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_get_private_zone.go @@ -0,0 +1,42 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func GetPrivateZone() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + zoneId := "Your private zone id" + result, err := client.GetPrivateZone(zoneId) + if err != nil { + fmt.Println("get private zone err:", err) + return + } + + fmt.Println("private zone zoneId: ", result.ZoneId) + fmt.Println("private zone zoneName: ", result.ZoneName) + fmt.Println("private zone recordCount: ", result.RecordCount) + fmt.Println("private zone createTime: ", result.CreateTime) + fmt.Println("private zone updateTime: ", result.UpdateTime) + for _, vpc := range result.BindVpcs { + fmt.Println("vpcId: ", vpc.VpcId) + fmt.Println("vpcName: ", vpc.VpcName) + fmt.Println("vpcRegion: ", vpc.VpcRegion) + } + fmt.Println("get private zone success") +} diff --git a/bce-sdk-go/examples/localDns/example_list_private_zone.go b/bce-sdk-go/examples/localDns/example_list_private_zone.go new file mode 100644 index 0000000..3b7c25b --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_list_private_zone.go @@ -0,0 +1,46 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func ListPrivateZone() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + args := &localDns.ListPrivateZoneRequest{ + Marker: "Get from last response", // 分页标示,从上次请求的返回值中获取,第一次请求不需要设置 + MaxKeys: 10, // 每页包含的最大数量 + } + result, err := client.ListPrivateZone(args) + if err != nil { + fmt.Println("list private zone err:", err) + return + } + + fmt.Println("private zone list marker: ", result.Marker) // 返回标记查询的起始位置 + fmt.Println("private zone list isTruncated: ", result.IsTruncated) // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("private zone list nextMarker: ", result.NextMarker) // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("private zone list maxKeys: ", result.MaxKeys) // 每页包含的最大数量 + for _, zone := range result.Zones { // 获取私有域的列表信息 + fmt.Println("zoneId: ", zone.ZoneId) + fmt.Println("zoneName: ", zone.ZoneName) + fmt.Println("recordCount: ", zone.RecordCount) + fmt.Println("createTime: ", zone.CreateTime) + fmt.Println("updateTime: ", zone.UpdateTime) + } + fmt.Println("list private zone success") +} diff --git a/bce-sdk-go/examples/localDns/example_list_record.go b/bce-sdk-go/examples/localDns/example_list_record.go new file mode 100644 index 0000000..3c7fea4 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_list_record.go @@ -0,0 +1,46 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func ListRecord() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + zoneId := "Your private zone id" + result, err := client.ListRecord(zoneId) + if err != nil { + fmt.Println("list record err:", err) + return + } + + fmt.Println("record list marker: ", result.Marker) // 返回标记查询的起始位置 + fmt.Println("record list isTruncated: ", result.IsTruncated) // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("record list nextMarker: ", result.NextMarker) // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("record list maxKeys: ", result.MaxKeys) // 每页包含的最大数量 + for _, record := range result.Records { // 获取对等连接的列表信息 + fmt.Println("recordId: ", record.RecordId) + fmt.Println("rr: ", record.Rr) + fmt.Println("value: ", record.Value) + fmt.Println("status: ", record.Status) + fmt.Println("type: ", record.Type) + fmt.Println("ttl: ", record.Ttl) + fmt.Println("priority: ", record.Priority) + fmt.Println("description: ", record.Description) + } + fmt.Println("list record success") +} diff --git a/bce-sdk-go/examples/localDns/example_unbind_vpcs.go b/bce-sdk-go/examples/localDns/example_unbind_vpcs.go new file mode 100644 index 0000000..c9e4e72 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_unbind_vpcs.go @@ -0,0 +1,36 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func UnbindVpcs() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + zoneId := "Your Zone Id" + args := &localDns.UnbindVpcRequest{ + ClientToken: getClientToken(), // 客户端 token + Region: "Your vpc region", // region + VpcIds: []string{"Your vpc1", "Your vpc2"}, // 该 region 下需要解绑的 vpc 列表 + } + if err := client.UnbindVpc(zoneId, args); err != nil { + fmt.Println("unbind vpcs err:", err) + return + } + + fmt.Println("unbind vpcs success") +} diff --git a/bce-sdk-go/examples/localDns/example_update_record.go b/bce-sdk-go/examples/localDns/example_update_record.go new file mode 100644 index 0000000..5480803 --- /dev/null +++ b/bce-sdk-go/examples/localDns/example_update_record.go @@ -0,0 +1,40 @@ +package ldexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/localDns" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token +func getClientToken() string { + return util.NewUUID() +} + +func UpdateRecord() { + + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := localDns.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + + recordId := "Your record Id" + args := &localDns.UpdateRecordRequest{ + ClientToken: getClientToken(), // 幂等性 token + Rr: "Your record name, such as www.test.com", // 记录名称 + Value: "Your record value, such as 192.168.0.1", // 记录值 + Type: "Your record type, such as A", // 解析记录类型,目前支持A, AAAA,CNAME, TXT, MX, PTR, SRV + Ttl: 60, // 生存时间,值为[5,24*3600],默认为60 + Priority: 0, // MX记录的优先级,取值范围:[0,100]。记录类型为MX记录时,此参数必选。 + Description: "You record description", // 描述 + } + if err := client.UpdateRecord(recordId, args); err != nil { + fmt.Println("update record err:", err) + return + } + + fmt.Println("udpate record success") +} diff --git a/bce-sdk-go/examples/userservice/example_create_userservice.go b/bce-sdk-go/examples/userservice/example_create_userservice.go new file mode 100644 index 0000000..79332e3 --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_create_userservice.go @@ -0,0 +1,49 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// CreateUserService 用于创建用户服务 +func CreateUserService() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + createArgs := &userservice.CreateUserServiceArgs{ + ClientToken: util.NewUUID(), + InstanceId: "lb-xxxxxxxx", //BLB实例ID + Name: "test_name", //名称 + Description: "test_user_service_description", //UserService备注 + ServiceName: "testUserServiceName", //UserService名称,系统根据此名称生成服务名 + AuthList: []userservice.UserServiceAuthModel{ //用户权限列表 + { + Uid: "12345678901234567890123456789012", //用户ID + Auth: userservice.ServiceAuthAllow, //用户权限,允许访问 + }}, + } + + response, err := client.CreateUserService(createArgs) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/userservice/example_delete_userservice.go b/bce-sdk-go/examples/userservice/example_delete_userservice.go new file mode 100644 index 0000000..9a74160 --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_delete_userservice.go @@ -0,0 +1,33 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" +) + +// DeleteUserService 函数用于删除用户服务 +func DeleteUserService() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "Your service domain" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + err := client.DeleteUserService(serviceDomain) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/userservice/example_describe_userservice_detail.go b/bce-sdk-go/examples/userservice/example_describe_userservice_detail.go new file mode 100644 index 0000000..3118ce9 --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_describe_userservice_detail.go @@ -0,0 +1,36 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/userservice" +) + +// DescribeUserServiceDetail 函数用于获取用户服务的详细信息 +func DescribeUserServiceDetail() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "your service domain" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + response, err := client.DescribeUserServiceDetail(serviceDomain) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/userservice/example_describe_userservices.go b/bce-sdk-go/examples/userservice/example_describe_userservices.go new file mode 100644 index 0000000..3db6a1d --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_describe_userservices.go @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/userservice" +) + +// DescribeUserServices 函数用于获取用户服务列表 +func DescribeUserServices() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.DescribeUserServicesArgs{} + + response, err := client.DescribeUserServices(args) + + if err != nil { + panic(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/userservice/example_update_userservice.go b/bce-sdk-go/examples/userservice/example_update_userservice.go new file mode 100644 index 0000000..8e416fa --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_update_userservice.go @@ -0,0 +1,40 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// UpdateUserService 函数用于更新用户服务信息 +func UpdateUserService() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "Your service domain" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.UpdateServiceArgs{ + ClientToken: util.NewUUID(), + Name: "update_test_name", + Description: "update_test_user_service_description", + } + + err := client.UpdateUserService(serviceDomain, args) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/userservice/example_userservice_add_auth.go b/bce-sdk-go/examples/userservice/example_userservice_add_auth.go new file mode 100644 index 0000000..87e5262 --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_userservice_add_auth.go @@ -0,0 +1,44 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// UserServiceAddAuth 添加用户服务权限 +func UserServiceAddAuth() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "your service domain" + uid := "the uid will be added" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.UserServiceAuthArgs{ + ClientToken: util.NewUUID(), + AuthList: []userservice.UserServiceAuthModel{ + { + Uid: uid, // 将要添加权限的uid + Auth: userservice.ServiceAuthAllow, // 权限类型,允许或拒绝,对应userservice.ServiceAuthAllow和userservice.ServiceAuthDeny + }}, + } + + err := client.UserServiceAddAuth(serviceDomain, args) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/userservice/example_userservice_bind_instance.go b/bce-sdk-go/examples/userservice/example_userservice_bind_instance.go new file mode 100644 index 0000000..fe5a3fb --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_userservice_bind_instance.go @@ -0,0 +1,40 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// UserServiceBindInstance 函数用于绑定用户服务实例 +func UserServiceBindInstance() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "Your service domain" + blbInstanceId := "Your blb instance id" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.UserServiceBindArgs{ + ClientToken: util.NewUUID(), + InstanceId: blbInstanceId, + } + + err := client.UserServiceBindInstance(serviceDomain, args) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/userservice/example_userservice_edit_auth.go b/bce-sdk-go/examples/userservice/example_userservice_edit_auth.go new file mode 100644 index 0000000..14eeabd --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_userservice_edit_auth.go @@ -0,0 +1,44 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// UserServiceEditAuth 是一个函数,用于编辑用户服务授权。 +func UserServiceEditAuth() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "your service domain" + uid := "the uid will be added" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.UserServiceAuthArgs{ + ClientToken: util.NewUUID(), + AuthList: []userservice.UserServiceAuthModel{ + { + Uid: uid, // 将要添加权限的uid + Auth: userservice.ServiceAuthAllow, // 权限类型,允许或拒绝,对应userservice.ServiceAuthAllow和userservice.ServiceAuthDeny + }}, + } + + err := client.UserServiceEditAuth(serviceDomain, args) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/userservice/example_userservice_remove_auth.go b/bce-sdk-go/examples/userservice/example_userservice_remove_auth.go new file mode 100644 index 0000000..7deeca8 --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_userservice_remove_auth.go @@ -0,0 +1,40 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// UserServiceRemoveAuth 用于从用户服务中移除用户授权 +func UserServiceRemoveAuth() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "your service domain" + uid := "the uid will be added" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.UserServiceRemoveAuthArgs{ + ClientToken: util.NewUUID(), + UidList: []string{uid}, // 用户uid列表 + } + + err := client.UserServiceRemoveAuth(serviceDomain, args) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/userservice/example_userservice_unbind_instance.go b/bce-sdk-go/examples/userservice/example_userservice_unbind_instance.go new file mode 100644 index 0000000..6e5cd48 --- /dev/null +++ b/bce-sdk-go/examples/userservice/example_userservice_unbind_instance.go @@ -0,0 +1,38 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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 userserviceexamples + +import ( + "github.com/baidubce/bce-sdk-go/services/userservice" + "github.com/baidubce/bce-sdk-go/util" +) + +// UserServiceUnBindInstance 从用户服务中解绑实例 +func UserServiceUnBindInstance() { + ak, sk, endpoint := "Your AK", "Your SK", "Your Endpoint" + serviceDomain := "Your service domain" + + client, _ := userservice.NewClient(ak, sk, endpoint) // 初始化client + + args := &userservice.UserServiceUnBindArgs{ + ClientToken: util.NewUUID(), + } + + err := client.UserServiceUnBindInstance(serviceDomain, args) + + if err != nil { + panic(err) + } +} diff --git a/bce-sdk-go/examples/vpc/acl/example_create_acl_rule.go b/bce-sdk-go/examples/vpc/acl/example_create_acl_rule.go new file mode 100644 index 0000000..f89db14 --- /dev/null +++ b/bce-sdk-go/examples/vpc/acl/example_create_acl_rule.go @@ -0,0 +1,47 @@ +package main + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func CreateAclRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + requests := []vpc.AclRuleRequest{ + { + // 设置acl规则所属的子网id + SubnetId: "sbn-zuabnf2w6qtn", + // 设置acl规则的协议 + Protocol: vpc.ACL_RULE_PROTOCOL_TCP, + // 设置acl规则的源ip + SourceIpAddress: "192.168.2.0", + // 设置acl规则的目的ip + DestinationIpAddress: "192.168.0.0/24", + // 设置acl规则的源端口 + SourcePort: "1-65535", + // 设置acl规则的目的端口 + DestinationPort: "443", + // 设置acl规则的优先级 + Position: 2, + // 设置acl规则的方向 + Direction: vpc.ACL_RULE_DIRECTION_INGRESS, + // 设置acl规则的策略 + Action: vpc.ACL_RULE_ACTION_ALLOW, + // 设置acl规则的描述信息 + Description: "test", + }, + } + args := &vpc.CreateAclRuleArgs{ + AclRules: requests, + } + if err := client.CreateAclRule(args); err != nil { + fmt.Println("create acl rule err:", err) + return + } + fmt.Println("create acl rule success") +} diff --git a/bce-sdk-go/examples/vpc/acl/example_delete_acl_rule.go b/bce-sdk-go/examples/vpc/acl/example_delete_acl_rule.go new file mode 100644 index 0000000..6eca70d --- /dev/null +++ b/bce-sdk-go/examples/vpc/acl/example_delete_acl_rule.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" + "github.com/baidubce/bce-sdk-go/util" +) + +// getClientToken 生成一个长度为32位的随机字符串作为客户端token。 +func getClientToken() string { + return util.NewUUID() +} + +func DeleteAclRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + aclRuleId := "acl-rule-id" + clientToken := getClientToken() + if err := client.DeleteAclRule(aclRuleId, clientToken); err != nil { + fmt.Println("delete acl rule err:", err) + return + } + fmt.Println("delete acl rule success") +} diff --git a/bce-sdk-go/examples/vpc/acl/example_query_acl.go b/bce-sdk-go/examples/vpc/acl/example_query_acl.go new file mode 100644 index 0000000..d36b59e --- /dev/null +++ b/bce-sdk-go/examples/vpc/acl/example_query_acl.go @@ -0,0 +1,35 @@ +package main + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func QueryAcl() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak、sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + vpcId := "vpc-12345678" + result, err := client.ListAclEntrys(vpcId) + if err != nil { + fmt.Println("query acl err:", err) + return + } + // 查询得到acl所属的vpc id + fmt.Println("acl entrys of vpcId: ", result.VpcId) + // 查询得到acl所属的vpc名称 + fmt.Println("acl entrys of vpcName: ", result.VpcName) + // 查询得到acl所属的vpc网段 + fmt.Println("acl entrys of vpcCidr: ", result.VpcCidr) + // 查询得到acl的详细信息 + for _, acl := range result.AclEntrys { + fmt.Println("subnetId: ", acl.SubnetId) + fmt.Println("subnetName: ", acl.SubnetName) + fmt.Println("subnetCidr: ", acl.SubnetCidr) + fmt.Println("aclRules: ", acl.AclRules) + } + fmt.Println("query acl success") +} diff --git a/bce-sdk-go/examples/vpc/acl/example_query_acl_rule.go b/bce-sdk-go/examples/vpc/acl/example_query_acl_rule.go new file mode 100644 index 0000000..5f59bd6 --- /dev/null +++ b/bce-sdk-go/examples/vpc/acl/example_query_acl_rule.go @@ -0,0 +1,51 @@ +package main + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func QueryAclRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak、sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.ListAclRulesArgs{ + // 设置acl所属子网的id + SubnetId: "sbn-zuabnf2w6qtn", + // 设置批量获取列表的查询的起始位置 + Marker: "", + // 设置每页包含的最大数量 + MaxKeys: 100, + } + result, err := client.ListAclRules(args) + if err != nil { + fmt.Println("query acl rule err:", err) + return + } + // 返回标记查询的起始位置 + fmt.Println("acl list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("acl list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("acl list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("acl list maxKeys: ", result.MaxKeys) + // 获取acl的列表信息 + for _, acl := range result.AclRules { + fmt.Println("acl rule id: ", acl.Id) + fmt.Println("acl rule subnetId: ", acl.SubnetId) + fmt.Println("acl rule description: ", acl.Description) + fmt.Println("acl rule protocol: ", acl.Protocol) + fmt.Println("acl rule sourceIpAddress: ", acl.SourceIpAddress) + fmt.Println("acl rule destinationIpAddress: ", acl.DestinationIpAddress) + fmt.Println("acl rule sourcePort: ", acl.SourcePort) + fmt.Println("acl rule destinationPort: ", acl.DestinationPort) + fmt.Println("acl rule position: ", acl.Position) + fmt.Println("acl rule direction: ", acl.Direction) + fmt.Println("acl rule action: ", acl.Action) + } + fmt.Println("query acl rule success") +} diff --git a/bce-sdk-go/examples/vpc/acl/example_update_acl_rule.go b/bce-sdk-go/examples/vpc/acl/example_update_acl_rule.go new file mode 100644 index 0000000..95d878c --- /dev/null +++ b/bce-sdk-go/examples/vpc/acl/example_update_acl_rule.go @@ -0,0 +1,39 @@ +package main + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func UpdateAclRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak、sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + aclRuleId := "ar-gkf7pdiy0cuj" + args := &vpc.UpdateAclRuleArgs{ + // 设置acl的最新协议 + Protocol: vpc.ACL_RULE_PROTOCOL_TCP, + // 设置acl的源ip + SourceIpAddress: "0.0.0.0", + // 设置acl的目的ip + DestinationIpAddress: "192.168.0.0/24", + // 设置acl的源端口 + SourcePort: "3333", + // 设置acl的目的端口 + DestinationPort: "4444", + // 设置acl的优先级 + Position: 12, + // 设置acl的策略 + Action: vpc.ACL_RULE_ACTION_ALLOW, + // 设置acl最新的描述信息 + Description: "test", + } + if err := client.UpdateAclRule(aclRuleId, args); err != nil { + fmt.Println("update acl rule err:", err) + return + } + fmt.Println("update acl rule success") +} diff --git a/bce-sdk-go/examples/vpc/csn/example_create_propagation.go b/bce-sdk-go/examples/vpc/csn/example_create_propagation.go new file mode 100644 index 0000000..c4f7cca --- /dev/null +++ b/bce-sdk-go/examples/vpc/csn/example_create_propagation.go @@ -0,0 +1,28 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreatePropagation() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxxx" //云智能网路由表的ID + clientToken := util.NewUUID() //幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 + desc := "desc" + args := &csn.CreatePropagationRequest{ + AttachId: "tgwAttach-uff0gvjkis95f6xg", + Description: &desc, + } + err := client.CreatePropagation(csnRtId, args, clientToken) // 创建学习关系 + + if err != nil { + fmt.Println(err) + } + + fmt.Print("create propagation success.") +} diff --git a/bce-sdk-go/examples/vpc/csn/example_create_route_rule.go b/bce-sdk-go/examples/vpc/csn/example_create_route_rule.go new file mode 100644 index 0000000..077e173 --- /dev/null +++ b/bce-sdk-go/examples/vpc/csn/example_create_route_rule.go @@ -0,0 +1,27 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreateRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxxx" //云智能网路由表的ID + clientToken := util.NewUUID() //幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 + args := &csn.CreateRouteRuleRequest{ + AttachId: "tgwAttach-rvu8tkaubphb78eg", + DestAddress: "0.0.0.0/0", + RouteType: "custom", + } + + err := client.CreateRouteRule(csnRtId, args, clientToken) // 创建路由规则 + if err != nil { + fmt.Println(err) + } + fmt.Println("create route rule success.") +} diff --git a/bce-sdk-go/examples/vpc/csn/example_delete_propagation.go b/bce-sdk-go/examples/vpc/csn/example_delete_propagation.go new file mode 100644 index 0000000..fbe31d2 --- /dev/null +++ b/bce-sdk-go/examples/vpc/csn/example_delete_propagation.go @@ -0,0 +1,24 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" + "github.com/baidubce/bce-sdk-go/util" +) + +func DeletePropagation() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxx" //云智能网路由表的ID + attachId := "tgwAttach-xxxx" //网络实例在云智能网中的身份ID + clientToken := util.NewUUID() //幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 + + err := client.DeletePropagation(csnRtId, attachId, clientToken) // 删除学习关系 + + if err != nil { + fmt.Println(err) + } + fmt.Println("delete propagation success.") +} diff --git a/bce-sdk-go/examples/vpc/csn/example_list_propagation.go b/bce-sdk-go/examples/vpc/csn/example_list_propagation.go new file mode 100644 index 0000000..0e55849 --- /dev/null +++ b/bce-sdk-go/examples/vpc/csn/example_list_propagation.go @@ -0,0 +1,21 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListPropagation() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxx" //云智能网路由表的ID + + response, err := client.ListPropagation(csnRtId) + if err != nil { + fmt.Println(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/csn/example_list_route_rule.go b/bce-sdk-go/examples/vpc/csn/example_list_route_rule.go new file mode 100644 index 0000000..f99d3f4 --- /dev/null +++ b/bce-sdk-go/examples/vpc/csn/example_list_route_rule.go @@ -0,0 +1,22 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/csn" +) + +func ListRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := csn.NewClient(ak, sk, endpoint) // 初始化client + + csnRtId := "xxxxx" //云智能网路由表的ID + args := &csn.ListRouteRuleArgs{} + + response, err := client.ListRouteRule(csnRtId, args) + if err != nil { + fmt.Println(err) + } + + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway.go new file mode 100644 index 0000000..b5a0ada --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway.go @@ -0,0 +1,34 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func CreateIPv6Gateway() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpc.CreateIPv6GatewayArgs{ + // 设置ipv6网关的名称 + Name: "ipv6gateway-sdk-go", + // 设置ipv6网关所属的vpc id + VpcId: "vpc-id", + // 设置ipv6网关的带宽上限 + BandwidthInMbps: 10, + // 设置ipv6网关的计费信息 + Billing: &vpc.Billing{ + PaymentTiming: vpc.PAYMENT_TIMING_POSTPAID, + }, + } + result, err := ipv6gatewayClient.CreateIPv6Gateway(args) + if err != nil { + fmt.Println("create ipv6 gateway error: ", err) + return + } + fmt.Println("ipv6 gateway id: ", result.GatewayId) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway_egress_only_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway_egress_only_rule.go new file mode 100644 index 0000000..a4a8ab5 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway_egress_only_rule.go @@ -0,0 +1,28 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func CreateIPv6GatewayEgressOnlyRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + args := &vpc.CreateIPv6GatewayEgressOnlyRuleArgs{ + // 设置只出不进策略的CIDR + Cidr: "2400:da00:e003:d01::/64", + } + result, err := ipv6gatewayClient.CreateIPv6GatewayEgressOnlyRule(ipv6gatewayID, args) + if err != nil { + fmt.Println("create ipv6 gateway egress only rule error: ", err) + return + } + fmt.Println("ipv6 gateway egress only rule id: ", result.EgressOnlyRuleId) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway_ratelimit_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway_ratelimit_rule.go new file mode 100644 index 0000000..d266088 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_create_ipv6gateway_ratelimit_rule.go @@ -0,0 +1,32 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func CreateIPv6GatewayRateLimitRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + args := &vpc.CreateIPv6GatewayRateLimitRuleArgs{ + // 设置要限速IPv6的地址 + IPv6Address: "240c:4082:0:100::", + // 设置限速的入向带宽 + IngressBandwidthInMbps: 10, + // 设置限速的出向带宽 + EgressBandwidthInMbps: 10, + } + result, err := ipv6gatewayClient.CreateIPv6GatewayRateLimitRule(ipv6gatewayID, args) + if err != nil { + fmt.Println("create ipv6 gateway rate limit rule error: ", err) + return + } + fmt.Println("ipv6 gateway rate limit rule id: ", result.RateLimitRuleId) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway.go new file mode 100644 index 0000000..7e4ddde --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway.go @@ -0,0 +1,28 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func DeleteIPv6Gateway() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + args := &vpc.DeleteIPv6GatewayArgs{ + // 客户端Token,用于请求的幂等性 + ClientToken: "-", + } + if err := ipv6gatewayClient.DeleteIPv6Gateway(ipv6gatewayID, args); err != nil { + fmt.Println("delete ipv6 gateway error: ", err) + return + } + + fmt.Printf("delete ipv6 gateway %s success.", ipv6gatewayID) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway_egress_only_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway_egress_only_rule.go new file mode 100644 index 0000000..0c13fee --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway_egress_only_rule.go @@ -0,0 +1,30 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func DeleteIPv6GatewayEgressOnlyRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + egressOnlyRuleID := "Your egressOnlyRule's id" + + args := &vpc.DeleteIPv6GatewayEgressOnlyRuleArgs{ + // 客户端Token,用于请求的幂等性 + ClientToken: "-", + } + if err := ipv6gatewayClient.DeleteIPv6GatewayEgressOnlyRule(ipv6gatewayID, egressOnlyRuleID, args); err != nil { + fmt.Println("delete ipv6 gateway egress only rule error: ", err) + return + } + + fmt.Printf("delete ipv6 gateway %s egress only rule %s success.", ipv6gatewayID, egressOnlyRuleID) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway_ratelimit_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway_ratelimit_rule.go new file mode 100644 index 0000000..865ee35 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_delete_ipv6gateway_ratelimit_rule.go @@ -0,0 +1,30 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func DeleteIPv6GatewayRateLimitRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + rateLimitRuleID := "Your rateLimitRule's id" + + args := &vpc.DeleteIPv6GatewayRateLimitRuleArgs{ + // 客户端Token,用于请求的幂等性 + ClientToken: "-", + } + if err := ipv6gatewayClient.DeleteIPv6GatewayRateLimitRule(ipv6gatewayID, rateLimitRuleID, args); err != nil { + fmt.Println("delete ipv6 gateway rate limit rule error: ", err) + return + } + + fmt.Printf("delete ipv6 gateway %s rate limit rule %s success.", ipv6gatewayID, rateLimitRuleID) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway.go new file mode 100644 index 0000000..fbd3419 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway.go @@ -0,0 +1,34 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ListIPv6Gateway() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + vpcID := "Your vpc's id" + + args := &vpc.ListIPv6GatewayArgs{ + // 设置ipv6网关所属的vpc id,必选 + VpcId: vpcID, + } + result, err := ipv6gatewayClient.ListIPv6Gateway(args) + if err != nil { + fmt.Println("list ipv6 gateway error: ", err) + return + } + // 获取ipv6gateway信息 + fmt.Println("ipv6 gateway id: ", result.GatewayId) + fmt.Println("ipv6 gateway name: ", result.Name) + fmt.Println("ipv6 gateway vpcId: ", result.VpcId) + fmt.Println("ipv6 gateway bandwidthInMbps: ", result.BandwidthInMbps) + fmt.Printf("ipv6 gateway egress only rules: %v", result.EgressOnlyRules) + fmt.Printf("ipv6 gateway rate limit rules: %v", result.RateLimitRules) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway_egress_only_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway_egress_only_rule.go new file mode 100644 index 0000000..119cf0f --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway_egress_only_rule.go @@ -0,0 +1,34 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ListIPv6GatewayEgressOnlyRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + args := &vpc.ListIPv6GatewayEgressOnlyRuleArgs{ + // 设置每页包含的最大数量 + MaxKeys: 10, + // 设置查询起始位置 + Marker: "Your EgressOnlyRule's id", + } + result, err := ipv6gatewayClient.ListIPv6GatewayEgressOnlyRule(ipv6gatewayID, args) + if err != nil { + fmt.Println("list ipv6 gateway egress only rules error: ", err) + return + } + // 获取ipv6gatewayEgressOnlyRule列表 + for _, egressOnlyRule := range result.EgressOnlyRules { + fmt.Println("ipv6 gateway egress only rule id: ", egressOnlyRule.EgressOnlyRuleId) + fmt.Println("ipv6 gateway egress only rule cidr: ", egressOnlyRule.Cidr) + } +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway_ratelimit_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway_ratelimit_rule.go new file mode 100644 index 0000000..3191523 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_list_ipv6gateway_ratelimit_rule.go @@ -0,0 +1,35 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ListIPv6GatewayRateLimitRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + args := &vpc.ListIPv6GatewayRateLimitRuleArgs{ + // 设置每页包含的最大数量 + MaxKeys: 10, + // 设置查询起始位置 + Marker: "Your RateLimitRule's id", + } + result, err := ipv6gatewayClient.ListIPv6GatewayRateLimitRule(ipv6gatewayID, args) + if err != nil { + fmt.Println("list ipv6 gateway rate limit rules error: ", err) + return + } + // 获取ipv6gatewayRateLimitRule列表 + for _, rateLimitRule := range result.RateLimitRules { + fmt.Println("ipv6 gateway rate limit rule id: ", rateLimitRule.RateLimitRuleId) + fmt.Println("ipv6 gateway rate limit rule ingress bandwidthInMbps: ", rateLimitRule.IngressBandwidthInMbps) + fmt.Println("ipv6 gateway rate limit rule egress bandwidthInMbps: ", rateLimitRule.EgressBandwidthInMbps) + } +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_resize_ipv6gateway.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_resize_ipv6gateway.go new file mode 100644 index 0000000..9177d12 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_resize_ipv6gateway.go @@ -0,0 +1,30 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ResizeIPv6Gateway() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + args := &vpc.ResizeIPv6GatewayArgs{ + // 客户端Token,用于请求的幂等性 + ClientToken: "-", + // 指定IPv6网关的带宽 + BandwidthInMbps: 10, + } + if err := ipv6gatewayClient.ResizeIPv6Gateway(ipv6gatewayID, args); err != nil { + fmt.Println("resize ipv6 gateway error: ", err) + return + } + + fmt.Printf("resize ipv6 gateway %s success.", ipv6gatewayID) +} diff --git a/bce-sdk-go/examples/vpc/ipv6gateway/example_update_ipv6gateway_ratelimit_rule.go b/bce-sdk-go/examples/vpc/ipv6gateway/example_update_ipv6gateway_ratelimit_rule.go new file mode 100644 index 0000000..19aa7d9 --- /dev/null +++ b/bce-sdk-go/examples/vpc/ipv6gateway/example_update_ipv6gateway_ratelimit_rule.go @@ -0,0 +1,34 @@ +package ipv6gateway + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UpdateIPv6GatewayRateLimitRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + ipv6gatewayClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + ipv6gatewayID := "Your ipv6gateway's id" + + rateLimitRuleID := "Your rateLimitRule's id" + + args := &vpc.UpdateIPv6GatewayRateLimitRuleArgs{ + // 客户端Token,用于请求的幂等性 + ClientToken: "-", + // 设置限速的入向带宽 + IngressBandwidthInMbps: 10, + // 设置限速的出向带宽 + EgressBandwidthInMbps: 10, + } + if err := ipv6gatewayClient.UpdateIPv6GatewayRateLimitRule(ipv6gatewayID, rateLimitRuleID, args); err != nil { + fmt.Println("update ipv6 gateway rate limit rule error: ", err) + return + } + + fmt.Printf("update ipv6 gateway %s rate limit rule %s success.", ipv6gatewayID, rateLimitRuleID) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_batch_create_dnat_rule.go b/bce-sdk-go/examples/vpc/nat/example_batch_create_dnat_rule.go new file mode 100644 index 0000000..69b9b28 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_batch_create_dnat_rule.go @@ -0,0 +1,44 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func BatchCreateDnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + // replace by your data + args := &vpc.BatchCreateNatGatewayDnatRuleArgs{ + Rules: []vpc.DnatRuleArgs{ + { + RuleName: "dnat_go_1", + PublicIpAddress: "100.88.14.90", + PrivateIpAddress: "192.168.1.1", + Protocol: "TCP", + PublicPort: "1212", + PrivatePort: "1212", + }, + { + RuleName: "dnat_go_2", + PublicIpAddress: "100.88.14.52", + PrivateIpAddress: "192.168.1.2", + Protocol: "UDP", + PublicPort: "65535", + PrivatePort: "65535", + }, + }, + } + result, err := natClient.BatchCreateNatGatewayDnatRule(NatID, args) + if err != nil { + fmt.Println("error: ", err) + return + } + fmt.Println("dnat rules id: ", result.RuleIds) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_batch_create_snat_rule.go b/bce-sdk-go/examples/vpc/nat/example_batch_create_snat_rule.go new file mode 100644 index 0000000..1d1c4ee --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_batch_create_snat_rule.go @@ -0,0 +1,31 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func BatchCreateSnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.BatchCreateNatGatewaySnatRuleArgs{ + NatId: NatID, + SnatRules: []vpc.SnatRuleArgs{ + {RuleName: "batchTest1", SourceCIDR: "192.168.1.0/24", PublicIpAddresses: []string{"100.88.14.90"}}, + {RuleName: "batchTest2", SourceCIDR: "192.168.16.0/20", PublicIpAddresses: []string{"100.88.14.90"}}, + }, + } + results, err := natClient.BatchCreateNatGatewaySnatRule(args) + if err != nil { + fmt.Println("error: ", err) + return + } + fmt.Println("snat rules id: ", results.SnatRuleIds) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_bind_dnat_eip.go b/bce-sdk-go/examples/vpc/nat/example_bind_dnat_eip.go new file mode 100644 index 0000000..7665e7a --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_bind_dnat_eip.go @@ -0,0 +1,26 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func BindDnatEip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.BindDnatEipsArgs{ + // 设置要绑定的 EIP 列表 + DnatEips: []string{"180.76.186.174"}, // 替换为需要绑定的 EIP 列表 + } + if err := natClient.BindDnatEips(NatID, args); err != nil { + fmt.Println("bind dnat eips error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/vpc/nat/example_bind_eip.go b/bce-sdk-go/examples/vpc/nat/example_bind_eip.go new file mode 100644 index 0000000..5fcf79e --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_bind_eip.go @@ -0,0 +1,26 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func BindEip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.BindEipsArgs{ + // 设置要绑定的 EIP 列表 + Eips: []string{"180.76.186.174"}, // 替换为需要绑定的 EIP 列表 + } + if err := natClient.BindEips(NatID, args); err != nil { + fmt.Println("bind eips error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/vpc/nat/example_create_dnat_rule.go b/bce-sdk-go/examples/vpc/nat/example_create_dnat_rule.go new file mode 100644 index 0000000..33252f1 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_create_dnat_rule.go @@ -0,0 +1,32 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func CreateDnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + // replace by your data + args := &vpc.CreateNatGatewayDnatRuleArgs{ + RuleName: "dnat_go", + PublicIpAddress: "100.88.14.90", + PrivateIpAddress: "192.168.1.1", + Protocol: "TCP", + PublicPort: "1212", + PrivatePort: "1212", + } + result, err := natClient.CreateNatGatewayDnatRule(NatID, args) + if err != nil { + fmt.Println("error: ", err) + return + } + fmt.Println("dnat rule id: ", result.RuleId) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_create_nat.go b/bce-sdk-go/examples/vpc/nat/example_create_nat.go new file mode 100644 index 0000000..41ff651 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_create_nat.go @@ -0,0 +1,38 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func CreateNat() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpc.CreateNatGatewayArgs{ + // 设置nat网关的名称 + Name: "nat-sdk-go", + // 设置nat网关所属的vpc id + VpcId: "vpc-id", + // 设置nat网关的规格 + Spec: vpc.NAT_GATEWAY_SPEC_SMALL, + // 设置nat网关的snat eip列表 + Eips: []string{}, + // 设置nat网关的dnat eip列表 + DnatEips: []string{}, + // 设置nat网关的计费信息 + Billing: &vpc.Billing{ + PaymentTiming: vpc.PAYMENT_TIMING_PREPAID, + }, + } + result, err := natClient.CreateNatGateway(args) + if err != nil { + fmt.Println("create nat gateway error: ", err) + return + } + fmt.Println("create nat gateway success, nat gateway id: ", result.NatId) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_create_snat_rule.go b/bce-sdk-go/examples/vpc/nat/example_create_snat_rule.go new file mode 100644 index 0000000..8c15a73 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_create_snat_rule.go @@ -0,0 +1,30 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func CreateSnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.CreateNatGatewaySnatRuleArgs{ + RuleName: "snat_go", + SourceCIDR: "192.168.1.0/24", // 源网段,eg. 192.168.1.0/24 + PublicIpAddresses: []string{"100.88.14.90"}, // 替换为需要绑定的 EIP 列表 + } + result, err := natClient.CreateNatGatewaySnatRule(NatID, args) + if err != nil { + fmt.Println("error: ", err) + return + } + + fmt.Println("snat rule id: ", result.RuleId) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_delete_dnat_rule.go b/bce-sdk-go/examples/vpc/nat/example_delete_dnat_rule.go new file mode 100644 index 0000000..0cddd8a --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_delete_dnat_rule.go @@ -0,0 +1,28 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func DeleteDnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + DnatRuleID := "Your dnat rule's id" + + clientToken := "-" // 客户端Token,用于请求的幂等性 + + if err := natClient.DeleteNatGatewayDnatRule(NatID, DnatRuleID, clientToken); err != nil { + fmt.Println("error: ", err) + return + } + + fmt.Println("ok.") +} diff --git a/bce-sdk-go/examples/vpc/nat/example_delete_nat.go b/bce-sdk-go/examples/vpc/nat/example_delete_nat.go new file mode 100644 index 0000000..cfbd87c --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_delete_nat.go @@ -0,0 +1,25 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func DeleteNat() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + clientToken := "-" // 客户端Token,用于请求的幂等性 + if err := natClient.DeleteNatGateway(NatID, clientToken); err != nil { + fmt.Println("delete nat gateway error: ", err) + return + } + + fmt.Printf("delete nat gateway %s success.", NatID) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_delete_snat_rule.go b/bce-sdk-go/examples/vpc/nat/example_delete_snat_rule.go new file mode 100644 index 0000000..154739d --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_delete_snat_rule.go @@ -0,0 +1,28 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func DeleteSnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + SnatRuleID := "Your snat rule's id" + + clientToken := "-" // 客户端Token,用于请求的幂等性 + + if err := natClient.DeleteNatGatewaySnatRule(NatID, SnatRuleID, clientToken); err != nil { + fmt.Println("error: ", err) + return + } + + fmt.Println("ok.") +} diff --git a/bce-sdk-go/examples/vpc/nat/example_get_nat_detail.go b/bce-sdk-go/examples/vpc/nat/example_get_nat_detail.go new file mode 100644 index 0000000..00d770c --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_get_nat_detail.go @@ -0,0 +1,42 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func GetNatDetail() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + result, err := natClient.GetNatGatewayDetail(NatID) + if err != nil { + fmt.Println("get nat gateway details error: ", err) + return + } + + // 查询得到nat网关的id + fmt.Println("nat id: ", result.Id) + // 查询得到nat网关的名称 + fmt.Println("nat name: ", result.Name) + // 查询得到nat网关所属的vpc id + fmt.Println("nat vpcId: ", result.VpcId) + // 查询得到nat网关的大小 + fmt.Println("nat spec: ", result.Spec) + // 查询得到nat网关绑定的snat EIP的IP地址列表 + fmt.Println("nat snat eips: ", result.Eips) + // 查询得到nat网关绑定的dnat EIP的IP地址列表 + fmt.Println("nat dnat eips: ", result.DnatEips) + // 查询得到nat网关的状态 + fmt.Println("nat status: ", result.Status) + // 查询得到nat网关的付费方式 + fmt.Println("nat paymentTiming: ", result.PaymentTiming) + // 查询得到nat网关的过期时间 + fmt.Println("nat expireTime: ", result.ExpiredTime) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_list_dnat_rule.go b/bce-sdk-go/examples/vpc/nat/example_list_dnat_rule.go new file mode 100644 index 0000000..eb78524 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_list_dnat_rule.go @@ -0,0 +1,27 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ListDnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.ListNatGatewaDnatRuleArgs{ + MaxKeys: 10, + } + result, err := natClient.ListNatGatewayDnatRules(NatID, args) + if err != nil { + fmt.Println("error: ", err) + return + } + fmt.Printf("Get %d dnat rules: \n", len(result.Rules)) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_list_nat.go b/bce-sdk-go/examples/vpc/nat/example_list_nat.go new file mode 100644 index 0000000..0939178 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_list_nat.go @@ -0,0 +1,40 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ListNat() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + VPCID := "Your vpc's id" + + args := &vpc.ListNatGatewayArgs{ + // 设置nat网关所属的vpc id,必选 + VpcId: VPCID, + // 指定查询的NAT的Id + } + result, err := natClient.ListNatGateway(args) + if err != nil { + fmt.Println("list nat gateway error: ", err) + return + } + // 获取nat的列表信息 + for _, nat := range result.Nats { + fmt.Println("nat id: ", nat.Id) + fmt.Println("nat name: ", nat.Name) + fmt.Println("nat vpcId: ", nat.VpcId) + fmt.Println("nat spec: ", nat.Spec) + fmt.Println("nat snat eips: ", nat.Eips) + fmt.Println("nat dnat eips: ", nat.DnatEips) + fmt.Println("nat status: ", nat.Status) + fmt.Println("nat paymentTiming: ", nat.PaymentTiming) + fmt.Println("nat expireTime: ", nat.ExpiredTime) + } +} diff --git a/bce-sdk-go/examples/vpc/nat/example_list_snat_rule.go b/bce-sdk-go/examples/vpc/nat/example_list_snat_rule.go new file mode 100644 index 0000000..0a7231e --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_list_snat_rule.go @@ -0,0 +1,30 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func ListSnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.ListNatGatewaySnatRuleArgs{ + NatId: NatID, + } + result, err := natClient.ListNatGatewaySnatRules(args) + if err != nil { + fmt.Println("error: ", err) + return + } + fmt.Printf("Get %d snat rules: \n", len(result.Rules)) + for _, rule := range result.Rules { + fmt.Printf("snat rule: %s\n", rule) + } +} diff --git a/bce-sdk-go/examples/vpc/nat/example_renew_nat.go b/bce-sdk-go/examples/vpc/nat/example_renew_nat.go new file mode 100644 index 0000000..2840f47 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_renew_nat.go @@ -0,0 +1,33 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func RenewNat() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.RenewNatGatewayArgs{ + // 设置nat网关续费的订单信息 + Billing: &vpc.Billing{ + Reservation: &vpc.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + } + if err := natClient.RenewNatGateway(NatID, args); err != nil { + fmt.Println("renew nat gateway error: ", err) + return + } + + fmt.Printf("renew nat gateway %s success.", NatID) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_unbind_dnat_eip.go b/bce-sdk-go/examples/vpc/nat/example_unbind_dnat_eip.go new file mode 100644 index 0000000..e555909 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_unbind_dnat_eip.go @@ -0,0 +1,26 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UnDnatBindEip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.UnBindDnatEipsArgs{ + // 设置要解绑的 Dnat EIP 列表 + DnatEips: []string{"180.76.186.174"}, // 替换为需要解绑的 Dnat EIP 列表 + } + if err := natClient.UnBindDnatEips(NatID, args); err != nil { + fmt.Println("unbind eips error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/vpc/nat/example_unbind_eip.go b/bce-sdk-go/examples/vpc/nat/example_unbind_eip.go new file mode 100644 index 0000000..720f734 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_unbind_eip.go @@ -0,0 +1,26 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UnBindEip() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.UnBindEipsArgs{ + // 设置要解绑的 EIP 列表 + Eips: []string{"180.76.186.174"}, // 替换为需要解绑的 EIP 列表 + } + if err := natClient.UnBindEips(NatID, args); err != nil { + fmt.Println("unbind eips error: ", err) + return + } +} diff --git a/bce-sdk-go/examples/vpc/nat/example_update_dnat_rule.go b/bce-sdk-go/examples/vpc/nat/example_update_dnat_rule.go new file mode 100644 index 0000000..5a986d6 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_update_dnat_rule.go @@ -0,0 +1,35 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UpdateDnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + DnatRuleID := "Your dnat rule's id" + + // replace with your data + args := &vpc.UpdateNatGatewayDnatRuleArgs{ + RuleName: "dnat_go_update", + PublicIpAddress: "100.88.14.90", + PrivateIpAddress: "192.168.1.2", + Protocol: "TCP", + PublicPort: "1212", + PrivatePort: "1212", + } + err := natClient.UpdateNatGatewayDnatRule(NatID, DnatRuleID, args) + if err != nil { + fmt.Println("error: ", err) + return + } + fmt.Println("dnat rule update successfully") +} diff --git a/bce-sdk-go/examples/vpc/nat/example_update_nat.go b/bce-sdk-go/examples/vpc/nat/example_update_nat.go new file mode 100644 index 0000000..a5b8777 --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_update_nat.go @@ -0,0 +1,29 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UpdateNat() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + args := &vpc.UpdateNatGatewayArgs{ + // 设置nat网关的最新名称 + Name: "GO-SDK-TestNatUpdate", + } + + if err := natClient.UpdateNatGateway(NatID, args); err != nil { + fmt.Println("update nat gateway error: ", err) + return + } + + fmt.Printf("update nat gateway %s success.", NatID) +} diff --git a/bce-sdk-go/examples/vpc/nat/example_update_snat_rule.go b/bce-sdk-go/examples/vpc/nat/example_update_snat_rule.go new file mode 100644 index 0000000..855834f --- /dev/null +++ b/bce-sdk-go/examples/vpc/nat/example_update_snat_rule.go @@ -0,0 +1,31 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 以下为示例代码,实际开发中请根据需要进行修改和补充 + +func UpdateSnatRule() { + ak, sk, endpoint := "Your AK", "Your SK", "bcc.bj.baidubce.com" + + natClient, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + NatID := "Your nat's id" + + SnatRuleID := "Your snat rule's id" + + args := &vpc.UpdateNatGatewaySnatRuleArgs{ + RuleName: "snat_go_modify", + SourceCIDR: "192.168.1.0/24", // 源网段,eg. 192.168.1.0/24 + PublicIpAddresses: []string{"x.x.x.x"}, // 替换为需要绑定的 EIP 列表 + } + if err := natClient.UpdateNatGatewaySnatRule(NatID, SnatRuleID, args); err != nil { + fmt.Println("error: ", err) + return + } + + fmt.Println("ok.") +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_accept_peer_conn_apply.go b/bce-sdk-go/examples/vpc/peerconn/example_accept_peer_conn_apply.go new file mode 100644 index 0000000..05754bd --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_accept_peer_conn_apply.go @@ -0,0 +1,22 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func AcceptPeerConnApply() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + peerConnId := "peer-conn-id" + clientToken := getClientToken() + if err := client.AcceptPeerConnApply(peerConnId, clientToken); err != nil { + fmt.Println("accept peer conn error: ", err) + return + } + fmt.Printf("accept peer conn %s success.", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_close_peer_conn_sync_dns.go b/bce-sdk-go/examples/vpc/peerconn/example_close_peer_conn_sync_dns.go new file mode 100644 index 0000000..0299540 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_close_peer_conn_sync_dns.go @@ -0,0 +1,28 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ClosePeerConnSyncDns() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.PeerConnSyncDNSArgs{ + // 请求标识 + ClientToken: getClientToken(), + // 指定对等连接的角色,发起端"initiator" 接收端"acceptor" + Role: vpc.PEERCONN_ROLE_INITIATOR, + } + peerConnId := "peer-conn-id" + if err := client.ClosePeerConnSyncDNS(peerConnId, args); err != nil { + fmt.Println("close peer conn sync dns error: ", err) + return + } + + fmt.Printf("close peer conn %s sync dns success.", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_create_peer_conn.go b/bce-sdk-go/examples/vpc/peerconn/example_create_peer_conn.go new file mode 100644 index 0000000..656fb47 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_create_peer_conn.go @@ -0,0 +1,46 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func CreatePeerConn() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.CreatePeerConnArgs{ + // 请求标识 + ClientToken: getClientToken(), + // 设置对等连接的带宽 + BandwidthInMbps: 10, + // 设置对等连接的描述信息 + Description: "test peer conn", + // 设置对等连接的本端端口名称 + LocalIfName: "local-interface", + // 设置对等连接的本端vpc的id + LocalVpcId: "local-vpc-id", + // 设置对等连接的对端账户ID,只有在建立跨账号的对等连接时需要该字段 + peerAccountId: "peer-account-id", + // 设置对等连接的对端vpc的id + PeerVpcId: "peer-vpc-id", + // 设置对等连接的对端区域 + PeerRegion: "bj", + // 设置对等连接的对端接口名称,只有本账号的对等连接才允许设置该字段 + PeerIfName: "peer-interface", + // 设置对等连接的计费信息 + Billing: &vpc.Billing{ + PaymentTiming: vpc.PAYMENT_TIMING_POSTPAID, + }, + } + result, err := client.CreatePeerConn(args) + if err != nil { + fmt.Println("create peerconn error: ", err) + return + } + + fmt.Println("create peerconn success, peerconn id: ", result.PeerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_delete_peer_conn.go b/bce-sdk-go/examples/vpc/peerconn/example_delete_peer_conn.go new file mode 100644 index 0000000..24552c8 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_delete_peer_conn.go @@ -0,0 +1,23 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func DeletePeerConn() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + peerConnId := "peer-conn-id" + clientToken := getClientToken() + if err := client.DeletePeerConn(peerConnId, clientToken); err != nil { + fmt.Println("delete peer conn error: ", err) + return + } + + fmt.Printf("delete peer conn %s success", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_get_peer_conn_detail.go b/bce-sdk-go/examples/vpc/peerconn/example_get_peer_conn_detail.go new file mode 100644 index 0000000..4e41361 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_get_peer_conn_detail.go @@ -0,0 +1,54 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func GetPeerConnDetail() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + peerConnId := "peer-conn-id" + result, err := client.GetPeerConnDetail(peerConnId, vpc.PEERCONN_ROLE_INITIATOR) + if err != nil { + fmt.Println("get peer conn detail error: ", err) + return + } + + // 查询得到对等连接的id + fmt.Println("peerconn id: ", result.PeerConnId) + // 查询得到对等连接的角色, "initiator"表示发起端"acceptor"表示接受端 + fmt.Println("peerconn role: ", result.Role) + // 查询得到对等连接的状态 + fmt.Println("peerconn status: ", result.Status) + // 查询得到对等连接的带宽 + fmt.Println("peerconn bandwithInMbp: ", result.BandwidthInMbps) + // 查询得到对等连接的描述 + fmt.Println("peerconn description: ", result.Description) + // 查询得到对等连接的本端接口ID + fmt.Println("peerconn localIfId: ", result.LocalIfId) + // 查询得到对等连接的本端接口名称 + fmt.Println("peerconn localIfName: ", result.LocalIfName) + // 查询得到对等连接的本端VPC ID + fmt.Println("peerconn localVpcId: ", result.LocalVpcId) + // 查询得到对等连接的本端区域 + fmt.Println("peerconn localRegion: ", result.LocalRegion) + // 查询得到对等连接的对端VPC ID + fmt.Println("peerconn peerVpcId: ", result.PeerVpcId) + // 查询得到对等连接的对端区域 + fmt.Println("peerconn peerRegion: ", result.PeerRegion) + // 查询得到对等连接的对端账户ID + fmt.Println("peerconn peerAccountId: ", result.PeerAccountId) + // 查询得到对等连接的计费方式 + fmt.Println("peerconn paymentTiming: ", result.PaymentTiming) + // 查询得到对等连接的dns状态 + fmt.Println("peerconn dnsStatus: ", result.DnsStatus) + // 查询得到对等连接的创建时间 + fmt.Println("peerconn createdTime: ", result.CreatedTime) + // 查询得到对等连接的过期时间 + fmt.Println("peerconn expiredTime: ", result.ExpiredTime) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_list_peer_conn.go b/bce-sdk-go/examples/vpc/peerconn/example_list_peer_conn.go new file mode 100644 index 0000000..af53fea --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_list_peer_conn.go @@ -0,0 +1,56 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ListPeerConn() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.ListPeerConnsArgs{ + // 指定对等连接所属的vpc id + VpcId: "vpcId", + // 指定批量获取列表的查询的起始位置 + Marker: "20", + // 指定每页包含的最大数量,最大数量不超过1000。缺省值为1000 + MaxKeys: 1000, + } + result, err := client.ListPeerConn(args) + if err != nil { + fmt.Println("list peer conns error: ", err) + return + } + + // 返回标记查询的起始位置 + fmt.Println("peerconn list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("peerconn list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("peerconn list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("peerconn list maxKeys: ", result.MaxKeys) + // 获取对等连接的列表信息 + for _, pc := range result.PeerConns { + fmt.Println("peerconn id: ", pc.PeerConnId) + fmt.Println("peerconn role: ", pc.Role) + fmt.Println("peerconn status: ", pc.Status) + fmt.Println("peerconn bandwithInMbp: ", pc.BandwidthInMbps) + fmt.Println("peerconn description: ", pc.Description) + fmt.Println("peerconn localIfId: ", pc.LocalIfId) + fmt.Println("peerconn localIfName: ", pc.LocalIfName) + fmt.Println("peerconn localVpcId: ", pc.LocalVpcId) + fmt.Println("peerconn localRegion: ", pc.LocalRegion) + fmt.Println("peerconn peerVpcId: ", pc.PeerVpcId) + fmt.Println("peerconn peerRegion: ", pc.PeerRegion) + fmt.Println("peerconn peerAccountId: ", pc.PeerAccountId) + fmt.Println("peerconn paymentTiming: ", pc.PaymentTiming) + fmt.Println("peerconn dnsStatus: ", pc.DnsStatus) + fmt.Println("peerconn createdTime: ", pc.CreatedTime) + fmt.Println("peerconn expiredTime: ", pc.ExpiredTime) + } +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_open_peer_conn_sync_dns.go b/bce-sdk-go/examples/vpc/peerconn/example_open_peer_conn_sync_dns.go new file mode 100644 index 0000000..0df0051 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_open_peer_conn_sync_dns.go @@ -0,0 +1,28 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func OpenPeerConnSyncDns() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.PeerConnSyncDNSArgs{ + // 请求标识 + ClientToken: getClientToken(), + // 指定对等连接的角色,发起端"initiator" 接收端"acceptor" + Role: vpc.PEERCONN_ROLE_INITIATOR, + } + peerConnId := "peer-conn-id" + if err := client.OpenPeerConnSyncDNS(peerConnId, args); err != nil { + fmt.Println("open peer conn sync dns error: ", err) + return + } + + fmt.Printf("open peer conn %s sync dns success.", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_renew_peer_conn.go b/bce-sdk-go/examples/vpc/peerconn/example_renew_peer_conn.go new file mode 100644 index 0000000..7383103 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_renew_peer_conn.go @@ -0,0 +1,33 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func RenewPeerConn() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.RenewPeerConnArgs{ + // 请求标识 + ClientToken: getClientToken(), + // 指定对等连接的续费信息 + Billing: &vpc.Billing{ + Reservation: &vpc.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + } + peerConnId := "peer-conn-id" + if err := client.RenewPeerConn(peerConnId, args); err != nil { + fmt.Println("renew peer conn error: ", err) + return + } + + fmt.Printf("renew peer conn %s success.", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_resize_peer_conn.go b/bce-sdk-go/examples/vpc/peerconn/example_resize_peer_conn.go new file mode 100644 index 0000000..93b5c29 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_resize_peer_conn.go @@ -0,0 +1,28 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ResizePeerConn() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.ResizePeerConnArgs{ + // 请求标识 + ClientToken: getClientToken(), + // 指定对等连接升降级的带宽 + NewBandwidthInMbps: 20, + } + peerConnId := "peer-conn-id" + if err := client.ResizePeerConn(peerConnId, args); err != nil { + fmt.Println("resize peer conn error: ", err) + return + } + + fmt.Printf("resize peer conn %s success.", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/peerconn/example_update_peer_conn.go b/bce-sdk-go/examples/vpc/peerconn/example_update_peer_conn.go new file mode 100644 index 0000000..a32d5c1 --- /dev/null +++ b/bce-sdk-go/examples/vpc/peerconn/example_update_peer_conn.go @@ -0,0 +1,30 @@ +package peerconnexamples + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func UpdatePeerConn() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, err := vpc.NewClient(ak, sk, endpoint) // 初始化client + if err != nil { + fmt.Println("create client err:", err) + return + } + args := &vpc.UpdatePeerConnArgs{ + // 设置对等连接的接口ID 不可更改,必选 + LocalIfId: "localIfId", + // 设置对等连接的本端端口名称 + LocalIfName: "test-update", + // 设置对等连接的本端端口描述 + Description: "test-description", + } + peerConnId := "peer-conn-id" + if err := client.UpdatePeerConn(peerConnId, args); err != nil { + fmt.Println("update peer conn error: ", err) + return + } + + fmt.Printf("update peer conn %s success", peerConnId) +} diff --git a/bce-sdk-go/examples/vpc/probe/example_create_probe.go b/bce-sdk-go/examples/vpc/probe/example_create_probe.go new file mode 100644 index 0000000..71deb3d --- /dev/null +++ b/bce-sdk-go/examples/vpc/probe/example_create_probe.go @@ -0,0 +1,34 @@ +package probeexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" + "github.com/baidubce/bce-sdk-go/util" +) + +func CreateProbe() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + createProbeArgs := &vpc.CreateProbeArgs{ + Name: "TestSDK", // 探测名称 + VpcId: "Your Vpc ID", // 探测所在vpc id + SubnetId: "Your Subnet ID", // 探测所在子网id + Protocol: "UDP", // 探测协议 + Frequency: 10, // 探测频率 + DestIp: "192.168.0.4", // 探测目标ip + DestPort: "53", // 探测目标端口 + SourceIps: []string{"192.168.0.19"}, // 探测源ip列表 + SourceIpNum: 0, // 探测源ip数量 + Payload: "test udp", // 探测包内容 + Description: "test create probe", // 探测描述 + ClientToken: util.NewUUID(), + } + response, err := client.CreateProbe(createProbeArgs) // 创建探测 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/probe/example_delete_probe.go b/bce-sdk-go/examples/vpc/probe/example_delete_probe.go new file mode 100644 index 0000000..1dfb398 --- /dev/null +++ b/bce-sdk-go/examples/vpc/probe/example_delete_probe.go @@ -0,0 +1,23 @@ +package probeexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" + "github.com/baidubce/bce-sdk-go/util" +) + +func DeleteProbe() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + probeId := "Your Probe ID" + clientToken := util.NewUUID() + err := client.DeleteProbe(probeId, clientToken) // 删除探测 + + if err != nil { + fmt.Println(err) + return + } + fmt.Printf("delete probe %s success.", probeId) +} diff --git a/bce-sdk-go/examples/vpc/probe/example_get_probe_detail.go b/bce-sdk-go/examples/vpc/probe/example_get_probe_detail.go new file mode 100644 index 0000000..b03c1c5 --- /dev/null +++ b/bce-sdk-go/examples/vpc/probe/example_get_probe_detail.go @@ -0,0 +1,32 @@ +package probeexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func GetProbeDetail() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + probeId := "Your Probe ID" + result, err := client.GetProbeDetail(probeId) // 查询探测详情 + if err != nil { + fmt.Println("get probe detail error: ", err) + return + } + + fmt.Println("probe id: ", result.ProbeId) + fmt.Println("probe name: ", result.Name) + fmt.Println("probe vpcId: ", result.VpcId) + fmt.Println("probe subnetId: ", result.SubnetId) + fmt.Println("probe description: ", result.Description) + fmt.Println("probe protocol: ", result.Protocol) + fmt.Println("probe frequency: ", result.Frequency) + fmt.Println("probe destIp: ", result.DestIp) + fmt.Println("probe destPort: ", result.DestPort) + fmt.Println("probe sourceIps: ", result.SourceIps) + fmt.Println("probe sourceIpNum: ", result.SourceIpNum) + fmt.Println("probe payload: ", result.Payload) +} diff --git a/bce-sdk-go/examples/vpc/probe/example_list_probes.go b/bce-sdk-go/examples/vpc/probe/example_list_probes.go new file mode 100644 index 0000000..5a102fc --- /dev/null +++ b/bce-sdk-go/examples/vpc/probe/example_list_probes.go @@ -0,0 +1,46 @@ +package probeexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ListProbes() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpc.ListProbesArgs{ + Marker: "20", // 指定批量获取列表的查询的起始位置 + MaxKeys: 1000, // 指定每页包含的最大数量,最大数量不超过1000。缺省值为1000 + } + result, err := client.ListProbes(args) // 查询探测列表 + if err != nil { + fmt.Println("list probes error: ", err) + return + } + + // 返回标记查询的起始位置 + fmt.Println("probe list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("probe list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("probe list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("probe list maxKeys: ", result.MaxKeys) + // 获取探测列表信息 + for _, probe := range result.Probes { + fmt.Println("probe id: ", probe.ProbeId) + fmt.Println("probe name: ", probe.Name) + fmt.Println("probe vpcId: ", probe.VpcId) + fmt.Println("probe subnetId: ", probe.SubnetId) + fmt.Println("probe description: ", probe.Description) + fmt.Println("probe protocol: ", probe.Protocol) + fmt.Println("probe frequency: ", probe.Frequency) + fmt.Println("probe destIp: ", probe.DestIp) + fmt.Println("probe destPort: ", probe.DestPort) + fmt.Println("probe sourceIps: ", probe.SourceIps) + fmt.Println("probe sourceIpNum: ", probe.SourceIpNum) + fmt.Println("probe payload: ", probe.Payload) + } +} diff --git a/bce-sdk-go/examples/vpc/probe/example_update_probe.go b/bce-sdk-go/examples/vpc/probe/example_update_probe.go new file mode 100644 index 0000000..f0597ea --- /dev/null +++ b/bce-sdk-go/examples/vpc/probe/example_update_probe.go @@ -0,0 +1,31 @@ +package probeexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" + "github.com/baidubce/bce-sdk-go/util" +) + +func UpdateProbe() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + probeId := "Your Probe ID" + updateProbeArgs := &vpc.UpdateProbeArgs{ + Name: "TestSDK1", // 探测名称 + Frequency: 20, // 探测频率 + DestIp: "192.168.0.8", // 探测目标ip + DestPort: "88", // 探测目标端口 + Payload: "test udp update", // 探测包内容 + Description: "test update probe", // 子网描述 + ClientToken: util.NewUUID(), + } + err := client.UpdateProbe(probeId, updateProbeArgs) // 更新探测 + + if err != nil { + fmt.Println(err) + return + } + fmt.Printf("update probe %s success.", probeId) +} diff --git a/bce-sdk-go/examples/vpc/route/example_create_route_rule.go b/bce-sdk-go/examples/vpc/route/example_create_route_rule.go new file mode 100644 index 0000000..9a5fa40 --- /dev/null +++ b/bce-sdk-go/examples/vpc/route/example_create_route_rule.go @@ -0,0 +1,33 @@ +package routeexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main函数用于启动程序 +func CreateRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + args := &vpc.CreateRouteRuleArgs{ + RouteTableId: "rt-hf1ezaxxxxxx", + SourceAddress: "192.168.0.0/20", + DestinationAddress: "0.0.0.0/0", + // NexthopId: "yourNexthopId", //optional + // NexthopType: "nat", //optional + // Description: "Your Description", //optional + // ClientToken: "Your Client Token", //optional + // NextHopList: []NextHop, // if you want to create multiple nexthop, you can use this field. + } + + // 创建路由规则 + result, err := VPC_CLIENT.CreateRouteRule(args) + if err != nil { + fmt.Println("create route rule error: ", err) + } + + // 输出结果 + fmt.Println(result.RouteRuleId) +} diff --git a/bce-sdk-go/examples/vpc/route/example_delete_route_rule.go b/bce-sdk-go/examples/vpc/route/example_delete_route_rule.go new file mode 100644 index 0000000..d2927c9 --- /dev/null +++ b/bce-sdk-go/examples/vpc/route/example_delete_route_rule.go @@ -0,0 +1,24 @@ +package routeexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" + "github.com/baidubce/bce-sdk-go/util" +) + +// main函数,删除路由规则 +func DeleteRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + routeRuleId := "rr-1zctgrxxxxxx" + clientToken := util.NewUUID() // "yourClientToken" + + err := VPC_CLIENT.DeleteRouteRule(routeRuleId, clientToken) + if err != nil { + fmt.Println("delete route rule error: ", err) + } + + fmt.Printf("delete route rule %s success.", routeRuleId) +} diff --git a/bce-sdk-go/examples/vpc/route/example_get_route_table_detail.go b/bce-sdk-go/examples/vpc/route/example_get_route_table_detail.go new file mode 100644 index 0000000..b30bb7a --- /dev/null +++ b/bce-sdk-go/examples/vpc/route/example_get_route_table_detail.go @@ -0,0 +1,36 @@ +package routeexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main 函数是 Go 程序的入口函数 +func GetRouteTableDetail() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + routeTableId := "rt-hf1ezardxxxx" + vpcId := "vpc-nx6bs5xxxxxx" + + // routeTableId and vpcId should not be empty at the same time + result, err := VPC_CLIENT.GetRouteTableDetail(routeTableId, vpcId) + if err != nil { + fmt.Println("get route table error: ", err) + } + + // print result + fmt.Println("result of route table id: ", result.RouteTableId) + fmt.Println("result of vpc id: ", result.VpcId) + + for _, route := range result.RouteRules { + fmt.Println("route rule id: ", route.RouteRuleId) + fmt.Println("route rule routeTableId: ", route.RouteTableId) + fmt.Println("route rule sourceAddress: ", route.SourceAddress) + fmt.Println("route rule destinationAddress: ", route.DestinationAddress) + fmt.Println("route rule nexthopId: ", route.NexthopId) + fmt.Println("route rule nexthopType: ", route.NexthopType) + fmt.Println("route rule description: ", route.Description) + } +} diff --git a/bce-sdk-go/examples/vpc/route/example_list_route_rules.go b/bce-sdk-go/examples/vpc/route/example_list_route_rules.go new file mode 100644 index 0000000..4146cce --- /dev/null +++ b/bce-sdk-go/examples/vpc/route/example_list_route_rules.go @@ -0,0 +1,38 @@ +package routeexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main函数是主函数,用于执行程序 +func GetRouteRuleDetail() { + // 设置AK、SK和endpoint + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + args := &vpc.GetRouteRuleArgs{ + RouteTableId: "rt-hf1ezaxxxxxf", + VpcId: "vpc-nx6xxxxxxxd2", + Marker: "rr-j4snfssssssm", // 该参数为路由表内的某个路由规则ID,表示从这个路由规则开始取列表 + MaxKeys: 10, + } + + // 获取路由表详情 + result, err := VPC_CLIENT.GetRouteRuleDetail(args) + if err != nil { + panic(err) + } + + for _, route := range result.RouteRules { + fmt.Println("route rule id: ", route.RouteRuleId) + fmt.Println("route rule routeTableId: ", route.RouteTableId) + fmt.Println("route rule sourceAddress: ", route.SourceAddress) + fmt.Println("route rule destinationAddress: ", route.DestinationAddress) + fmt.Println("route rule nexthopId: ", route.NexthopId) + fmt.Println("route rule nexthopType: ", route.NexthopType) + fmt.Println("route rule description: ", route.Description) + } +} diff --git a/bce-sdk-go/examples/vpc/route/example_switchroute.go b/bce-sdk-go/examples/vpc/route/example_switchroute.go new file mode 100644 index 0000000..abbb0b7 --- /dev/null +++ b/bce-sdk-go/examples/vpc/route/example_switchroute.go @@ -0,0 +1,26 @@ +package routeexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// switchRoute +// +// PARAMS: +// - routeRuleId: 主路由规则ID +// - clientToken: the idempotent token, 可选 +// - action: 切换路由规则的动作,可选值:switchRouteHA +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SwitchRoute() { + ak, sk, endpoint := "Your AK", "Your SK", "endpoint" + client, _ := vpc.NewClient(ak, sk, endpoint) // 创建vpc client + err := client.SwitchRoute("Your routeRuleId", "ClientToken") + if err != nil { + panic(err) + } + fmt.Print("SwitchRoute success!\n") +} diff --git a/bce-sdk-go/examples/vpc/route/example_update_route_rule.go b/bce-sdk-go/examples/vpc/route/example_update_route_rule.go new file mode 100644 index 0000000..962ea83 --- /dev/null +++ b/bce-sdk-go/examples/vpc/route/example_update_route_rule.go @@ -0,0 +1,28 @@ +package routeexample + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main 函数作为主函数 +func UpdateRouteRule() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + args := &vpc.UpdateRouteRuleArgs{ + RouteRuleId: "rr-1zcxxxxxxyyy", + // SourceAddress: "Your SourceAddress", // optional + // DestinationAddress: "Your DestinationAddress", // optional + // NexthopId: "your NewNexthopId", // optional + // Description: "Your New Description", // optional + } + + err := VPC_CLIENT.UpdateRouteRule(args) + if err != nil { + fmt.Println("Route rule updated fail") + } + + fmt.Println("Route rule %s updated successfully", args.RouteRuleId) +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_create_ip_reserve.go b/bce-sdk-go/examples/vpc/subnet/example_create_ip_reserve.go new file mode 100644 index 0000000..8290ad3 --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_create_ip_reserve.go @@ -0,0 +1,30 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main 函数作为 Go 语言的主函数,用于创建保留 IP。 +func CreateIpreserve() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // Initialize ak, sk, and endpoint + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) // Initialize VPC client + + args := &vpc.CreateIpreserveArgs{ + SubnetId: "sbn-4fa15xxxxxxx", // ID of the subnet to create the reserved ip segment + IpCidr: "192.168.0.0/31", // Reserved CIDR + IpVersion: 4, // IP version (4 for IPv4, 6 for IPv6) + // Description: "test", // Description of the reserved CIDR, optional + // ClientToken: "", // Client token, optional + } + + result, err := VPC_CLIENT.CreateIpreserve(args) + + if err != nil { + fmt.Println("create reserved ip error: ", err) + return + } + + fmt.Println("create reserved ip success, reserved CIDR id: ", result.IpReserveId) +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_create_subnet.go b/bce-sdk-go/examples/vpc/subnet/example_create_subnet.go new file mode 100644 index 0000000..7db4043 --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_create_subnet.go @@ -0,0 +1,26 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func CreateSubnet() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + createSubnetArgs := &vpc.CreateSubnetArgs{ + Name: "TestSDK-Subnet", // 子网名称 + Description: "vpc test", // 子网描述 + Cidr: "192.168.96.0/20", // 子网网段 + VpcId: "vpc-p1eawhw5rx4n", // vpc id + ZoneName: "cn-bj-a", // 子网可用区 + } + response, err := client.CreateSubnet(createSubnetArgs) // 创建子网 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_delete_ip_reserve.go b/bce-sdk-go/examples/vpc/subnet/example_delete_ip_reserve.go new file mode 100644 index 0000000..1a93cda --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_delete_ip_reserve.go @@ -0,0 +1,25 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main 函数用于启动程序 +func DeleteIpreserve() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // Initialize ak, sk, and endpoint + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) // Initialize VPC client + + ipReserveId := "ipr-nc4xxxxx" // ID of the reserved CIDR to be deleted + clientToken := "" // optional yourclientToken + + err := VPC_CLIENT.DeleteIpreserve(ipReserveId, clientToken) + + if err != nil { + fmt.Println("DeleteIpreserve error: ", err) + return + } + + fmt.Printf("delete reserved CIDR %s success.", ipReserveId) +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_delete_subnet.go b/bce-sdk-go/examples/vpc/subnet/example_delete_subnet.go new file mode 100644 index 0000000..e462949 --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_delete_subnet.go @@ -0,0 +1,22 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func DeleteSubnet() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) + + subnetID := "sbn-5uj2t9f1jazj" // 子网ID + clientToken := "be31b98c-5141-4838-9830-9be700de5a20" // 幂等性Token,是一个长度不超过64位的ASCII字符串,见 https://cloud.baidu.com/doc/VPC/s/gjwvyu77i#%E5%B9%82%E7%AD%89%E6%80%A7 + + err := client.DeleteSubnet(subnetID, clientToken) // 删除子网 + + if err != nil { + fmt.Println(err) + } + fmt.Println("delete subnet success.") +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_get_subnet.go b/bce-sdk-go/examples/vpc/subnet/example_get_subnet.go new file mode 100644 index 0000000..9c3d47b --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_get_subnet.go @@ -0,0 +1,21 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ShowSubnet() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + subnetID := "sbn-u166vdnqqubi" // 子网id + + response, err := client.GetSubnetDetail(subnetID) // 获取子网详情 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_list_ip_reserve.go b/bce-sdk-go/examples/vpc/subnet/example_list_ip_reserve.go new file mode 100644 index 0000000..0cd56b6 --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_list_ip_reserve.go @@ -0,0 +1,34 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// main函数定义了程序入口 +func ListIpreserve() { + // 设置AK、SK和Endpoint + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // Initialize ak, sk, and endpoint + + // 创建VPC客户端 + VPC_CLIENT, _ := vpc.NewClient(ak, sk, endpoint) + + args := &vpc.ListIpeserveArgs{ + SubnetId: "sbn-4fxx51yxxxx", + Marker: "", // 查询的起始位置,为空则从第一条开始查询 + MaxKeys: 10, + } + + // 添加查询保留IP范围的代码 + result, err := VPC_CLIENT.ListIpreserve(args) + if err != nil { + fmt.Printf("List reserved IP ranges failed with %s\n", err) + } + + // 输出子网ID和保留IP范围信息 + for _, IpReserve := range result.IpReserves { + fmt.Printf("IP Range: %s, Description: %s\n", IpReserve.IpCidr, IpReserve.SubnetId) + fmt.Println("isTruncated %d", result.IsTruncated) + } +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_list_subnet.go b/bce-sdk-go/examples/vpc/subnet/example_list_subnet.go new file mode 100644 index 0000000..6c91366 --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_list_subnet.go @@ -0,0 +1,25 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ListSubnet() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpc.ListSubnetArgs{ + MaxKeys: 100, // 设置每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 + Marker: "", // 设置批量获取列表的查询的起始位置,是一个由系统生成的字符串 + VpcId: "vpc-p1eawhw5rx4n", // 子网所属vpc id + } + + response, err := client.ListSubnets(args) // 获取子网列表 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/subnet/example_update_subnet.go b/bce-sdk-go/examples/vpc/subnet/example_update_subnet.go new file mode 100644 index 0000000..6315aa1 --- /dev/null +++ b/bce-sdk-go/examples/vpc/subnet/example_update_subnet.go @@ -0,0 +1,27 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func UpdateSubnet() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + clientToken := "be31b98c-5e41-4838-9830-9be700de5a20" // 幂等性Token,是一个长度不超过64位的ASCII字符串,见 https://cloud.baidu.com/doc/VPC/s/gjwvyu77i#%E5%B9%82%E7%AD%89%E6%80%A7 + subnetID := "sbn-u166vdnqqubi" // 子网ID + + updateSubnetArgs := &vpc.UpdateSubnetArgs{ + ClientToken: clientToken, + Name: "test_subnet", // 更新子网名称 + Description: "", // 更新子网描述 + } + err := client.UpdateSubnet(subnetID, updateSubnetArgs) // 更新子网 + + if err != nil { + fmt.Println(err) + } + fmt.Println("update subnet success.") +} diff --git a/bce-sdk-go/examples/vpc/vpc/example_create_vpc.go b/bce-sdk-go/examples/vpc/vpc/example_create_vpc.go new file mode 100644 index 0000000..2773c23 --- /dev/null +++ b/bce-sdk-go/examples/vpc/vpc/example_create_vpc.go @@ -0,0 +1,31 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func CreateVpc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + createVpcArgs := &vpc.CreateVPCArgs{ + Name: "TestSDK-VPC", // vpc名称 + Description: "vpc test", // vpc描述 + Cidr: "192.168.0.0/16", // vpc网段 + Tags: []model.TagModel{ // vpc标签 + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + } + response, err := client.CreateVPC(createVpcArgs) // 创建vpc + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/vpc/example_delete_vpc.go b/bce-sdk-go/examples/vpc/vpc/example_delete_vpc.go new file mode 100644 index 0000000..6bb5aa0 --- /dev/null +++ b/bce-sdk-go/examples/vpc/vpc/example_delete_vpc.go @@ -0,0 +1,22 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func DeleteVpc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + vpcID := "vpc-is0j69zp08cx" // 要删除的VPC的ID + clientToken := "be31b98c-5141-4838-9830-9be700de5a20" // 幂等性Token,是一个长度不超过64位的ASCII字符串,见 https://cloud.baidu.com/doc/VPC/s/gjwvyu77i#%E5%B9%82%E7%AD%89%E6%80%A7 + + err := client.DeleteVPC(vpcID, clientToken) // 删除 VPC + + if err != nil { + fmt.Println(err) + } + fmt.Println("delete vpc success.") +} diff --git a/bce-sdk-go/examples/vpc/vpc/example_get_vpc.go b/bce-sdk-go/examples/vpc/vpc/example_get_vpc.go new file mode 100644 index 0000000..8801c2f --- /dev/null +++ b/bce-sdk-go/examples/vpc/vpc/example_get_vpc.go @@ -0,0 +1,21 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ShowVpc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + vpcID := "vpc-p1eawhw5rx4n" // vpc id + + response, err := client.GetVPCDetail(vpcID) // 获取vpc详情 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/vpc/example_get_vpc_ip.go b/bce-sdk-go/examples/vpc/vpc/example_get_vpc_ip.go new file mode 100644 index 0000000..0e0f0dd --- /dev/null +++ b/bce-sdk-go/examples/vpc/vpc/example_get_vpc_ip.go @@ -0,0 +1,27 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ShowVpcIP() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + vpcID := "vpc-p1eawhw5rx4n" // vpc id + privateIPAddresses := []string{"192.168.0.1"} // 私有ip地址 + + args := &vpc.GetVpcPrivateIpArgs{ + VpcId: vpcID, + PrivateIpAddresses: privateIPAddresses, + } + + response, err := client.GetPrivateIpAddressesInfo(args) // 获取vpc私有ip信息 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/vpc/example_list_vpc.go b/bce-sdk-go/examples/vpc/vpc/example_list_vpc.go new file mode 100644 index 0000000..1b127e7 --- /dev/null +++ b/bce-sdk-go/examples/vpc/vpc/example_list_vpc.go @@ -0,0 +1,24 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func ListVpc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpc.ListVPCArgs{ + MaxKeys: 100, // 设置每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 + Marker: "", // 设置批量获取列表的查询的起始位置,是一个由系统生成的字符串 + } + + response, err := client.ListVPC(args) // 获取vpc列表 + + if err != nil { + fmt.Println(err) + } + fmt.Println(response) +} diff --git a/bce-sdk-go/examples/vpc/vpc/example_update_vpc.go b/bce-sdk-go/examples/vpc/vpc/example_update_vpc.go new file mode 100644 index 0000000..83b1039 --- /dev/null +++ b/bce-sdk-go/examples/vpc/vpc/example_update_vpc.go @@ -0,0 +1,27 @@ +package vpcexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +func UpdateVpc() { + ak, sk, endpoint := "Your Ak", "Your Sk", "Your endpoint" // 初始化ak, sk和endpoint + client, _ := vpc.NewClient(ak, sk, endpoint) // 初始化client + + clientToken := "be31b98c-5e41-4838-9830-9be700de5a20" // 幂等性Token,是一个长度不超过64位的ASCII字符串,见 https://cloud.baidu.com/doc/VPC/s/gjwvyu77i#%E5%B9%82%E7%AD%89%E6%80%A7 + vpcID := "vpc-p1eawhw5rx4n" // vpc id + + updateVpcArgs := &vpc.UpdateVPCArgs{ + ClientToken: clientToken, + Name: "test_vpc", // 更新vpc名称 + Description: "", // 更新vpc描述 + } + err := client.UpdateVPC(vpcID, updateVpcArgs) // 更新vpc + + if err != nil { + fmt.Println(err) + } + fmt.Println("update vpc success.") +} diff --git a/bce-sdk-go/examples/vpn/example_batch_create_ssl_vpn_user.go b/bce-sdk-go/examples/vpn/example_batch_create_ssl_vpn_user.go new file mode 100644 index 0000000..d98b883 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_batch_create_ssl_vpn_user.go @@ -0,0 +1,37 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func BatchCreateSslVpnUser() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + desc1 := "user1 description" + args := &vpn.BatchCreateSslVpnUserArgs{ + ClientToken: "Your ClientToken", // client token + VpnId: "Your Vpn Id", // vpn id + SslVpnUsers: []vpn.SslVpnUser{ + { + UserName: "user1test", // 用户名 + Password: "psd123456!", // 密码 + Description: &desc1, // 描述 + }, + { + UserName: "user2test", // 用户名 + Password: "psd123456!", // 密码 + }, + }, + } + result, err := client.BatchCreateSslVpnUser(args) + if err != nil { + fmt.Printf("batch create ssl vpn user error: %+v\n", err) + return + } + + fmt.Println("batch create ssl vpn user success, result: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_bind_eip.go b/bce-sdk-go/examples/vpn/example_bind_eip.go new file mode 100644 index 0000000..a87eb0e --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_bind_eip.go @@ -0,0 +1,28 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func BindEip() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.BindEipArgs{ + ClientToken: "Your ClientToken", // client token + Eip: "Your Eip Address", // eip address + } + err := client.BindEip( + "vpnId", // vpn id + args, + ) + if err != nil { + fmt.Printf("bind eip error: %+v\n", err) + return + } + + fmt.Println("bind eip success") +} diff --git a/bce-sdk-go/examples/vpn/example_create_ssl_vpn_server.go b/bce-sdk-go/examples/vpn/example_create_ssl_vpn_server.go new file mode 100644 index 0000000..cfbd12e --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_create_ssl_vpn_server.go @@ -0,0 +1,32 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func CreateSslVpnServer() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + interfaceTypeStr := "tun" + clientDnsStr := "" + args := &vpn.CreateSslVpnServerArgs{ + ClientToken: "Your ClientToken", // client token + VpnId: "Your Vpn Id", // vpn id + SslVpnServerName: "server_1", + InterfaceType: &interfaceTypeStr, + LocalSubnets: []string{"192.168.0.0/20"}, + RemoteSubnet: "192.168.100.0/24", + ClientDns: &clientDnsStr, + } + result, err := client.CreateSslVpnServer(args) + if err != nil { + fmt.Printf("create ssl vpn server error: %+v\n", err) + return + } + + fmt.Println("create ssl vpn server success, result: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_create_vpn_conn.go b/bce-sdk-go/examples/vpn/example_create_vpn_conn.go new file mode 100644 index 0000000..90ab7ce --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_create_vpn_conn.go @@ -0,0 +1,44 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func CreateVpnConn() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.CreateVpnConnArgs{ + VpnId: "Your VPN ID", // vpn id + VpnConnName: "Your VPN Conn Name", // vpn conn name + LocalIp: "0.1.2.3", // local ip + SecretKey: "!sdse154d", // secret key + LocalSubnets: []string{"192.168.0.0/20"}, // local subnets + RemoteIp: "3.4.5.6", // remote ip + RemoteSubnets: []string{"192.168.100.0/24"}, // remote subnets + CreateIkeConfig: &vpn.CreateIkeConfig{ // ike config + IkeVersion: "v1", + IkeMode: "main", + IkeEncAlg: "aes", + IkeAuthAlg: "sha1", + IkePfs: "group2", + IkeLifeTime: 25500, + }, + CreateIpsecConfig: &vpn.CreateIpsecConfig{ // ipsec config + IpsecEncAlg: "aes", + IpsecAuthAlg: "sha1", + IpsecPfs: "group2", + IpsecLifetime: 25500, + }, + } + result, err := client.CreateVpnConn(args) + if err != nil { + fmt.Printf("create vpn conn error: %+v\n", err) + return + } + + fmt.Println("create vpn conn success, vpn: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_create_vpn_gateway.go b/bce-sdk-go/examples/vpn/example_create_vpn_gateway.go new file mode 100644 index 0000000..08e768a --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_create_vpn_gateway.go @@ -0,0 +1,34 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func CreateVpnGateway() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.CreateVpnGatewayArgs{ + VpnName: "Your VPN Name", // vpn name + Description: "vpn test", // vpn description + VpcId: "vpcId", // vpc id + Billing: &vpn.Billing{ // billing info + PaymentTiming: vpn.PAYMENT_TIMING_PREPAID, + Reservation: &vpn.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + ClientToken: "Your ClientToken", // client token + } + result, err := client.CreateVpnGateway(args) + if err != nil { + fmt.Printf("create vpn error: %+v\n", err) + return + } + + fmt.Println("create vpn success, vpn: ", result.VpnId) +} diff --git a/bce-sdk-go/examples/vpn/example_delete_ssl_vpn_server.go b/bce-sdk-go/examples/vpn/example_delete_ssl_vpn_server.go new file mode 100644 index 0000000..69085bc --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_delete_ssl_vpn_server.go @@ -0,0 +1,25 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func DeleteSslVpnServer() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + err := client.DeleteSslVpnServer( + "Your Vpn Id", // vpn id + "Your SslVpnServer Id", // ssl vpn server id + "Your ClientToken", // client token + ) + if err != nil { + fmt.Printf("delete ssl vpn server error: %+v\n", err) + return + } + + fmt.Println("delete ssl vpn server success") +} diff --git a/bce-sdk-go/examples/vpn/example_delete_ssl_vpn_user.go b/bce-sdk-go/examples/vpn/example_delete_ssl_vpn_user.go new file mode 100644 index 0000000..7ae11f7 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_delete_ssl_vpn_user.go @@ -0,0 +1,25 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func DeleteSslVpnUser() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + err := client.DeleteSslVpnUser( + "Your Vpn Id", // vpn id + "Your User Id", // user id + "Your ClientToken", // client token + ) + if err != nil { + fmt.Printf("delete ssl vpn user error: %+v\n", err) + return + } + + fmt.Println("delete ssl vpn user success") +} diff --git a/bce-sdk-go/examples/vpn/example_delete_vpn_conn.go b/bce-sdk-go/examples/vpn/example_delete_vpn_conn.go new file mode 100644 index 0000000..b585d2a --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_delete_vpn_conn.go @@ -0,0 +1,24 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func DeleteVpnConn() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + err := client.DeleteVpnConn( + "Your VpnConnId", // vpn conn id + "Your ClientToken", // client token + ) + if err != nil { + fmt.Printf("delete vpn conn error: %+v\n", err) + return + } + + fmt.Println("delete vpn conn success") +} diff --git a/bce-sdk-go/examples/vpn/example_delete_vpn_gateway.go b/bce-sdk-go/examples/vpn/example_delete_vpn_gateway.go new file mode 100644 index 0000000..f7538da --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_delete_vpn_gateway.go @@ -0,0 +1,24 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func DeleteVpnGateway() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + err := client.DeleteVpnGateway( + "vpnId", // vpn id + "Your ClientToken", // client token + ) + if err != nil { + fmt.Printf("delete vpn error: %+v\n", err) + return + } + + fmt.Println("delete vpn success") +} diff --git a/bce-sdk-go/examples/vpn/example_get_ssl_vpn_server.go b/bce-sdk-go/examples/vpn/example_get_ssl_vpn_server.go new file mode 100644 index 0000000..4559f5b --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_get_ssl_vpn_server.go @@ -0,0 +1,24 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func GetSslVpnServer() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + result, err := client.GetSslVpnServer( + "Your Vpn Id", // vpn id + "Your ClientToken", // client token + ) + if err != nil { + fmt.Printf("get ssl vpn server error: %+v\n", err) + return + } + + fmt.Println("get ssl vpn server success, result: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_get_vpn_gateway_detail.go b/bce-sdk-go/examples/vpn/example_get_vpn_gateway_detail.go new file mode 100644 index 0000000..73924d0 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_get_vpn_gateway_detail.go @@ -0,0 +1,21 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func GetVpnGatewayDetail() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + result, err := client.GetVpnGatewayDetail("Your VPN ID") + if err != nil { + fmt.Printf("get vpn error: %+v\n", err) + return + } + + fmt.Println("get vpn success, result: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_list_ssl_vpn_user.go b/bce-sdk-go/examples/vpn/example_list_ssl_vpn_user.go new file mode 100644 index 0000000..81e9725 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_list_ssl_vpn_user.go @@ -0,0 +1,24 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func ListSslVpnUser() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.ListSslVpnUserArgs{ + VpnId: "Your Vpn Id", // vpn id + } + result, err := client.ListSslVpnUser(args) + if err != nil { + fmt.Printf("list ssl vpn user error: %+v\n", err) + return + } + + fmt.Println("list ssl vpn user success, result: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_list_vpn_conn.go b/bce-sdk-go/examples/vpn/example_list_vpn_conn.go new file mode 100644 index 0000000..b308a8a --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_list_vpn_conn.go @@ -0,0 +1,21 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func ListVpnConn() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + result, err := client.ListVpnConn("Your VpnConnId") + if err != nil { + fmt.Printf("list vpn conn error: %+v\n", err) + return + } + + fmt.Println("list vpn conn success, result: ", result) +} diff --git a/bce-sdk-go/examples/vpn/example_list_vpn_gateway.go b/bce-sdk-go/examples/vpn/example_list_vpn_gateway.go new file mode 100644 index 0000000..c92ec8c --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_list_vpn_gateway.go @@ -0,0 +1,24 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func ListVpnGateway() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.ListVpnGatewayArgs{ + VpcId: "vpcId", // vpc id + } + results, err := client.ListVpnGateway(args) + if err != nil { + fmt.Printf("list vpn error: %+v\n", err) + return + } + + fmt.Println("list vpn success, results: ", results) +} diff --git a/bce-sdk-go/examples/vpn/example_renew_vpn_gateway.go b/bce-sdk-go/examples/vpn/example_renew_vpn_gateway.go new file mode 100644 index 0000000..5df24a2 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_renew_vpn_gateway.go @@ -0,0 +1,33 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func RenewVpnGateway() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.RenewVpnGatewayArgs{ + Billing: &vpn.Billing{ // billing info + Reservation: &vpn.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + ClientToken: "Your ClientToken", // client token + } + err := client.RenewVpnGateway( + "vpnId", // vpn id + args, + ) + if err != nil { + fmt.Printf("renew vpn error: %+v\n", err) + return + } + + fmt.Println("renew vpn success") +} diff --git a/bce-sdk-go/examples/vpn/example_unbind_eip.go b/bce-sdk-go/examples/vpn/example_unbind_eip.go new file mode 100644 index 0000000..1785840 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_unbind_eip.go @@ -0,0 +1,24 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func UnBindEip() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + err := client.UnBindEip( + "vpnId", // vpn id + "Your ClientToken", // client token + ) + if err != nil { + fmt.Printf("unbind eip error: %+v\n", err) + return + } + + fmt.Println("unbind eip success") +} diff --git a/bce-sdk-go/examples/vpn/example_update_ssl_vpn_server.go b/bce-sdk-go/examples/vpn/example_update_ssl_vpn_server.go new file mode 100644 index 0000000..54eabf0 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_update_ssl_vpn_server.go @@ -0,0 +1,33 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func UpdateSslVpnServer() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + clientDnsStr := "" + args := &vpn.UpdateSslVpnServerArgs{ + ClientToken: "Your ClientToken", // client token + VpnId: "Your Vpn Id", // vpn id + SslVpnServerId: "Your SslVpnServer Id", // ssl vpn server id + UpdateSslVpnServer: &vpn.UpdateSslVpnServer{ + SslVpnServerName: "Your SslVpnServer Name", // ssl vpn server name + LocalSubnets: []string{"192.168.0.0/20"}, // local subnets + RemoteSubnet: "192.168.100.0/24", // remote subnet + ClientDns: &clientDnsStr, // client dns + }, + } + err := client.UpdateSslVpnServer(args) + if err != nil { + fmt.Printf("update ssl vpn server error: %+v\n", err) + return + } + + fmt.Println("update ssl vpn server success") +} diff --git a/bce-sdk-go/examples/vpn/example_update_ssl_vpn_user.go b/bce-sdk-go/examples/vpn/example_update_ssl_vpn_user.go new file mode 100644 index 0000000..811626e --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_update_ssl_vpn_user.go @@ -0,0 +1,31 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func UpdateSslVpnUser() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + desc := "333" + args := &vpn.UpdateSslVpnUserArgs{ + ClientToken: "Your ClientToken", // client token + VpnId: "Your Vpn Id", // vpn id + UserId: "Your User Id", // user id + SslVpnUser: &vpn.UpdateSslVpnUser{ + Password: "psd123456!", // 密码 + Description: &desc, // 描述 + }, + } + err := client.UpdateSslVpnUser(args) + if err != nil { + fmt.Printf("update ssl vpn user error: %+v\n", err) + return + } + + fmt.Println("update ssl vpn user success") +} diff --git a/bce-sdk-go/examples/vpn/example_update_vpn_conn.go b/bce-sdk-go/examples/vpn/example_update_vpn_conn.go new file mode 100644 index 0000000..641ecfa --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_update_vpn_conn.go @@ -0,0 +1,47 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func UpdateVpnConn() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.UpdateVpnConnArgs{ + VpnConnId: "", + UpdateVpnconn: &vpn.CreateVpnConnArgs{ + VpnId: "Your VPN ID", // vpn id + VpnConnName: "Your VPN Conn Name", // vpn conn name + LocalIp: "0.1.2.3", // local ip + SecretKey: "!sdse154d", // secret key + LocalSubnets: []string{"192.168.0.0/20"}, // local subnets + RemoteIp: "3.4.5.6", // remote ip + RemoteSubnets: []string{"192.168.100.0/24"}, // remote subnets + CreateIkeConfig: &vpn.CreateIkeConfig{ // ike config + IkeVersion: "v1", + IkeMode: "main", + IkeEncAlg: "aes", + IkeAuthAlg: "sha1", + IkePfs: "group2", + IkeLifeTime: 25500, + }, + CreateIpsecConfig: &vpn.CreateIpsecConfig{ // ipsec config + IpsecEncAlg: "aes", + IpsecAuthAlg: "sha1", + IpsecPfs: "group2", + IpsecLifetime: 25500, + }, + }, + } + err := client.UpdateVpnConn(args) + if err != nil { + fmt.Printf("update vpn conn error: %+v\n", err) + return + } + + fmt.Println("update vpn conn success") +} diff --git a/bce-sdk-go/examples/vpn/example_update_vpn_gateway.go b/bce-sdk-go/examples/vpn/example_update_vpn_gateway.go new file mode 100644 index 0000000..29760b1 --- /dev/null +++ b/bce-sdk-go/examples/vpn/example_update_vpn_gateway.go @@ -0,0 +1,29 @@ +package vpnexamples + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/vpn" +) + +func UpdateVpnGateway() { + ak, sk, endpoint := "Your AK", "Your SK", "vpn.bj.baidubce.com" + + client, _ := vpn.NewClient(ak, sk, endpoint) // 初始化client + + args := &vpn.UpdateVpnGatewayArgs{ + ClientToken: "Your ClientToken", // client token + Name: "Your VPN Name", // vpn name + } + + err := client.UpdateVpnGateway( + "vpnId", // vpn id + args, + ) + if err != nil { + fmt.Printf("update vpn error: %+v\n", err) + return + } + + fmt.Println("update vpn success") +} diff --git a/bce-sdk-go/go.mod b/bce-sdk-go/go.mod new file mode 100644 index 0000000..6150974 --- /dev/null +++ b/bce-sdk-go/go.mod @@ -0,0 +1,3 @@ +module github.com/baidubce/bce-sdk-go + +go 1.11 diff --git a/bce-sdk-go/http/client.go b/bce-sdk-go/http/client.go new file mode 100644 index 0000000..e111d61 --- /dev/null +++ b/bce-sdk-go/http/client.go @@ -0,0 +1,175 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the execute function to send http request and get response + +// Package http defines the structure of request and response which used to access the BCE services +// as well as the http constant headers and and methods. And finally implement the `Execute` funct- +// ion to do the work. +package http + +import ( + "net" + "net/http" + "net/url" + "sync" + "time" +) + +const ( + defaultMaxIdleConnsPerHost = 500 + defaultResponseHeaderTimeout = 60 * time.Second + defaultDialTimeout = 30 * time.Second + defaultSmallInterval = 600 * time.Second + defaultLargeInterval = 1200 * time.Second +) + +// The httpClient is the global variable to send the request and get response +// for reuse and the Client provided by the Go standard library is thread safe. +var ( + httpClient *http.Client + transport *http.Transport +) + +type timeoutConn struct { + conn net.Conn + smallInterval time.Duration + largeInterval time.Duration +} + +func (c *timeoutConn) Read(b []byte) (n int, err error) { + c.SetReadDeadline(time.Now().Add(c.smallInterval)) + n, err = c.conn.Read(b) + c.SetReadDeadline(time.Now().Add(c.largeInterval)) + return n, err +} +func (c *timeoutConn) Write(b []byte) (n int, err error) { + c.SetWriteDeadline(time.Now().Add(c.smallInterval)) + n, err = c.conn.Write(b) + c.SetWriteDeadline(time.Now().Add(c.largeInterval)) + return n, err +} +func (c *timeoutConn) Close() error { return c.conn.Close() } +func (c *timeoutConn) LocalAddr() net.Addr { return c.conn.LocalAddr() } +func (c *timeoutConn) RemoteAddr() net.Addr { return c.conn.RemoteAddr() } +func (c *timeoutConn) SetDeadline(t time.Time) error { return c.conn.SetDeadline(t) } +func (c *timeoutConn) SetReadDeadline(t time.Time) error { return c.conn.SetReadDeadline(t) } +func (c *timeoutConn) SetWriteDeadline(t time.Time) error { return c.conn.SetWriteDeadline(t) } + +type ClientConfig struct { + RedirectDisabled bool +} + +var customizeInit sync.Once + +func InitClient(config ClientConfig) { + customizeInit.Do(func() { + httpClient = &http.Client{} + transport = &http.Transport{ + MaxIdleConnsPerHost: defaultMaxIdleConnsPerHost, + ResponseHeaderTimeout: defaultResponseHeaderTimeout, + Dial: func(network, address string) (net.Conn, error) { + conn, err := net.DialTimeout(network, address, defaultDialTimeout) + if err != nil { + return nil, err + } + tc := &timeoutConn{conn, defaultSmallInterval, defaultLargeInterval} + tc.SetReadDeadline(time.Now().Add(defaultLargeInterval)) + return tc, nil + }, + } + httpClient.Transport = transport + if config.RedirectDisabled { + httpClient.CheckRedirect = func(req *http.Request, via []*http.Request) error { + return http.ErrUseLastResponse + } + } + }) +} + +// Execute - do the http requset and get the response +// +// PARAMS: +// - request: the http request instance to be sent +// +// RETURNS: +// - response: the http response returned from the server +// - error: nil if ok otherwise the specific error +func Execute(request *Request) (*Response, error) { + // Build the request object for the current requesting + httpRequest := &http.Request{ + Proto: "HTTP/1.1", + ProtoMajor: 1, + ProtoMinor: 1, + } + + // Set the connection timeout for current request + httpClient.Timeout = time.Duration(request.Timeout()) * time.Second + + // Set the request method + httpRequest.Method = request.Method() + + // Set the request url + internalUrl := &url.URL{ + Scheme: request.Protocol(), + Host: request.Host(), + Path: request.Uri(), + RawQuery: request.QueryString()} + httpRequest.URL = internalUrl + + // Set the request headers + internalHeader := make(http.Header) + for k, v := range request.Headers() { + val := make([]string, 0, 1) + val = append(val, v) + internalHeader[k] = val + } + httpRequest.Header = internalHeader + + if request.Body() != nil { + if request.Length() > 0 { + httpRequest.ContentLength = request.Length() + httpRequest.Body = request.Body() + } else if request.Length() < 0 { + // if set body and ContentLength <= 0, will be chunked + httpRequest.Body = request.Body() + } // else {} body == nil and ContentLength == 0 + } + + // Set the proxy setting if needed + if len(request.ProxyUrl()) != 0 { + transport.Proxy = func(_ *http.Request) (*url.URL, error) { + return url.Parse(request.ProxyUrl()) + } + } + + // Perform the http request and get response + // It needs to explicitly close the keep-alive connections when error occurs for the request + // that may continue sending request's data subsequently. + start := time.Now() + + httpResponse, err := httpClient.Do(httpRequest) + + end := time.Now() + if err != nil { + transport.CloseIdleConnections() + return nil, err + } + if httpResponse.StatusCode >= 400 && + (httpRequest.Method == PUT || httpRequest.Method == POST) { + transport.CloseIdleConnections() + } + response := &Response{httpResponse, end.Sub(start)} + return response, nil +} diff --git a/bce-sdk-go/http/constants.go b/bce-sdk-go/http/constants.go new file mode 100644 index 0000000..404ee74 --- /dev/null +++ b/bce-sdk-go/http/constants.go @@ -0,0 +1,86 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// constants.go - defines constants of the BCE http package including headers and methods + +package http + +// Constants of the supported HTTP methods for BCE +const ( + GET = "GET" + PUT = "PUT" + POST = "POST" + DELETE = "DELETE" + HEAD = "HEAD" + OPTIONS = "OPTIONS" + PATCH = "PATCH" +) + +// Constants of the HTTP headers for BCE +const ( + // Standard HTTP Headers + AUTHORIZATION = "Authorization" + CACHE_CONTROL = "Cache-Control" + CONTENT_DISPOSITION = "Content-Disposition" + CONTENT_ENCODING = "Content-Encoding" + CONTENT_LANGUAGE = "Content-Language" + CONTENT_LENGTH = "Content-Length" + CONTENT_MD5 = "Content-Md5" + CONTENT_RANGE = "Content-Range" + CONTENT_TYPE = "Content-Type" + DATE = "Date" + ETAG = "Etag" + EXPIRES = "Expires" + HOST = "Host" + LAST_MODIFIED = "Last-Modified" + LOCATION = "Location" + RANGE = "Range" + SERVER = "Server" + TRANSFER_ENCODING = "Transfer-Encoding" + USER_AGENT = "User-Agent" + + // BCE Common HTTP Headers + BCE_PREFIX = "x-bce-" + BCE_ACL = "x-bce-acl" + BCE_GRANT_READ = "x-bce-grant-read" + BCE_GRANT_FULL_CONTROL = "x-bce-grant-full-control" + BCE_CONTENT_SHA256 = "x-bce-content-sha256" + BCE_CONTENT_CRC32 = "x-bce-content-crc32" + BCE_REQUEST_ID = "x-bce-request-id" + BCE_USER_METADATA_PREFIX = "x-bce-meta-" + BCE_SECURITY_TOKEN = "x-bce-security-token" + BCE_DATE = "x-bce-date" + + // BOS HTTP Headers + BCE_COPY_METADATA_DIRECTIVE = "x-bce-metadata-directive" + BCE_COPY_SOURCE = "x-bce-copy-source" + BCE_COPY_SOURCE_IF_MATCH = "x-bce-copy-source-if-match" + BCE_COPY_SOURCE_IF_MODIFIED_SINCE = "x-bce-copy-source-if-modified-since" + BCE_COPY_SOURCE_IF_NONE_MATCH = "x-bce-copy-source-if-none-match" + BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE = "x-bce-copy-source-if-unmodified-since" + BCE_COPY_SOURCE_RANGE = "x-bce-copy-source-range" + BCE_DEBUG_ID = "x-bce-debug-id" + BCE_OBJECT_TYPE = "x-bce-object-type" + BCE_NEXT_APPEND_OFFSET = "x-bce-next-append-offset" + BCE_STORAGE_CLASS = "x-bce-storage-class" + BCE_PROCESS = "x-bce-process" + BCE_RESTORE_TIER = "x-bce-restore-tier" + BCE_RESTORE_DAYS = "x-bce-restore-days" + BCE_RESTORE = "x-bce-restore" + BCE_FORBID_OVERWRITE = "x-bce-forbid-overwrite" + BCE_SYMLINK_TARGET = "x-bce-symlink-target" + BCE_SYMLINK_BUCKET = "x-bce-symlink-bucket" + BCE_TRAFFIC_LIMIT = "x-bce-traffic-limit" + BCE_BUCKET_TYPE = "x-bce-bucket-type" +) diff --git a/bce-sdk-go/http/request.go b/bce-sdk-go/http/request.go new file mode 100644 index 0000000..964c570 --- /dev/null +++ b/bce-sdk-go/http/request.go @@ -0,0 +1,225 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// request.go - the custom HTTP request for BCE + +package http + +import ( + "fmt" + "io" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/util" +) + +// Reauest stands for the general http request structure to make request to the BCE services. +type Request struct { + protocol string + host string + port int + method string + uri string + proxyUrl string + timeout int + headers map[string]string + params map[string]string + + // Optional body and length fields to set the body stream and content length + body io.ReadCloser + length int64 +} + +func (r *Request) Protocol() string { + return r.protocol +} + +func (r *Request) SetProtocol(protocol string) { + r.protocol = protocol +} + +func (r *Request) Endpoint() string { + if r.host == "" { + return "" + } + return r.protocol + "://" + r.host +} + +func (r *Request) SetEndpoint(endpoint string) { + pos := strings.Index(endpoint, "://") + rest := endpoint + if pos != -1 { + r.protocol = endpoint[0:pos] + rest = endpoint[pos+3:] + } else { + r.protocol = "http" + } + + r.SetHost(rest) +} + +func (r *Request) Host() string { + return r.host +} + +func (r *Request) SetHost(host string) { + r.host = host + pos := strings.Index(host, ":") + if pos != -1 { + p, e := strconv.Atoi(host[pos+1:]) + if e == nil { + r.port = p + } + } + + if r.port == 0 { + if r.protocol == "http" { + r.port = 80 + } else if r.protocol == "https" { + r.port = 443 + } + } +} + +func (r *Request) Port() int { + return r.port +} + +func (r *Request) SetPort(port int) { + // Port can be set by the endpoint or host, this method is rarely used. + r.port = port +} + +func (r *Request) Headers() map[string]string { + return r.headers +} + +func (r *Request) SetHeaders(headers map[string]string) { + r.headers = headers +} + +func (r *Request) Header(key string) string { + if v, ok := r.headers[key]; ok { + return v + } + return "" +} + +func (r *Request) SetHeader(key, value string) { + if r.headers == nil { + r.headers = make(map[string]string) + } + r.headers[key] = value +} + +func (r *Request) Params() map[string]string { + return r.params +} + +func (r *Request) SetParams(params map[string]string) { + r.params = params +} + +func (r *Request) Param(key string) string { + if v, ok := r.params[key]; ok { + return v + } + return "" +} + +func (r *Request) SetParam(key, value string) { + if r.params == nil { + r.params = make(map[string]string) + } + r.params[key] = value +} + +func (r *Request) QueryString() string { + buf := make([]string, 0, len(r.params)) + for k, v := range r.params { + if len(v) == 0 { + buf = append(buf, util.UriEncode(k, true)) + } else { + buf = append(buf, util.UriEncode(k, true)+"="+util.UriEncode(v, true)) + } + } + return strings.Join(buf, "&") +} + +func (r *Request) Method() string { + return r.method +} + +func (r *Request) SetMethod(method string) { + r.method = method +} + +func (r *Request) Uri() string { + return r.uri +} + +func (r *Request) SetUri(uri string) { + r.uri = uri +} + +func (r *Request) ProxyUrl() string { + return r.proxyUrl +} + +func (r *Request) SetProxyUrl(url string) { + r.proxyUrl = url +} + +func (r *Request) Timeout() int { + return r.timeout +} + +func (r *Request) SetTimeout(timeout int) { + r.timeout = timeout +} + +func (r *Request) Body() io.ReadCloser { + return r.body +} + +func (r *Request) SetBody(stream io.ReadCloser) { + r.body = stream +} + +func (r *Request) Length() int64 { + return r.length +} + +func (r *Request) SetLength(l int64) { + r.length = l +} + +func (r *Request) GenerateUrl(addPort bool) string { + if addPort { + return fmt.Sprintf("%s://%s:%d%s?%s", + r.protocol, r.host, r.port, r.uri, r.QueryString()) + } else { + return fmt.Sprintf("%s://%s%s?%s", r.protocol, r.host, r.uri, r.QueryString()) + } +} + +func (r *Request) String() string { + header := make([]string, 0, len(r.headers)) + for k, v := range r.headers { + header = append(header, "\t"+k+"="+v) + } + return fmt.Sprintf("\t%s %s\n%v", + r.method, r.GenerateUrl(false), strings.Join(header, "\n")) +} diff --git a/bce-sdk-go/http/response.go b/bce-sdk-go/http/response.go new file mode 100644 index 0000000..98632fc --- /dev/null +++ b/bce-sdk-go/http/response.go @@ -0,0 +1,74 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// response.go - the custom HTTP response for BCE + +package http + +import ( + "io" + "net/http" + "time" +) + +// Response defines the general http response structure for accessing the BCE services. +type Response struct { + httpResponse *http.Response // the standard libaray http.Response object + elapsedTime time.Duration // elapsed time just from sending request to receiving response +} + +func (r *Response) StatusText() string { + return r.httpResponse.Status +} + +func (r *Response) StatusCode() int { + return r.httpResponse.StatusCode +} + +func (r *Response) Protocol() string { + return r.httpResponse.Proto +} + +func (r *Response) HttpResponse() *http.Response { + return r.httpResponse +} + +func (r *Response) SetHttpResponse(response *http.Response) { + r.httpResponse = response +} + +func (r *Response) ElapsedTime() time.Duration { + return r.elapsedTime +} + +func (r *Response) GetHeader(name string) string { + return r.httpResponse.Header.Get(name) +} + +func (r *Response) GetHeaders() map[string]string { + header := r.httpResponse.Header + ret := make(map[string]string, len(header)) + for k, v := range header { + ret[k] = v[0] + } + return ret +} + +func (r *Response) ContentLength() int64 { + return r.httpResponse.ContentLength +} + +func (r *Response) Body() io.ReadCloser { + return r.httpResponse.Body +} diff --git a/bce-sdk-go/init.go b/bce-sdk-go/init.go new file mode 100644 index 0000000..b733c7b --- /dev/null +++ b/bce-sdk-go/init.go @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// init.go - just import the sub packages + +// Package sdk imports all sub packages to build all of them when calling `go install', `go build' +// or `go get' commands. +package sdk + +import ( + _ "github.com/baidubce/bce-sdk-go/auth" + _ "github.com/baidubce/bce-sdk-go/bce" + _ "github.com/baidubce/bce-sdk-go/http" + _ "github.com/baidubce/bce-sdk-go/model" + _ "github.com/baidubce/bce-sdk-go/services/appblb" + _ "github.com/baidubce/bce-sdk-go/services/as" + _ "github.com/baidubce/bce-sdk-go/services/bbc" + _ "github.com/baidubce/bce-sdk-go/services/bcc" + _ "github.com/baidubce/bce-sdk-go/services/bcm" + _ "github.com/baidubce/bce-sdk-go/services/bec" + _ "github.com/baidubce/bce-sdk-go/services/bie" + _ "github.com/baidubce/bce-sdk-go/services/blb" + _ "github.com/baidubce/bce-sdk-go/services/bos" + _ "github.com/baidubce/bce-sdk-go/services/cdn" + _ "github.com/baidubce/bce-sdk-go/services/cert" + _ "github.com/baidubce/bce-sdk-go/services/cfc" + _ "github.com/baidubce/bce-sdk-go/services/dcc" + _ "github.com/baidubce/bce-sdk-go/services/ddc" + _ "github.com/baidubce/bce-sdk-go/services/ddc/v2" + _ "github.com/baidubce/bce-sdk-go/services/eccr" + _ "github.com/baidubce/bce-sdk-go/services/eip" + _ "github.com/baidubce/bce-sdk-go/services/etGateway" + _ "github.com/baidubce/bce-sdk-go/services/iam" + _ "github.com/baidubce/bce-sdk-go/services/mms" + _ "github.com/baidubce/bce-sdk-go/services/rds" + _ "github.com/baidubce/bce-sdk-go/services/scs" + _ "github.com/baidubce/bce-sdk-go/services/sms" + _ "github.com/baidubce/bce-sdk-go/services/sts" + _ "github.com/baidubce/bce-sdk-go/services/vca" + _ "github.com/baidubce/bce-sdk-go/services/vcr" + _ "github.com/baidubce/bce-sdk-go/services/vpc" + _ "github.com/baidubce/bce-sdk-go/services/vpn" + _ "github.com/baidubce/bce-sdk-go/util" + _ "github.com/baidubce/bce-sdk-go/util/crypto" + _ "github.com/baidubce/bce-sdk-go/util/log" +) diff --git a/bce-sdk-go/model/tag.go b/bce-sdk-go/model/tag.go new file mode 100644 index 0000000..581e477 --- /dev/null +++ b/bce-sdk-go/model/tag.go @@ -0,0 +1,6 @@ +package model + +type TagModel struct { + TagKey string `json:"tagKey"` + TagValue string `json:"tagValue"` +} diff --git a/bce-sdk-go/services/appblb/appblb.go b/bce-sdk-go/services/appblb/appblb.go new file mode 100644 index 0000000..2229e28 --- /dev/null +++ b/bce-sdk-go/services/appblb/appblb.go @@ -0,0 +1,145 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// appblb.go - the Application BLB APIs definition supported by the APPBLB service + +package appblb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateLoadBalancer - create a LoadBalancer +// +// PARAMS: +// - args: parameters to create LoadBalancer +// +// RETURNS: +// - *CreateLoadBalanceResult: the result of create LoadBalancer, contains new LoadBalancer's ID +// - error: nil if ok otherwise the specific error +func (c *Client) CreateLoadBalancer(args *CreateLoadBalancerArgs) (*CreateLoadBalanceResult, error) { + if args == nil || len(args.SubnetId) == 0 { + return nil, fmt.Errorf("unset subnet id") + } + + if len(args.VpcId) == 0 { + return nil, fmt.Errorf("unset vpc id") + } + + result := &CreateLoadBalanceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppBlbUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateLoadBalancer - update a LoadBalancer +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update LoadBalancer +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateLoadBalancer(blbId string, args *UpdateLoadBalancerArgs) error { + if args == nil { + args = &UpdateLoadBalancerArgs{} + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppBlbUriWithId(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeLoadBalancers - describe all LoadBalancers +// +// PARAMS: +// - args: parameters to describe all LoadBalancers +// +// RETURNS: +// - *DescribeLoadBalancersResult: the result all LoadBalancers's detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeLoadBalancers(args *DescribeLoadBalancersArgs) (*DescribeLoadBalancersResult, error) { + if args == nil { + args = &DescribeLoadBalancersArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeLoadBalancersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppBlbUri()). + WithQueryParamFilter("address", args.Address). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("blbId", args.BlbId). + WithQueryParamFilter("bccId", args.BccId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ExactlyMatch { + request.WithQueryParam("exactlyMatch", "true") + } + + err := request.Do() + return result, err +} + +// DescribeLoadBalancerDetail - describe a LoadBalancer +// +// PARAMS: +// - blbId: describe LoadBalancer's ID +// +// RETURNS: +// - *DescribeLoadBalancerDetailResult: the result LoadBalancer detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeLoadBalancerDetail(blbId string) (*DescribeLoadBalancerDetailResult, error) { + result := &DescribeLoadBalancerDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppBlbUriWithId(blbId)). + WithResult(result). + Do() + + return result, err +} + +// DeleteLoadBalancer - delete a group +// +// PARAMS: +// - blbId: parameters to delete LoadBalancer +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteLoadBalancer(blbId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getAppBlbUriWithId(blbId)). + Do() +} diff --git a/bce-sdk-go/services/appblb/appipgroup.go b/bce-sdk-go/services/appblb/appipgroup.go new file mode 100644 index 0000000..77f8195 --- /dev/null +++ b/bce-sdk-go/services/appblb/appipgroup.go @@ -0,0 +1,300 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// appipgroup.go - the Application BLB Ip Group APIs definition supported by the APPBLB service + +package appblb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateAppIpGroup - create an ip group +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create IpGroup +// +// RETURNS: +// - *CreateAppIpGroupResult: the result of create IpGroup, contains new IpGroup's ID +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppIpGroup(blbId string, args *CreateAppIpGroupArgs) (*CreateAppIpGroupResult, error) { + if args == nil { + args = &CreateAppIpGroupArgs{} + } + + result := &CreateAppIpGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppIpGroupUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateAppIpGroup - update an ip group +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update an ip group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppIpGroup(blbId string, args *UpdateAppIpGroupArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppIpGroupUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeAppIpGroup - describe all ip groups +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all ip groups +// +// RETURNS: +// - *DescribeAppIpGroupResult: the result of describe all ip groups +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppIpGroup(blbId string, args *DescribeAppIpGroupArgs) (*DescribeAppIpGroupResult, error) { + if args == nil { + args = &DescribeAppIpGroupArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeAppIpGroupResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppIpGroupUri(blbId)). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ExactlyMatch { + request.WithQueryParam("exactlyMatch", "true") + } + + err := request.Do() + return result, err +} + +// DeleteAppIpGroup - delete an ip group +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete an ip group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppIpGroup(blbId string, args *DeleteAppIpGroupArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppIpGroupUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("delete", ""). + WithBody(args). + Do() +} + +// CreateAppIpGroupBackendPolicy - create an ip group backend policy +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create an ip group backend policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppIpGroupBackendPolicy(blbId string, args *CreateAppIpGroupBackendPolicyArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + if len(args.Type) == 0 { + return fmt.Errorf("unset type") + } + + if args.Type == "UDP" && len(args.UdpHealthCheckString) == 0 { + return fmt.Errorf("unset udpHealthCheckString") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppIpGroupBackendPolicyUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppIpGroupBackendPolicy - update ip group backend policy +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update ip group backend policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppIpGroupBackendPolicy(blbId string, args *UpdateAppIpGroupBackendPolicyArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + if len(args.Id) == 0 { + return fmt.Errorf("unset ip group backend policy id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppIpGroupBackendPolicyUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DeleteAppIpGroupBackendPolicy - delete an ip group backend policy +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete ip group backend policies +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppIpGroupBackendPolicy(blbId string, args *DeleteAppIpGroupBackendPolicyArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppIpGroupBackendPolicyUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("delete", ""). + WithBody(args). + Do() +} + +// CreateAppIpGroupMember - create ip group members +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create ip group members +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppIpGroupMember(blbId string, args *CreateAppIpGroupMemberArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppIpGroupMemberUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppIpGroupMember - update ip group members +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update ip group members +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppIpGroupMember(blbId string, args *UpdateAppIpGroupMemberArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppIpGroupMemberUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeAppIpGroupMember - describe ip group members +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe ip group members +// +// RETURNS: +// - *DescribeAppIpGroupMemberResult: the result of describe ip group members +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppIpGroupMember(blbId string, args *DescribeAppIpGroupMemberArgs) (*DescribeAppIpGroupMemberResult, error) { + if args == nil || len(args.IpGroupId) == 0 { + return nil, fmt.Errorf("unset ip group id") + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeAppIpGroupMemberResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppIpGroupMemberUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("ipGroupId", args.IpGroupId). + WithResult(result). + Do() + + return result, err +} + +// DeleteAppIpGroupMember - delete ip group members +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete ip group members +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppIpGroupMember(blbId string, args *DeleteAppIpGroupMemberArgs) error { + if args == nil || len(args.IpGroupId) == 0 { + return fmt.Errorf("unset ip group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppIpGroupMemberUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("delete", ""). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/appblb/appservergroup.go b/bce-sdk-go/services/appblb/appservergroup.go new file mode 100644 index 0000000..508732a --- /dev/null +++ b/bce-sdk-go/services/appblb/appservergroup.go @@ -0,0 +1,351 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// appservergroup.go - the Application BLB Server Group APIs definition supported by the APPBLB service + +package appblb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateAppServerGroup - create a LoadBalancer +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create ServerGroup +// +// RETURNS: +// - *CreateAppServerGroupResult: the result of create ServerGroup, contains new ServerGroup's ID +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppServerGroup(blbId string, args *CreateAppServerGroupArgs) (*CreateAppServerGroupResult, error) { + if args == nil { + args = &CreateAppServerGroupArgs{} + } + + result := &CreateAppServerGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppServerGroupUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateAppServerGroup - update a server group +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update a server group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppServerGroup(blbId string, args *UpdateAppServerGroupArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppServerGroupUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeAppServerGroup - describe all server groups +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all server groups +// +// RETURNS: +// - *DescribeAppServerGroupResult: the result of describe all server groups +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppServerGroup(blbId string, args *DescribeAppServerGroupArgs) (*DescribeAppServerGroupResult, error) { + if args == nil { + args = &DescribeAppServerGroupArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeAppServerGroupResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppServerGroupUri(blbId)). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ExactlyMatch { + request.WithQueryParam("exactlyMatch", "true") + } + + err := request.Do() + return result, err +} + +// DeleteAppServerGroup - delete a server group +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete a server group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppServerGroup(blbId string, args *DeleteAppServerGroupArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppServerGroupUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("delete", ""). + WithBody(args). + Do() +} + +// CreateAppServerGroupPort - create a server group port +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create a server group port +// +// RETURNS: +// - *CreateAppServerGroupPortResult: the result of create a server group port +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppServerGroupPort(blbId string, args *CreateAppServerGroupPortArgs) (*CreateAppServerGroupPortResult, error) { + if args == nil || len(args.SgId) == 0 { + return nil, fmt.Errorf("unset server group id") + } + + if len(args.Type) == 0 { + return nil, fmt.Errorf("unset type") + } + + if args.Type == "UDP" && len(args.UdpHealthCheckString) == 0 { + return nil, fmt.Errorf("unset udpHealthCheckString") + } + + result := &CreateAppServerGroupPortResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppServerGroupPortUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateAppServerGroupPort - update server group port +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update server group port +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppServerGroupPort(blbId string, args *UpdateAppServerGroupPortArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppServerGroupPortUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DeleteAppServerGroupPort - delete server group ports +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete server group ports +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppServerGroupPort(blbId string, args *DeleteAppServerGroupPortArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppServerGroupPortUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("batchdelete", ""). + WithBody(args). + Do() +} + +// CreateBlbRs - add backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to add backend servers +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateBlbRs(blbId string, args *CreateBlbRsArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getBlbRsUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateBlbRs - update backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update backend servers +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateBlbRs(blbId string, args *UpdateBlbRsArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBlbRsUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeBlbRs - describe backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe backend servers +// +// RETURNS: +// - *DescribeBlbRsResult: the result of describe backend servers +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeBlbRs(blbId string, args *DescribeBlbRsArgs) (*DescribeBlbRsResult, error) { + if args == nil || len(args.SgId) == 0 { + return nil, fmt.Errorf("unset server group id") + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeBlbRsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbRsUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("sgId", args.SgId). + WithResult(result). + Do() + + return result, err +} + +// DeleteBlbRs - delete backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete backend servers +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteBlbRs(blbId string, args *DeleteBlbRsArgs) error { + if args == nil || len(args.SgId) == 0 { + return fmt.Errorf("unset server group id") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBlbRsUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("batchdelete", ""). + WithBody(args). + Do() +} + +// DescribeRsMount - get all mount backend server list +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - sgId: ServerGroup's ID +// +// RETURNS: +// - *DescribeRsMountResult: the mount backend server list +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeRsMount(blbId, sgId string) (*DescribeRsMountResult, error) { + if len(sgId) == 0 { + return nil, fmt.Errorf("unset server group id") + } + + result := &DescribeRsMountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbRsMountUri(blbId)). + WithQueryParam("sgId", sgId). + WithResult(result). + Do() + + return result, err +} + +// DescribeRsUnMount - get all unmount backend server list +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - sgId: ServerGroup's ID +// +// RETURNS: +// - *DescribeRsMountResult: the unMount backend server list +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeRsUnMount(blbId, sgId string) (*DescribeRsMountResult, error) { + if len(sgId) == 0 { + return nil, fmt.Errorf("unset server group id") + } + + result := &DescribeRsMountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbRsUnMountUri(blbId)). + WithQueryParam("sgId", sgId). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/appblb/client.go b/bce-sdk-go/services/appblb/client.go new file mode 100644 index 0000000..e57d1d0 --- /dev/null +++ b/bce-sdk-go/services/appblb/client.go @@ -0,0 +1,140 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for Application LoadBalance service + +// Package appblb defines the Application BLB services of BCE. The supported APIs are all defined in sub-package +package appblb + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + DEFAULT_SERVICE_DOMAIN = "blb." + bce.DEFAULT_REGION + ".baidubce.com" + URI_PREFIX = bce.URI_PREFIX + "v1" + REQUEST_APPBLB_URL = "/appblb" + + APP_SERVER_GROUP_URL = "/appservergroup" + APP_SERVER_GROUP_PORT_URL = "/appservergroupport" + BLB_RS_URL = "/blbrs" + BLB_RS_MOUNT_URL = "/blbrsmount" + BLB_RS_UNMOUNT_URL = "/blbrsunmount" + + APP_LISTENER_URL = "/listener" + APP_TCPLISTENER_URL = "/TCPlistener" + APP_UDPLISTENER_URL = "/UDPlistener" + APP_HTTPLISTENER_URL = "/HTTPlistener" + APP_HTTPSLISTENER_URL = "/HTTPSlistener" + APP_SSLLISTENER_URL = "/SSLlistener" + + POLICYS_URL = "/policys" + + APP_IP_GROUP_URL = "/ipgroup" + APP_IP_GROUP_BACKEND_POLICY_URL = "/ipgroup/backendpolicy" + APP_IP_GROUP_MEMBER_URL = "/ipgroup/member" + + SECURITY_GROUP_URL = "/securitygroup" + ENTERPRISE_SECURITY_GROUP_URL = "/enterprise/securitygroup" +) + +// Client of APPBLB service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getAppBlbUri() string { + return URI_PREFIX + REQUEST_APPBLB_URL +} + +func getAppBlbUriWithId(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id +} + +func getAppServerGroupUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_SERVER_GROUP_URL +} + +func getAppServerGroupPortUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_SERVER_GROUP_PORT_URL +} + +func getBlbRsUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + BLB_RS_URL +} + +func getBlbRsMountUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + BLB_RS_MOUNT_URL +} + +func getBlbRsUnMountUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + BLB_RS_UNMOUNT_URL +} + +func getAppListenerUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_LISTENER_URL +} + +func getAppTCPListenerUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_TCPLISTENER_URL +} + +func getAppUDPListenerUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_UDPLISTENER_URL +} + +func getAppHTTPListenerUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_HTTPLISTENER_URL +} + +func getAppHTTPSListenerUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_HTTPSLISTENER_URL +} + +func getAppSSLListenerUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_SSLLISTENER_URL +} + +func getPolicysUrl(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + POLICYS_URL +} + +func getAppIpGroupUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_IP_GROUP_URL +} + +func getAppIpGroupBackendPolicyUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_IP_GROUP_BACKEND_POLICY_URL +} + +func getAppIpGroupMemberUri(id string) string { + return URI_PREFIX + REQUEST_APPBLB_URL + "/" + id + APP_IP_GROUP_MEMBER_URL +} + +func getSecurityGroupUri(id string) string { + return URI_PREFIX + "/blb" + "/" + id + SECURITY_GROUP_URL +} + +func getEnterpriseSecurityGroupUri(id string) string { + return URI_PREFIX + "/blb" + "/" + id + ENTERPRISE_SECURITY_GROUP_URL +} diff --git a/bce-sdk-go/services/appblb/client_test.go b/bce-sdk-go/services/appblb/client_test.go new file mode 100644 index 0000000..930209c --- /dev/null +++ b/bce-sdk-go/services/appblb/client_test.go @@ -0,0 +1,673 @@ +package appblb + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + APPBLB_CLIENT *Client + APPBLB_ID string + APPBLB_SERVERGROUP_ID string + APPBLB_SERVERGROUPPORT_ID string + APPBLB_POLICY_ID string + APPBLB_IPGROUP_ID string + IPGROUP_MEMBER_ID string + APPBLB_IPGROUPP_BACKENDPOLICY_ID string + + // set these values before start test + VPC_TEST_ID = "" + SUBNET_TEST_ID = "" + INSTANCE_ID = "" + CERT_ID = "" + IPGROUP_MEMBER_IP = "" + CLUSTER_PROPERTY_TEST = "" + TEST_APPBLB_ID = "" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + APPBLB_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateLoadBalancer(t *testing.T) { + createArgs := &CreateLoadBalancerArgs{ + ClientToken: getClientToken(), + Name: "sdkBlb", + VpcId: VPC_TEST_ID, + SubnetId: SUBNET_TEST_ID, + ClusterProperty: CLUSTER_PROPERTY_TEST, + } + + createResult, err := APPBLB_CLIENT.CreateLoadBalancer(createArgs) + ExpectEqual(t.Errorf, nil, err) + + APPBLB_ID = createResult.BlbId +} + +func TestClient_UpdateLoadBalancer(t *testing.T) { + updateArgs := &UpdateLoadBalancerArgs{ + Name: "testSdk", + Description: "test desc", + } + err := APPBLB_CLIENT.UpdateLoadBalancer(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeLoadBalancers(t *testing.T) { + describeArgs := &DescribeLoadBalancersArgs{} + res, err := APPBLB_CLIENT.DescribeLoadBalancers(describeArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeLoadBalancerDetail(t *testing.T) { + res, err := APPBLB_CLIENT.DescribeLoadBalancerDetail(APPBLB_ID) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppServerGroup(t *testing.T) { + createArgs := &CreateAppServerGroupArgs{ + ClientToken: getClientToken(), + Name: "sdkTest", + } + createResult, err := APPBLB_CLIENT.CreateAppServerGroup(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) + + APPBLB_SERVERGROUP_ID = createResult.Id +} + +func TestClient_UpdateAppServerGroup(t *testing.T) { + updateArgs := &UpdateAppServerGroupArgs{ + SgId: APPBLB_SERVERGROUP_ID, + Name: "testSdk", + Description: "test desc", + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.UpdateAppServerGroup(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppServerGroup(t *testing.T) { + describeArgs := &DescribeAppServerGroupArgs{} + _, err := APPBLB_CLIENT.DescribeAppServerGroup(APPBLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppServerGroupPort(t *testing.T) { + createArgs := &CreateAppServerGroupPortArgs{ + ClientToken: getClientToken(), + SgId: APPBLB_SERVERGROUP_ID, + Port: 80, + Type: "TCP", + } + createResult, err := APPBLB_CLIENT.CreateAppServerGroupPort(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) + + APPBLB_SERVERGROUPPORT_ID = createResult.Id +} + +func TestClient_UpdateAppServerGroupPort(t *testing.T) { + updateArgs := &UpdateAppServerGroupPortArgs{ + ClientToken: getClientToken(), + SgId: APPBLB_SERVERGROUP_ID, + PortId: APPBLB_SERVERGROUPPORT_ID, + HealthCheck: "TCP", + HealthCheckPort: 30, + HealthCheckIntervalInSecond: 10, + HealthCheckTimeoutInSecond: 10, + } + err := APPBLB_CLIENT.UpdateAppServerGroupPort(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAppServerGroupPort(t *testing.T) { + deleteArgs := &DeleteAppServerGroupPortArgs{ + SgId: APPBLB_SERVERGROUP_ID, + PortIdList: []string{APPBLB_SERVERGROUPPORT_ID}, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteAppServerGroupPort(APPBLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateBlbRs(t *testing.T) { + createArgs := &CreateBlbRsArgs{ + BlbRsWriteOpArgs: BlbRsWriteOpArgs{ + ClientToken: getClientToken(), + SgId: APPBLB_SERVERGROUP_ID, + BackendServerList: []AppBackendServer{ + {InstanceId: INSTANCE_ID, Weight: 30}, + }, + }, + } + err := APPBLB_CLIENT.CreateBlbRs(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateBlbRs(t *testing.T) { + updateArgs := &UpdateBlbRsArgs{ + BlbRsWriteOpArgs: BlbRsWriteOpArgs{ + ClientToken: getClientToken(), + SgId: APPBLB_SERVERGROUP_ID, + BackendServerList: []AppBackendServer{ + {InstanceId: INSTANCE_ID, Weight: 50}, + }, + }, + } + err := APPBLB_CLIENT.UpdateBlbRs(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeBlbRs(t *testing.T) { + describeArgs := &DescribeBlbRsArgs{ + SgId: APPBLB_SERVERGROUP_ID, + } + _, err := APPBLB_CLIENT.DescribeBlbRs(APPBLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteBlbRs(t *testing.T) { + deleteArgs := &DeleteBlbRsArgs{ + SgId: APPBLB_SERVERGROUP_ID, + BackendServerIdList: []string{INSTANCE_ID}, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteBlbRs(APPBLB_ID, deleteArgs) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeRsMount(t *testing.T) { + _, err := APPBLB_CLIENT.DescribeRsMount(APPBLB_ID, APPBLB_SERVERGROUP_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeRsUnMount(t *testing.T) { + _, err := APPBLB_CLIENT.DescribeRsUnMount(APPBLB_ID, APPBLB_SERVERGROUP_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAppServerGroup(t *testing.T) { + deleteArgs := &DeleteAppServerGroupArgs{ + SgId: APPBLB_SERVERGROUP_ID, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteAppServerGroup(APPBLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppIpGroup(t *testing.T) { + createArgs := &CreateAppIpGroupArgs{ + ClientToken: getClientToken(), + Name: "sdkTest", + } + createResult, err := APPBLB_CLIENT.CreateAppIpGroup(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) + + APPBLB_IPGROUP_ID = createResult.Id +} + +func TestClient_UpdateAppIpGroup(t *testing.T) { + updateArgs := &UpdateAppIpGroupArgs{ + IpGroupId: APPBLB_IPGROUP_ID, + Name: "testSdk", + Desc: "test desc", + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.UpdateAppIpGroup(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppIpGroup(t *testing.T) { + describeArgs := &DescribeAppIpGroupArgs{} + res, err := APPBLB_CLIENT.DescribeAppIpGroup(APPBLB_ID, describeArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppIpGroupBackendPolicy(t *testing.T) { + createArgs := &CreateAppIpGroupBackendPolicyArgs{ + ClientToken: getClientToken(), + IpGroupId: APPBLB_IPGROUP_ID, + Type: "TCP", + } + err := APPBLB_CLIENT.CreateAppIpGroupBackendPolicy(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppIpGroupBackendPolicy(t *testing.T) { + updateArgs := &UpdateAppIpGroupBackendPolicyArgs{ + ClientToken: getClientToken(), + IpGroupId: APPBLB_IPGROUP_ID, + Id: APPBLB_IPGROUPP_BACKENDPOLICY_ID, + HealthCheckIntervalInSecond: 10, + HealthCheckTimeoutInSecond: 10, + } + err := APPBLB_CLIENT.UpdateAppIpGroupBackendPolicy(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAppIpGroupBackendPolicy(t *testing.T) { + deleteArgs := &DeleteAppIpGroupBackendPolicyArgs{ + IpGroupId: APPBLB_IPGROUP_ID, + BackendPolicyIdList: []string{APPBLB_IPGROUPP_BACKENDPOLICY_ID}, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteAppIpGroupBackendPolicy(APPBLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppIpGroupMember(t *testing.T) { + createArgs := &CreateAppIpGroupMemberArgs{ + AppIpGroupMemberWriteOpArgs: AppIpGroupMemberWriteOpArgs{ + ClientToken: getClientToken(), + IpGroupId: APPBLB_IPGROUP_ID, + MemberList: []AppIpGroupMember{ + {Ip: IPGROUP_MEMBER_IP, Port: 30}, + }, + }, + } + err := APPBLB_CLIENT.CreateAppIpGroupMember(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppIpGroupMember(t *testing.T) { + updateArgs := &UpdateAppIpGroupMemberArgs{ + AppIpGroupMemberWriteOpArgs: AppIpGroupMemberWriteOpArgs{ + ClientToken: getClientToken(), + IpGroupId: APPBLB_IPGROUP_ID, + MemberList: []AppIpGroupMember{ + {Ip: IPGROUP_MEMBER_IP, Port: 50, MemberId: IPGROUP_MEMBER_ID}, + }, + }, + } + err := APPBLB_CLIENT.UpdateAppIpGroupMember(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppIpGroupMember(t *testing.T) { + describeArgs := &DescribeAppIpGroupMemberArgs{ + IpGroupId: APPBLB_IPGROUP_ID, + } + res, err := APPBLB_CLIENT.DescribeAppIpGroupMember(APPBLB_ID, describeArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAppIpGroupMember(t *testing.T) { + deleteArgs := &DeleteAppIpGroupMemberArgs{ + IpGroupId: APPBLB_IPGROUP_ID, + MemberIdList: []string{IPGROUP_MEMBER_ID}, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteAppIpGroupMember(APPBLB_ID, deleteArgs) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppTCPListener(t *testing.T) { + createArgs := &CreateAppTCPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 90, + Scheduler: "RoundRobin", + } + err := APPBLB_CLIENT.CreateAppTCPListener(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppTCPListener(t *testing.T) { + updateArgs := &UpdateAppTCPListenerArgs{ + UpdateAppListenerArgs: UpdateAppListenerArgs{ + ListenerPort: 90, + Scheduler: "Hash", + }, + } + err := APPBLB_CLIENT.UpdateAppTCPListener(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppTCPListeners(t *testing.T) { + describeArgs := &DescribeAppListenerArgs{ + ListenerPort: 90, + } + _, err := APPBLB_CLIENT.DescribeAppTCPListeners(APPBLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppUDPListener(t *testing.T) { + createArgs := &CreateAppUDPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 91, + Scheduler: "RoundRobin", + } + err := APPBLB_CLIENT.CreateAppUDPListener(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppUDPListener(t *testing.T) { + updateArgs := &UpdateAppUDPListenerArgs{ + UpdateAppListenerArgs: UpdateAppListenerArgs{ + ListenerPort: 91, + Scheduler: "Hash", + }, + } + err := APPBLB_CLIENT.UpdateAppUDPListener(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppUDPListeners(t *testing.T) { + describeArgs := &DescribeAppListenerArgs{ + ListenerPort: 53, + } + result, err := APPBLB_CLIENT.DescribeAppUDPListeners(APPBLB_ID, describeArgs) + if err != nil { + fmt.Println("get udp listener failed:", err) + } else { + fmt.Println("get udp listener success: ", result) + } +} + +func TestClient_CreateAppHTTPListener(t *testing.T) { + createArgs := &CreateAppHTTPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 92, + Scheduler: "RoundRobin", + } + err := APPBLB_CLIENT.CreateAppHTTPListener(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppHTTPListener(t *testing.T) { + updateArgs := &UpdateAppHTTPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 92, + Scheduler: "LeastConnection", + KeepSession: true, + } + err := APPBLB_CLIENT.UpdateAppHTTPListener(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreatePolicys(t *testing.T) { + createArgs := &CreatePolicysArgs{ + ListenerPort: 92, + ClientToken: getClientToken(), + AppPolicyVos: []AppPolicy{ + { + Description: "test policy", + AppServerGroupId: "", + BackendPort: 92, + Priority: 300, + RuleList: []AppRule{ + { + Key: "*", + Value: "*", + }, + }, + }, + }, + } + err := APPBLB_CLIENT.CreatePolicys(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreatePolicysIpGroup(t *testing.T) { + createArgs := &CreatePolicysArgs{ + ListenerPort: 80, + ClientToken: getClientToken(), + AppPolicyVos: []AppPolicy{ + { + Description: "test policy", + AppIpGroupId: APPBLB_IPGROUP_ID, + Priority: 100, + RuleList: []AppRule{ + { + Key: "*", + Value: "*", + }, + }, + }, + }, + } + err := APPBLB_CLIENT.CreatePolicys(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribePolicys(t *testing.T) { + describeArgs := &DescribePolicysArgs{ + Port: 80, + } + res, err := APPBLB_CLIENT.DescribePolicys(APPBLB_ID, describeArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) + + APPBLB_POLICY_ID = res.PolicyList[0].Id +} + +func TestClient_DeletePolicys(t *testing.T) { + deleteArgs := &DeletePolicysArgs{ + Port: 80, + PolicyIdList: []string{APPBLB_POLICY_ID}, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeletePolicys(APPBLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppHTTPListeners(t *testing.T) { + describeArgs := &DescribeAppListenerArgs{ + ListenerPort: 92, + } + _, err := APPBLB_CLIENT.DescribeAppHTTPListeners(APPBLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppHTTPSListener(t *testing.T) { + createArgs := &CreateAppHTTPSListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 93, + Scheduler: "RoundRobin", + CertIds: []string{CERT_ID}, + } + err := APPBLB_CLIENT.CreateAppHTTPSListener(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppHTTPSListener(t *testing.T) { + updateArgs := &UpdateAppHTTPSListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 93, + Scheduler: "LeastConnection", + KeepSession: true, + CertIds: []string{CERT_ID}, + } + err := APPBLB_CLIENT.UpdateAppHTTPSListener(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppHTTPSListeners(t *testing.T) { + describeArgs := &DescribeAppListenerArgs{ + ListenerPort: 93, + } + _, err := APPBLB_CLIENT.DescribeAppHTTPSListeners(APPBLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAppSSLListener(t *testing.T) { + createArgs := &CreateAppSSLListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 94, + Scheduler: "RoundRobin", + CertIds: []string{CERT_ID}, + } + err := APPBLB_CLIENT.CreateAppSSLListener(APPBLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAppSSLListener(t *testing.T) { + updateArgs := &UpdateAppSSLListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 94, + Scheduler: "LeastConnection", + CertIds: []string{CERT_ID}, + } + err := APPBLB_CLIENT.UpdateAppSSLListener(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppSSLListeners(t *testing.T) { + describeArgs := &DescribeAppListenerArgs{ + ListenerPort: 94, + } + _, err := APPBLB_CLIENT.DescribeAppSSLListeners(APPBLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAppAllListeners(t *testing.T) { + describeArgs := &DescribeAppListenerArgs{} + result, err := APPBLB_CLIENT.DescribeAppAllListeners(APPBLB_ID, describeArgs) + if err != nil { + fmt.Println("get all listener failed:", err) + } else { + fmt.Println("get all listener success: ", result) + } +} + +func TestClient_BindSecurityGroups(t *testing.T) { + updateArgs := &UpdateSecurityGroupsArgs{ + ClientToken: getClientToken(), + SecurityGroupIds: []string{"sg-id"}, + } + err := APPBLB_CLIENT.BindSecurityGroups(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindSecurityGroups(t *testing.T) { + updateArgs := &UpdateSecurityGroupsArgs{ + ClientToken: getClientToken(), + SecurityGroupIds: []string{"sg-id"}, + } + err := APPBLB_CLIENT.UnbindSecurityGroups(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeSecurityGroups(t *testing.T) { + res, err := APPBLB_CLIENT.DescribeSecurityGroups(APPBLB_ID) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindEnterpriseSecurityGroups(t *testing.T) { + updateArgs := &UpdateEnterpriseSecurityGroupsArgs{ + ClientToken: getClientToken(), + EnterpriseSecurityGroupIds: []string{"esg-id"}, + } + err := APPBLB_CLIENT.BindEnterpriseSecurityGroups(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindEnterpriseSecurityGroups(t *testing.T) { + updateArgs := &UpdateEnterpriseSecurityGroupsArgs{ + ClientToken: getClientToken(), + EnterpriseSecurityGroupIds: []string{"esg-id"}, + } + err := APPBLB_CLIENT.UnbindEnterpriseSecurityGroups(APPBLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeEnterpriseSecurityGroups(t *testing.T) { + res, err := APPBLB_CLIENT.DescribeEnterpriseSecurityGroups(APPBLB_ID) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAppListeners(t *testing.T) { + deleteArgs := &DeleteAppListenersArgs{ + PortList: []uint16{90, 91, 92, 93, 94}, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteAppListeners(APPBLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAppPortTypeListeners(t *testing.T) { + deleteArgs := &DeleteAppListenersArgs{ + PortTypeList: []PortTypeModel{ + { + Port: 80, + Type: "UDP", + }, + { + Port: 80, + Type: "HTTP", + }, + }, + ClientToken: getClientToken(), + } + err := APPBLB_CLIENT.DeleteAppListeners(APPBLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteLoadBalancer(t *testing.T) { + err := APPBLB_CLIENT.DeleteLoadBalancer(APPBLB_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/appblb/config.json b/bce-sdk-go/services/appblb/config.json new file mode 100644 index 0000000..5a6634f --- /dev/null +++ b/bce-sdk-go/services/appblb/config.json @@ -0,0 +1,5 @@ +{ + "AK":"", + "SK":"", + "Endpoint":"" +} diff --git a/bce-sdk-go/services/appblb/enterprisesecuritygroups.go b/bce-sdk-go/services/appblb/enterprisesecuritygroups.go new file mode 100644 index 0000000..c630a66 --- /dev/null +++ b/bce-sdk-go/services/appblb/enterprisesecuritygroups.go @@ -0,0 +1,96 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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. + */ + +// enterprisesecuritygroups.go - the enterprisesecuritygroup APIs definition supported by the APPBLB service + +package appblb + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// BindEnterpriseSecurityGroups - bind the blb enterprise security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update enterprise security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) BindEnterpriseSecurityGroups(blbId string, args *UpdateEnterpriseSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.EnterpriseSecurityGroupIds) == 0 { + return fmt.Errorf("unset enterprise security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEnterpriseSecurityGroupUri(blbId)). + WithQueryParam("bind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UnbindEnterpriseSecurityGroups - unbind the blb enterprise security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update enterprise security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UnbindEnterpriseSecurityGroups(blbId string, args *UpdateEnterpriseSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.EnterpriseSecurityGroupIds) == 0 { + return fmt.Errorf("unset enterprise security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEnterpriseSecurityGroupUri(blbId)). + WithQueryParam("unbind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeEnterpriseSecurityGroups - describe all enterprise security groups of the specified LoadBalancer (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// +// RETURNS: +// - *DescribeEnterpriseSecurityGroupsResult: the result of describe all enterprise security groups +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeEnterpriseSecurityGroups(blbId string) (*DescribeEnterpriseSecurityGroupsResult, error) { + + result := &DescribeEnterpriseSecurityGroupsResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEnterpriseSecurityGroupUri(blbId)). + WithResult(result) + + err := request.Do() + return result, err +} diff --git a/bce-sdk-go/services/appblb/listener.go b/bce-sdk-go/services/appblb/listener.go new file mode 100644 index 0000000..cffee76 --- /dev/null +++ b/bce-sdk-go/services/appblb/listener.go @@ -0,0 +1,636 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// listener.go - the Application BLB Listener APIs definition supported by the APPBLB service + +package appblb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateAppTCPListener - create a TCP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create TCP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppTCPListener(blbId string, args *CreateAppTCPListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppTCPListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateAppUDPListener - create a UDP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create UDP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppUDPListener(blbId string, args *CreateAppUDPListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppUDPListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateAppHTTPListener - create a HTTP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create HTTP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppHTTPListener(blbId string, args *CreateAppHTTPListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppHTTPListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateAppHTTPSListener - create a HTTPS Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create HTTPS Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppHTTPSListener(blbId string, args *CreateAppHTTPSListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.CertIds) == 0 { + return fmt.Errorf("unset certIds") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppHTTPSListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateAppSSLListener - create a SSL Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create SSL Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppSSLListener(blbId string, args *CreateAppSSLListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.CertIds) == 0 { + return fmt.Errorf("unset certIds") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAppSSLListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppTCPListener - update a TCP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update TCP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppTCPListener(blbId string, args *UpdateAppTCPListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppTCPListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppUDPListener - update a UDP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update UDP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppUDPListener(blbId string, args *UpdateAppUDPListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppUDPListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppHTTPListener - update a HTTP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update HTTP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppHTTPListener(blbId string, args *UpdateAppHTTPListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppHTTPListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppHTTPSListener - update a HTTPS Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update HTTPS Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppHTTPSListener(blbId string, args *UpdateAppHTTPSListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.CertIds) == 0 { + return fmt.Errorf("unset certIds") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppHTTPSListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateAppSSLListener - update a SSL Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update SSL Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppSSLListener(blbId string, args *UpdateAppSSLListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.CertIds) == 0 { + return fmt.Errorf("unset certIds") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppSSLListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeAppTCPListeners - describe all TCP Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all TCP Listeners +// +// RETURNS: +// - *DescribeAppTCPListenersResult: the result of describe all TCP Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppTCPListeners(blbId string, args *DescribeAppListenerArgs) (*DescribeAppTCPListenersResult, error) { + if args == nil { + args = &DescribeAppListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAppTCPListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppTCPListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeAppUDPListeners - describe all UDP Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all UDP Listeners +// +// RETURNS: +// - *DescribeAppUDPListenersResult: the result of describe all UDP Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppUDPListeners(blbId string, args *DescribeAppListenerArgs) (*DescribeAppUDPListenersResult, error) { + if args == nil { + args = &DescribeAppListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAppUDPListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppUDPListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeAppHTTPListeners - describe all HTTP Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all HTTP Listeners +// +// RETURNS: +// - *DescribeAppHTTPListenersResult: the result of describe all HTTP Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppHTTPListeners(blbId string, args *DescribeAppListenerArgs) (*DescribeAppHTTPListenersResult, error) { + if args == nil { + args = &DescribeAppListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAppHTTPListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppHTTPListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeAppHTTPSListeners - describe all HTTPS Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all HTTPS Listeners +// +// RETURNS: +// - *DescribeAppHTTPSListenersResult: the result of describe all HTTPS Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppHTTPSListeners(blbId string, args *DescribeAppListenerArgs) (*DescribeAppHTTPSListenersResult, error) { + if args == nil { + args = &DescribeAppListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAppHTTPSListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppHTTPSListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeAppSSLListeners - describe all SSL Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all SSL Listeners +// +// RETURNS: +// - *DescribeAppSSLListenersResult: the result of describe all SSL Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppSSLListeners(blbId string, args *DescribeAppListenerArgs) (*DescribeAppSSLListenersResult, error) { + if args == nil { + args = &DescribeAppListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAppSSLListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppSSLListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeAppAllListeners - describe all Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all Listeners +// +// RETURNS: +// - *DescribeAppAllListenersResult: the result of describe all Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAppAllListeners(blbId string, args *DescribeAppListenerArgs) (*DescribeAppAllListenersResult, error) { + if args == nil { + args = &DescribeAppListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAppAllListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAppListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DeleteAppListeners - delete Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete Listeners, a listener port list +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppListeners(blbId string, args *DeleteAppListenersArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.PortList) == 0 && len(args.PortTypeList) == 0 { + return fmt.Errorf("unset port list") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAppListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("batchdelete", ""). + WithBody(args). + Do() +} + +// CreatePolicys - create a policy bind with Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create a policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreatePolicys(blbId string, args *CreatePolicysArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unset listen port") + } + + if len(args.AppPolicyVos) == 0 { + return fmt.Errorf("unset App Policy") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getPolicysUrl(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribePolicys - descirbe a policy +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create a policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DescribePolicys(blbId string, args *DescribePolicysArgs) (*DescribePolicysResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.Port == 0 { + return nil, fmt.Errorf("unset port") + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribePolicysResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getPolicysUrl(blbId)). + WithQueryParam("port", strconv.Itoa(int(args.Port))). + WithQueryParamFilter("type", args.Type). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// DeletePolicys - delete a policy +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete a policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeletePolicys(blbId string, args *DeletePolicysArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.Port == 0 { + return fmt.Errorf("unset port") + } + + if len(args.PolicyIdList) == 0 { + return fmt.Errorf("unset policy id list") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getPolicysUrl(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("batchdelete", ""). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/appblb/model.go b/bce-sdk-go/services/appblb/model.go new file mode 100644 index 0000000..168946c --- /dev/null +++ b/bce-sdk-go/services/appblb/model.go @@ -0,0 +1,758 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package appblb + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type BLBStatus string + +const ( + BLBStatusCreating BLBStatus = "creating" + BLBStatusAvailable BLBStatus = "available" + BLBStatusUpdating BLBStatus = "updating" + BLBStatusPaused BLBStatus = "paused" + BLBStatusUnavailable BLBStatus = "unavailable" +) + +type AppRsPortModel struct { + ListenerPort int `json:"listenerPort"` + BackendPort string `json:"backendPort"` + PortType string `json:"portType"` + HealthCheckPortType string `json:"healthCheckPortType"` + Status string `json:"status"` + PortId string `json:"portId"` + PolicyId string `json:"policyId"` +} + +type AppBackendServer struct { + InstanceId string `json:"instanceId,omitempty"` + Weight int `json:"weight,omitempty"` + PrivateIp string `json:"privateIp,omitempty"` + PortList []AppRsPortModel `json:"portList,omitempty"` +} + +type DescribeResultMeta struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type CreateAppServerGroupArgs struct { + Name string `json:"name,omitempty"` + Description string `json:"desc,omitempty"` + BackendServerList []AppBackendServer `json:"backendServerList,omitempty"` + ClientToken string `json:"-"` +} + +type CreateAppServerGroupResult struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"desc"` + Status BLBStatus `json:"status"` +} + +type UpdateAppServerGroupArgs struct { + SgId string `json:"sgId"` + Name string `json:"name,omitempty"` + Description string `json:"desc,omitempty"` + ClientToken string `json:"-"` +} + +type DescribeAppServerGroupArgs struct { + Name string + ExactlyMatch bool + Marker string + MaxKeys int +} + +type AppServerGroupPort struct { + Id string `json:"id"` + Port int `json:"port"` + Type string `json:"type"` + Status BLBStatus `json:"status"` + HealthCheck string `json:"healthCheck"` + HealthCheckPort int `json:"healthCheckPort"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond"` + HealthCheckDownRetry int `json:"healthCheckDownRetry"` + HealthCheckUpRetry int `json:"healthCheckUpRetry"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` + HealthCheckUrlPath string `json:"healthCheckUrlPath"` + UdpHealthCheckString string `json:"udpHealthCheckString"` +} + +type AppServerGroup struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"desc"` + Status BLBStatus `json:"status"` + PortList []AppServerGroupPort `json:"portList"` +} + +type DescribeAppServerGroupResult struct { + DescribeResultMeta + AppServerGroupList []AppServerGroup `json:"appServerGroupList"` +} + +type DeleteAppServerGroupArgs struct { + SgId string `json:"sgId"` + ClientToken string `json:"-"` +} + +type CreateAppServerGroupPortArgs struct { + ClientToken string `json:"-"` + SgId string `json:"sgId"` + Port uint16 `json:"port"` + Type string `json:"type"` + HealthCheck string `json:"healthCheck,omitempty"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond,omitempty"` + HealthCheckDownRetry int `json:"healthCheckDownRetry,omitempty"` + HealthCheckUpRetry int `json:"healthCheckUpRetry,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + HealthCheckUrlPath string `json:"healthCheckUrlPath,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` +} + +type CreateAppServerGroupPortResult struct { + Id string `json:"id"` + Name string `json:"name"` + Description string `json:"desc"` + Status BLBStatus `json:"status"` +} + +type UpdateAppServerGroupPortArgs struct { + ClientToken string `json:"-"` + SgId string `json:"sgId"` + PortId string `json:"portId"` + HealthCheck string `json:"healthCheck,omitempty"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckUrlPath string `json:"healthCheckUrlPath,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond,omitempty"` + HealthCheckDownRetry int `json:"healthCheckDownRetry,omitempty"` + HealthCheckUpRetry int `json:"healthCheckUpRetry,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` +} + +type DeleteAppServerGroupPortArgs struct { + SgId string `json:"sgId"` + PortIdList []string `json:"portIdList"` + ClientToken string `json:"-"` +} + +type BlbRsWriteOpArgs struct { + SgId string `json:"sgId"` + BackendServerList []AppBackendServer `json:"backendServerList"` + ClientToken string `json:"-"` +} + +type CreateBlbRsArgs struct { + BlbRsWriteOpArgs +} + +type UpdateBlbRsArgs struct { + BlbRsWriteOpArgs +} + +type DescribeBlbRsArgs struct { + Marker string + MaxKeys int + SgId string +} + +type DescribeBlbRsResult struct { + BackendServerList []AppBackendServer `json:"backendServerList"` + DescribeResultMeta +} + +type DeleteBlbRsArgs struct { + SgId string `json:"sgId"` + BackendServerIdList []string `json:"backendServerIdList"` + ClientToken string `json:"-"` +} + +type DescribeRsMountResult struct { + BackendServerList []AppBackendServer `json:"backendServerList"` +} + +type CreateLoadBalancerArgs struct { + ClientToken string `json:"-"` + Name string `json:"name,omitempty"` + Description string `json:"desc,omitempty"` + SubnetId string `json:"subnetId"` + VpcId string `json:"vpcId"` + ClusterProperty string `json:"clusterProperty"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +type CreateLoadBalanceResult struct { + Address string `json:"address"` + Name string `json:"name"` + Description string `json:"desc"` + BlbId string `json:"blbId"` +} + +type UpdateLoadBalancerArgs struct { + ClientToken string `json:"-"` + Name string `json:"name,omitempty"` + Description string `json:"desc,omitempty"` + AllowDelete *bool `json:"allowDelete,omitempty"` +} + +type DescribeLoadBalancersArgs struct { + Address string + Name string + BlbId string + BccId string + ExactlyMatch bool + Marker string + MaxKeys int +} + +type AppBLBModel struct { + BlbId string `json:"blbId"` + Name string `json:"name"` + Description string `json:"desc"` + Address string `json:"address"` + Status BLBStatus `json:"status"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + PublicIp string `json:"publicIp"` + Layer4ClusterId string `json:"layer4ClusterId"` + Layer7ClusterId string `json:"layer7ClusterId"` + Tags []model.TagModel `json:"tags"` + EipRouteType string `json:"eipRouteType"` + AllowDelete bool `json:"allowDelete"` +} + +type DescribeLoadBalancersResult struct { + BlbList []AppBLBModel `json:"blbList"` + DescribeResultMeta +} + +type ListenerModel struct { + Port string `json:"port"` + Type string `json:"type"` +} + +type PortTypeModel struct { + Port int `json:"port"` + Type string `json:"type"` +} + +type DescribeLoadBalancerDetailResult struct { + BlbId string `json:"blbId"` + Name string `json:"name"` + Status BLBStatus `json:"status"` + Description string `json:"desc"` + Address string `json:"address"` + PublicIp string `json:"publicIp"` + Cidr string `json:"cidr"` + VpcName string `json:"vpcName"` + SubnetCider string `json:"subnetCider"` + SubnetName string `json:"subnetName"` + CreateTime string `json:"createTime"` + ReleaseTime string `json:"releaseTime"` + Layer4ClusterId string `json:"layer4ClusterId"` + Layer7ClusterId string `json:"layer7ClusterId"` + Listener []ListenerModel `json:"listener"` + Tags []model.TagModel `json:"tags"` + EipRouteType string `json:"eipRouteType"` +} + +type CreateAppTCPListenerArgs struct { + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + ClientToken string `json:"-"` +} + +type CreateAppUDPListenerArgs struct { + UdpSessionTimeout int `json:"udpSessionTimeout,omitempty"` + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + ClientToken string `json:"-"` +} + +type CreateAppHTTPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionTimeout int `json:"keepSessionTimeout,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + RedirectPort uint16 `json:"redirectPort,omitempty"` +} + +type CreateAppHTTPSListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionTimeout int `json:"keepSessionTimeout,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type CreateAppSSLListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type UpdateAppListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + Scheduler string `json:"scheduler,omitempty"` + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` + UdpSessionTimeout int `json:"udpSessionTimeout,omitempty"` +} + +type UpdateAppTCPListenerArgs struct { + UpdateAppListenerArgs +} + +type UpdateAppUDPListenerArgs struct { + UpdateAppListenerArgs +} + +type UpdateAppHTTPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionTimeout int `json:"keepSessionTimeout,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + RedirectPort uint16 `json:"redirectPort,omitempty"` +} + +type UpdateAppHTTPSListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionTimeout int `json:"keepSessionTimeout,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type UpdateAppSSLListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + Scheduler string `json:"scheduler"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type AppListenerModel struct { + Port uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + TcpSessionTimeout int `json:"tcpSessionTimeout"` + UdpSessionTimeout int `json:"udpSessionTimeout"` +} + +type AppTCPListenerModel struct { + AppListenerModel +} + +type AppUDPListenerModel struct { + AppListenerModel +} + +type AppHTTPListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession"` + KeepSessionType string `json:"keepSessionType"` + KeepSessionTimeout int `json:"keepSessionTimeout"` + KeepSessionCookieName string `json:"keepSessionCookieName"` + XForwardedFor bool `json:"xForwardedFor"` + ServerTimeout int `json:"serverTimeout"` + RedirectPort int `json:"redirectPort"` +} + +type AppHTTPSListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession"` + KeepSessionType string `json:"keepSessionType"` + KeepSessionTimeout int `json:"keepSessionTimeout"` + KeepSessionCookieName string `json:"keepSessionCookieName"` + XForwardedFor bool `json:"xForwardedFor"` + ServerTimeout int `json:"serverTimeout"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType"` + EncryptionProtocols []string `json:"encryptionProtocols"` + AppliedCiphers string `json:"appliedCiphers"` + DualAuth bool `json:"dualAuth"` + ClientCertIds []string `json:"clientCertIds"` +} + +type AppSSLListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + Scheduler string `json:"scheduler"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType"` + EncryptionProtocols []string `json:"encryptionProtocols"` + AppliedCiphers string `json:"appliedCiphers"` + DualAuth bool `json:"dualAuth"` + ClientCertIds []string `json:"clientCertIds"` +} + +type AppAllListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + ListenerType string `json:"listenerType"` + Scheduler string `json:"scheduler"` + TcpSessionTimeout int `json:"tcpSessionTimeout"` + UdpSessionTimeout int `json:"udpSessionTimeout"` + KeepSession bool `json:"keepSession"` + KeepSessionType string `json:"keepSessionType"` + KeepSessionTimeout int `json:"keepSessionTimeout"` + KeepSessionCookieName string `json:"keepSessionCookieName"` + XForwardedFor bool `json:"xForwardedFor"` + xForwardedProto bool `json:"xForwardedProto"` + ServerTimeout int `json:"serverTimeout"` + RedirectPort int `json:"redirectPort"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType"` + EncryptionProtocols []string `json:"encryptionProtocols"` + AppliedCiphers string `json:"appliedCiphers"` + DualAuth bool `json:"dualAuth"` + ClientCertIds []string `json:"clientCertIds"` +} + +type DescribeAppListenerArgs struct { + ListenerPort uint16 + Marker string + MaxKeys int +} + +type DescribeAppTCPListenersResult struct { + ListenerList []AppTCPListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeAppUDPListenersResult struct { + ListenerList []AppUDPListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeAppHTTPListenersResult struct { + ListenerList []AppHTTPListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeAppHTTPSListenersResult struct { + ListenerList []AppHTTPSListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeAppSSLListenersResult struct { + ListenerList []AppSSLListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeAppAllListenersResult struct { + ListenerList []AppAllListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DeleteAppListenersArgs struct { + ClientToken string `json:"-"` + PortList []uint16 `json:"portList"` + PortTypeList []PortTypeModel `json:"portTypeList"` +} + +type AppRule struct { + Key string `json:"key"` + Value string `json:"value"` +} + +type AppPolicy struct { + Description string `json:"desc"` + AppServerGroupId string `json:"appServerGroupId,omitempty"` + AppIpGroupId string `json:"appIpGroupId,omitempty"` + AppIpGroupName string `json:"appIpGroupName,omitempty"` + GroupType string `json:"groupType,omitempty"` + + BackendPort uint16 `json:"backendPort,omitempty"` + Priority int `json:"priority"` + RuleList []AppRule `json:"ruleList"` + + Id string `json:"id"` + FrontendPort int `json:"frontendPort"` + AppServerGroupName string `json:"appServerGroupName"` + PortType string `json:"portType"` +} + +type CreatePolicysArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + AppPolicyVos []AppPolicy `json:"appPolicyVos"` + Type string `json:"type"` +} + +type DescribePolicysArgs struct { + Port uint16 + Type string + Marker string + MaxKeys int +} + +type DescribePolicysResult struct { + PolicyList []AppPolicy `json:"policyList"` + DescribeResultMeta +} + +type DeletePolicysArgs struct { + ClientToken string `json:"-"` + Port uint16 `json:"port"` + PolicyIdList []string `json:"policyIdList"` + Type string `json:"type"` +} + +type CreateAppIpGroupArgs struct { + Name string `json:"name,omitempty"` + Desc string `json:"desc,omitempty"` + MemberList []AppIpGroupMember `json:"memberList,omitempty"` + ClientToken string `json:"-"` +} + +type AppIpGroupMember struct { + Ip string `json:"ip,omitempty"` + Port int `json:"port,omitempty"` + Weight int `json:"weight,omitempty"` + MemberId string `json:"memberId,omitempty"` + PortList []AppIpGroupMemberPortModel `json:"portList,omitempty"` +} + +type AppIpGroupMemberPortModel struct { + HealthCheckPortType string `json:"healthCheckPortType"` + Status string `json:"status"` +} + +type CreateAppIpGroupResult struct { + Id string `json:"id"` + Name string `json:"name"` + Desc string `json:"desc"` +} + +type UpdateAppIpGroupArgs struct { + IpGroupId string `json:"ipGroupId"` + Name string `json:"name,omitempty"` + Desc string `json:"desc,omitempty"` + ClientToken string `json:"-"` +} + +type DescribeAppIpGroupArgs struct { + Name string + ExactlyMatch bool + Marker string + MaxKeys int +} + +type DescribeAppIpGroupResult struct { + DescribeResultMeta + AppIpGroupList []AppIpGroup `json:"appIpGroupList"` +} + +type AppIpGroup struct { + Id string `json:"id"` + Name string `json:"name"` + Desc string `json:"desc"` + BackendPolicyList []AppIpGroupBackendPolicy `json:"backendPolicyList"` +} + +type AppIpGroupBackendPolicy struct { + Id string `json:"id"` + Type string `json:"type"` + HealthCheck string `json:"healthCheck"` + HealthCheckPort int `json:"healthCheckPort"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond"` + HealthCheckDownRetry int `json:"healthCheckDownRetry"` + HealthCheckUpRetry int `json:"healthCheckUpRetry"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` + HealthCheckUrlPath string `json:"healthCheckUrlPath"` + UdpHealthCheckString string `json:"udpHealthCheckString"` +} + +type DeleteAppIpGroupArgs struct { + IpGroupId string `json:"ipGroupId"` + ClientToken string `json:"-"` +} + +type CreateAppIpGroupBackendPolicyArgs struct { + ClientToken string `json:"-"` + IpGroupId string `json:"ipGroupId"` + Type string `json:"type"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond,omitempty"` + HealthCheckDownRetry int `json:"healthCheckDownRetry,omitempty"` + HealthCheckUpRetry int `json:"healthCheckUpRetry,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + HealthCheckUrlPath string `json:"healthCheckUrlPath,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` +} + +type UpdateAppIpGroupBackendPolicyArgs struct { + ClientToken string `json:"-"` + IpGroupId string `json:"ipGroupId"` + Id string `json:"id"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckUrlPath string `json:"healthCheckUrlPath,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond,omitempty"` + HealthCheckDownRetry int `json:"healthCheckDownRetry,omitempty"` + HealthCheckUpRetry int `json:"healthCheckUpRetry,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` +} + +type DeleteAppIpGroupBackendPolicyArgs struct { + IpGroupId string `json:"ipGroupId"` + BackendPolicyIdList []string `json:"backendPolicyIdList"` + ClientToken string `json:"-"` +} + +type AppIpGroupMemberWriteOpArgs struct { + IpGroupId string `json:"ipGroupId"` + MemberList []AppIpGroupMember `json:"memberList"` + ClientToken string `json:"-"` +} + +type CreateAppIpGroupMemberArgs struct { + AppIpGroupMemberWriteOpArgs +} + +type UpdateAppIpGroupMemberArgs struct { + AppIpGroupMemberWriteOpArgs +} + +type DescribeAppIpGroupMemberArgs struct { + Marker string + MaxKeys int + IpGroupId string +} + +type DescribeAppIpGroupMemberResult struct { + MemberList []AppIpGroupMember `json:"memberList"` + DescribeResultMeta +} + +type DeleteAppIpGroupMemberArgs struct { + IpGroupId string `json:"ipGroupId"` + MemberIdList []string `json:"memberIdList"` + ClientToken string `json:"-"` +} + +type UpdateSecurityGroupsArgs struct { + ClientToken string `json:"-"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type UpdateEnterpriseSecurityGroupsArgs struct { + ClientToken string `json:"-"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` +} + +type DescribeSecurityGroupsResult struct { + BlbSecurityGroups []BlbSecurityGroupModel `json:"blbSecurityGroups"` +} + +type DescribeEnterpriseSecurityGroupsResult struct { + BlbEnterpriseSecurityGroups []BlbEnterpriseSecurityGroupModel `json:"enterpriseSecurityGroups"` +} + +type BlbSecurityGroupModel struct { + SecurityGroupId string `json:"securityGroupId"` + SecurityGroupName string `json:"securityGroupName"` + SecurityGroupDesc string `json:"securityGroupDesc"` + VpcName string `json:"vpcName"` + SecurityGroupRules []BlbSecurityGroupRuleModel `json:"securityGroupRules"` +} + +type BlbEnterpriseSecurityGroupModel struct { + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId"` + EnterpriseSecurityGroupName string `json:"enterpriseSecurityGroupName"` + EnterpriseSecurityGroupDesc string `json:"enterpriseSecurityGroupDesc"` + EnterpriseSecurityGroupRules []BlbEnterpriseSecurityGroupRuleModel `json:"enterpriseSecurityGroupRules"` +} + +type BlbSecurityGroupRuleModel struct { + SecurityGroupRuleId string `json:"securityGroupRuleId"` + Direction string `json:"direction"` + Ethertype string `json:"ethertype,omitempty"` + PortRange string `json:"portRange,omitempty"` + Protocol string `json:"protocol,omitempty"` + SourceGroupId string `json:"sourceGroupId,omitempty"` + SourceIp string `json:"sourceIp,omitempty"` + DestGroupId string `json:"destGroupId,omitempty"` + DestIp string `json:"destIp,omitempty"` +} + +type BlbEnterpriseSecurityGroupRuleModel struct { + EnterpriseSecurityGroupRuleId string `json:"enterpriseSecurityGroupRuleId"` + Direction string `json:"direction"` + Action string `json:"action"` + Priority string `json:"priority"` + Remark string `json:"remark"` + Ethertype string `json:"ethertype,omitempty"` + PortRange string `json:"portRange,omitempty"` + Protocol string `json:"protocol,omitempty"` + SourceIp string `json:"sourceIp,omitempty"` + DestIp string `json:"destIp,omitempty"` +} diff --git a/bce-sdk-go/services/appblb/securitygroup.go b/bce-sdk-go/services/appblb/securitygroup.go new file mode 100644 index 0000000..2670743 --- /dev/null +++ b/bce-sdk-go/services/appblb/securitygroup.go @@ -0,0 +1,96 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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. + */ + +// securitygroup.go - the securitygroup APIs definition supported by the APPBLB service + +package appblb + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// BindSecurityGroups - bind the blb security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) BindSecurityGroups(blbId string, args *UpdateSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.SecurityGroupIds) == 0 { + return fmt.Errorf("unset security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getSecurityGroupUri(blbId)). + WithQueryParam("bind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UnbindSecurityGroups - unbind the blb security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UnbindSecurityGroups(blbId string, args *UpdateSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.SecurityGroupIds) == 0 { + return fmt.Errorf("unset security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getSecurityGroupUri(blbId)). + WithQueryParam("unbind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeSecurityGroups - describe all security groups of the specified LoadBalancer (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// +// RETURNS: +// - *DescribeSecurityGroupsResult: the result of describe all security groups +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeSecurityGroups(blbId string) (*DescribeSecurityGroupsResult, error) { + + result := &DescribeSecurityGroupsResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupUri(blbId)). + WithResult(result) + + err := request.Do() + return result, err +} diff --git a/bce-sdk-go/services/as/as.go b/bce-sdk-go/services/as/as.go new file mode 100644 index 0000000..6c5ec46 --- /dev/null +++ b/bce-sdk-go/services/as/as.go @@ -0,0 +1,141 @@ +package as + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +const ( + GROUP_NAME = "groupName" + GROUP_ID = "groupId" + MARKER = "marker" + MAX_KEYS = "maxKeys" + MANNER = "manner" + AS_SCALING_DOWN = "scalingDown" + AS_SCALING_UP = "scalingUp" + AS_ADJUST_NODE = "adjustNode" +) + +// ListAsGroup 方法用于获取指定用户下的As组列表 +func (c *Client) ListAsGroup(req *ListAsGroupRequest) (*ListAsGroupResponse, error) { + if req == nil { + return nil, fmt.Errorf("ListAsGroupRequest is nil") + } + if req.MaxKeys <= 0 || req.MaxKeys > 1000 { + req.MaxKeys = 1000 + } + result := &ListAsGroupResponse{} + err := bce.NewRequestBuilder(c). + WithURL(getAsGroupListUri()). + WithMethod(http.GET). + WithQueryParamFilter(MANNER, MARKER). + WithQueryParamFilter(MARKER, req.Marker). + WithQueryParamFilter(MAX_KEYS, strconv.Itoa(req.MaxKeys)). + WithQueryParamFilter(GROUP_NAME, req.GroupName). + WithResult(result). + Do() + return result, err +} + +// GetAsGroup 根据groupId获取AsGroup信息 +func (c *Client) GetAsGroup(req *GetAsGroupRequest) (*GetAsGroupResponse, error) { + if req == nil { + return nil, fmt.Errorf("GetAsGroupRequest is nil") + } + result := &GetAsGroupResponse{} + err := bce.NewRequestBuilder(c). + WithURL(getAsGroupDetailUri(req.GroupId)). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} + +// IncreaseAsGroup 伸缩组扩容,用于在指定伸缩组下添加节点 +func (c *Client) IncreaseAsGroup(req *IncreaseAsGroupRequest) error { + if req == nil { + return fmt.Errorf("IncreaseAsGroupRequest is nil") + } + if len(req.GroupId) == 0 { + return fmt.Errorf("IncreaseAsGroupRequest GroupId is empty") + } + if req.NodeCount <= 0 { + return fmt.Errorf("IncreaseAsGroupRequest NodeCount is invalid") + } + if req.Zone == nil || len(req.Zone) == 0 { + return fmt.Errorf("IncreaseAsGroupRequest Zone is nil") + } + err := bce.NewRequestBuilder(c). + WithURL(getAsGroupUri(req.GroupId)). + WithQueryParam(AS_SCALING_UP, ""). + WithBody(req). + WithMethod(http.POST). + Do() + if err != nil { + return err + } + return nil +} + +// DecreaseAsGroup 伸缩组缩容,用于伸缩组下节点的缩容 +func (c *Client) DecreaseAsGroup(req *DecreaseAsGroupRequest) error { + if req == nil { + return fmt.Errorf("DecreaseAsGroupRequest is nil") + } + if len(req.GroupId) == 0 { + return fmt.Errorf("IncreaseAsGroupRequest GroupId is empty") + } + if req.Nodes == nil || len(req.Nodes) == 0 { + return fmt.Errorf("DecreaseAsGroupRequest Nodes is nil") + } + err := bce.NewRequestBuilder(c). + WithURL(getAsGroupUri(req.GroupId)). + WithQueryParam(AS_SCALING_DOWN, ""). + WithBody(req). + WithMethod(http.POST). + Do() + if err != nil { + return err + } + return nil +} + +// ListAsNode 方法用于获取节点列表 +func (c *Client) ListAsNode(req *ListAsNodeRequest) (*ListAsNodeResponse, error) { + if req == nil { + return nil, fmt.Errorf("ListAsNodeRequest is nil") + } + if req.MaxKeys <= 0 || req.MaxKeys > 1000 { + req.MaxKeys = 1000 + } + result := &ListAsNodeResponse{} + err := bce.NewRequestBuilder(c). + WithURL(getAsNodeUri()). + WithMethod(http.GET). + WithQueryParamFilter(MANNER, MARKER). + WithQueryParamFilter(MARKER, req.Marker). + WithQueryParamFilter(MAX_KEYS, strconv.Itoa(req.MaxKeys)). + WithQueryParamFilter(GROUP_ID, req.GroupId). + WithResult(result). + Do() + return result, err +} + +// AdjustAsGroup 将伸缩组节点调整到指定值。 +func (c *Client) AdjustAsGroup(req *AdjustAsGroupRequest) error { + if req == nil { + return fmt.Errorf("AdjustAsGroupByNodeIdRequest is nil") + } + if len(req.GroupId) == 0 { + return fmt.Errorf("AdjustAsGroupByNodeIdRequest GroupId is empty") + } + err := bce.NewRequestBuilder(c). + WithURL(getAsGroupUri(req.GroupId)). + WithQueryParam(AS_ADJUST_NODE, ""). + WithMethod(http.POST). + WithBody(req). + Do() + return err +} diff --git a/bce-sdk-go/services/as/client.go b/bce-sdk-go/services/as/client.go new file mode 100644 index 0000000..5168914 --- /dev/null +++ b/bce-sdk-go/services/as/client.go @@ -0,0 +1,69 @@ +package as + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strings" +) + +const ( + ProductName = "as" + DefaultBcmEndpoint = ProductName + "." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN + VERSION_1_URL = "v1" + VERSION_2_URL = "v2" + AS_GROUP_URL = "group" + AS_NODE_URL = "node" + AS_DETAIL_URL = "detail" +) + +// Client of BCM service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the as service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + + if len(endpoint) == 0 { + endpoint = DefaultBcmEndpoint + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: map[string]struct{}{ + strings.ToLower(http.HOST): {}, + strings.ToLower(http.BCE_DATE): {}, + }, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +func getAsGroupListUri() string { + return "/" + VERSION_1_URL + "/" + AS_GROUP_URL +} + +func getAsGroupDetailUri(groupId string) string { + return "/" + VERSION_1_URL + "/" + AS_GROUP_URL + "/" + AS_DETAIL_URL + "/" + groupId +} + +func getAsGroupUri(groupId string) string { + return "/" + VERSION_2_URL + "/" + AS_GROUP_URL + "/" + groupId +} + +func getAsNodeUri() string { + return "/" + VERSION_1_URL + "/" + AS_NODE_URL +} diff --git a/bce-sdk-go/services/as/client_test.go b/bce-sdk-go/services/as/client_test.go new file mode 100644 index 0000000..11d44d0 --- /dev/null +++ b/bce-sdk-go/services/as/client_test.go @@ -0,0 +1,123 @@ +package as + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + asClient *Client + asConf *Conf +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` + InstanceId string `json:"InstanceId"` + UserId string `json:"UserId"` +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + asConf = &Conf{} + _ = decoder.Decode(asConf) + + asClient, _ = NewClient(asConf.AK, asConf.SK, asConf.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_GetAsGroupList(t *testing.T) { + req := &ListAsGroupRequest{ + GroupName: "test-name", + } + resp, err := asClient.ListAsGroup(req) + fmt.Println(resp) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetAsGroupDetail(t *testing.T) { + req := &GetAsGroupRequest{ + GroupId: "asg-wqksXo95", + } + resp, err := asClient.GetAsGroup(req) + fmt.Println(resp) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetAsNodeList(t *testing.T) { + req := &ListAsNodeRequest{ + GroupId: "asg-wqksXo95", + } + resp, err := asClient.ListAsNode(req) + fmt.Println(resp) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_IncreaseAs(t *testing.T) { + req := &IncreaseAsGroupRequest{ + GroupId: "asg-Hhm2ucIK", + Zone: []string{"zoneB"}, + NodeCount: 1, + } + err := asClient.IncreaseAsGroup(req) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DecreaseAs(t *testing.T) { + req := &DecreaseAsGroupRequest{ + GroupId: "asg-Hhm2ucIK", + Nodes: []string{"i-z0PXqFD3"}, + } + err := asClient.DecreaseAsGroup(req) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_AdjustAs(t *testing.T) { + req := &AdjustAsGroupRequest{ + GroupId: "asg-Hhm2ucIK", + AdjustNum: 1, + } + err := asClient.AdjustAsGroup(req) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/as/model.go b/bce-sdk-go/services/as/model.go new file mode 100644 index 0000000..f64966c --- /dev/null +++ b/bce-sdk-go/services/as/model.go @@ -0,0 +1,155 @@ +package as + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type ListAsGroupRequest struct { + GroupName string `json:"groupName,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListAsGroupResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Result []GroupInfo `json:"result"` +} + +type AsGroupStatus string + +const ( + CREATING AsGroupStatus = "CREATING" + RUNNING AsGroupStatus = "RUNNING" + SCALING_UP AsGroupStatus = "SCALING_UP" + SCALING_DOWN AsGroupStatus = "SCALING_DOWN" + ATTACHING_NODE AsGroupStatus = "ATTACHING_NODE" + DETACHING_NODE AsGroupStatus = "DETACHING_NODE" + DELETING AsGroupStatus = "DELETING" + BINDING_BLB AsGroupStatus = "BINDING_BLB" + UNBINDING_BLB AsGroupStatus = "UNBINDING_BLB" + COOLDOWN AsGroupStatus = "COOLDOWN" + PAUSE AsGroupStatus = "PAUSE" + DELETED AsGroupStatus = "DELETED" +) + +type ZoneInfo struct { + Zone string `json:"zone,omitempty"` + SubnetID string `json:"subnetId,omitempty"` + SubnetUUID string `json:"subnetUuid,omitempty"` + SubnetName string `json:"subnetName,omitempty"` + SubnetType int16 `json:"subnetType,omitempty"` + NodeCount int `json:"nodeCount,omitempty"` +} + +type GroupConfig struct { + MinNodeNum int `json:"minNodeNum,omitempty"` + MaxNodeNum int `json:"maxNodeNum,omitempty"` + CooldownInSec int `json:"cooldownInSec,omitempty"` + ExpectNum int `json:"expectNum,omitempty"` +} + +type GroupInfo struct { + GroupId string `json:"groupId,omitempty"` + GroupName string `json:"groupName,omitempty"` + Region string `json:"region,omitempty"` + Status AsGroupStatus `json:"status,omitempty"` + VpcId string `json:"vpcId,omitempty"` + NodeNum int `json:"nodeNum,omitempty"` + CreateTime string `json:"createTime,omitempty"` + ZoneInfo []ZoneInfo `json:"zoneInfo,omitempty"` + Config GroupConfig `json:"config,omitempty"` + BlbId string `json:"blbId,omitempty"` +} + +type GetAsGroupRequest struct { + GroupId string `json:"groupId,omitempty"` +} + +type VpcInfo struct { + VpcId string `json:"vpcId,omitempty"` + VpcName string `json:"vpcName,omitempty"` + VpcUUID string `json:"vpcUuid,omitempty"` +} + +type GetAsGroupResponse struct { + GroupID string `json:"groupId,omitempty"` + GroupName string `json:"groupName,omitempty"` + Region string `json:"region,omitempty"` + Status string `json:"status,omitempty"` + VpcInfo VpcInfo `json:"vpcInfo,omitempty"` + ZoneInfo []ZoneInfo `json:"zoneInfo,omitempty"` + Config GroupConfig `json:"config,omitempty"` + BlbID string `json:"blbId,omitempty"` + NodeNum int `json:"nodeNum,omitempty"` + CreateTime string `json:"createTime,omitempty"` + RdsIDs string `json:"rdsIds,omitempty"` + ScsIDs string `json:"scsIds,omitempty"` + ExpansionStrategy string `json:"expansionStrategy,omitempty"` + ShrinkageStrategy string `json:"shrinkageStrategy,omitempty"` +} + +type IncreaseAsGroupRequest struct { + ClientToken string `json:"-"` + GroupId string `json:"groupId,omitempty"` + NodeCount int `json:"nodeCount,omitempty"` + Zone []string `json:"zone,omitempty"` + ExpansionStrategy string `json:"expansionStrategy,omitempty"` +} + +type DecreaseAsGroupRequest struct { + ClientToken string `json:"-"` + GroupId string `json:"groupId,omitempty"` + Nodes []string `json:"nodes,omitempty"` +} + +type AdjustAsGroupRequest struct { + ClientToken string `json:"-"` + GroupId string `json:"groupId,omitempty"` + AdjustNum int `json:"adjustNum,omitempty"` +} + +type ListAsNodeRequest struct { + GroupId string `json:"groupId,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type AsEipModel struct { + BandwidthInMbps int `json:"bandwidthInMbps,omitempty"` + EipId string `json:"eipId,omitempty"` + Address string `json:"address,omitempty"` + EipStatus string `json:"eipStatus,omitempty"` + EipAllocationId string `json:"eipAllocationId,omitempty"` +} + +type NodeModel struct { + InstanceId string `json:"instanceId,omitempty"` + InstanceUuid string `json:"instanceUuid,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + FloatingIp string `json:"floatingIp,omitempty"` + InternalIp string `json:"internalIp,omitempty"` + Status string `json:"status,omitempty"` + Payment string `json:"payment,omitempty"` + CpuCount int64 `json:"cpuCount,omitempty"` + MemoryCapacityInGB int64 `json:"memoryCapacityInGB,omitempty"` + InstanceType string `json:"instanceType,omitempty"` + SysDiskInGB int `json:"sysDiskInGB,omitempty"` + CreateTime string `json:"createTime,omitempty"` + Eip AsEipModel `json:"eip,omitempty"` + SubnetType string `json:"subnetType,omitempty"` + IsProtected bool `json:"isProtected,omitempty"` + NodeType string `json:"nodeType,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + GroupId string `json:"groupId,omitempty"` +} + +type ListAsNodeResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Result []NodeModel `json:"result,omitempty"` +} diff --git a/bce-sdk-go/services/bbc/cds.go b/bce-sdk-go/services/bbc/cds.go new file mode 100644 index 0000000..fe6e616 --- /dev/null +++ b/bce-sdk-go/services/bbc/cds.go @@ -0,0 +1,57 @@ +package bbc + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +// ListCDSVolume - list all cds volumes with the given parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: the optional arguments to list cds volumes +// +// RETURNS: +// - *ListCDSVolumeResult: the result of cds volume list +// - error: nil if success otherwise the specific error +func ListCDSVolume(cli bce.Client, queryArgs *ListCDSVolumeArgs) (*ListCDSVolumeResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.InstanceId) != 0 { + req.SetParam("instanceId", queryArgs.InstanceId) + } + if len(queryArgs.ZoneName) != 0 { + req.SetParam("zoneName", queryArgs.ZoneName) + } + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListCDSVolumeResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/bbc/client.go b/bce-sdk-go/services/bbc/client.go new file mode 100644 index 0000000..fd8a1ce --- /dev/null +++ b/bce-sdk-go/services/bbc/client.go @@ -0,0 +1,1352 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BBC service + +// Package bbc defines the BBC services of BCE. The supported APIs are all defined in sub-package +package bbc + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +const DEFAULT_SERVICE_DOMAIN = "bbc." + bce.DEFAULT_REGION + ".baidubce.com" + +// Client of BBC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the BBC service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endPoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endPoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// CreateInstance - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstance(args *CreateInstanceArgs) (*CreateInstanceResult, error) { + if len(args.AdminPass) > 0 { + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + + args.AdminPass = cryptedPass + } + + if args.RootDiskSizeInGb <= 0 { + args.RootDiskSizeInGb = 20 + } + + if args.PurchaseCount < 1 { + args.PurchaseCount = 1 + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateInstance(c, args, body) +} + +// CreateInstance - create an instance with specific parameters and support the passing in of label +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific erro +func (c *Client) CreateInstanceByLabel(args *CreateSpecialInstanceArgs) (*CreateInstanceResult, error) { + if len(args.AdminPass) > 0 { + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + + args.AdminPass = cryptedPass + } + + if args.RootDiskSizeInGb <= 0 { + args.RootDiskSizeInGb = 20 + } + + if args.PurchaseCount < 1 { + args.PurchaseCount = 1 + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateInstanceByLabel(c, args, body) +} + +// CreateInstanceByLabelV2 - create an instance with specific parameters and support the passing in of label +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific erro +func (c *Client) CreateInstanceByLabelV2(argsV2 *CreateSpecialInstanceArgsV2) (*CreateInstanceResult, error) { + if len(argsV2.AdminPass) > 0 { + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, argsV2.AdminPass) + if err != nil { + return nil, err + } + argsV2.AdminPass = cryptedPass + } + + if argsV2.RootDiskSizeInGb <= 0 { + argsV2.RootDiskSizeInGb = 20 + } + + if argsV2.PurchaseCount < 1 { + argsV2.PurchaseCount = 1 + } + + defaultTrue := true + defaultFalse := false + if argsV2.EnableNuma == nil { + argsV2.EnableNuma = &defaultFalse + } + if argsV2.EnableHt == nil { + argsV2.EnableHt = &defaultTrue + } + jsonBytes, err := json.Marshal(argsV2) + if err != nil { + return nil, err + } + args := &CreateSpecialInstanceArgs{} + err = json.Unmarshal(jsonBytes, args) + if err != nil { + return nil, err + } + args.ClientToken = argsV2.ClientToken + + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateInstanceByLabel(c, args, body) +} + +// ListInstances - list all instance with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance +// +// RETURNS: +// - *ListInstanceResult: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) ListInstances(args *ListInstancesArgs) (*ListInstancesResult, error) { + return ListInstances(c, args) +} + +// GetInstanceDetail - get a specific instance detail info +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - *GetInstanceDetailResult: the result of get instance detail info +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceDetail(instanceId string) (*InstanceModel, error) { + return GetInstanceDetail(c, instanceId) +} + +func (c *Client) GetInstanceDetailWithDeploySet(instanceId string, isDeploySet bool) (*InstanceModel, error) { + return GetInstanceDetailWithDeploySet(c, instanceId, isDeploySet) +} + +func (c *Client) GetInstanceDetailWithDeploySetAndFailed(instanceId string, + isDeploySet bool, containsFailed bool) (*InstanceModel, error) { + return GetInstanceDetailWithDeploySetAndFailed(c, instanceId, isDeploySet, containsFailed) +} + +// StartInstance - start an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StartInstance(instanceId string) error { + return StartInstance(c, instanceId) +} + +// StopInstance - stop an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - forceStop: choose to force stop an instance or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StopInstance(instanceId string, forceStop bool) error { + args := &StopInstanceArgs{ + ForceStop: forceStop, + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return StopInstance(c, instanceId, body) +} + +// RebootInstance - restart an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - forceStop: choose to force stop an instance or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstance(instanceId string, forceStop bool) error { + args := &StopInstanceArgs{ + ForceStop: forceStop, + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return RebootInstance(c, instanceId, body) +} + +// ModifyInstanceName - modify an instance's name +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments of now instance's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyInstanceName(instanceId string, args *ModifyInstanceNameArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return ModifyInstanceName(c, instanceId, body) +} + +// ModifyInstanceDesc - modify an instance's description +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments of now instance's description +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyInstanceDesc(instanceId string, args *ModifyInstanceDescArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + clientToken := args.ClientToken + + return ModifyInstanceDesc(c, instanceId, clientToken, body) +} + +// RebuildInstance - rebuild an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - isPreserveData: choose to preserve data or not +// - args: the arguments to rebuild an instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebuildInstance(instanceId string, isPreserveData bool, args *RebuildInstanceArgs) error { + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return err + } + args.AdminPass = cryptedPass + + args.IsPreserveData = isPreserveData + + if !isPreserveData && args.SysRootSize <= 0 { + args.SysRootSize = 20 + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return RebuildInstance(c, instanceId, body) +} + +// GetInstanceVNC - get an instance's VNC url +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - *api.GetInstanceVNCResult: the result of get instance's VNC url +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceVNC(instanceId string) (*GetInstanceVNCResult, error) { + return GetInstanceVNC(c, instanceId) +} + +// RebuildBatchInstance - batch rebuild instances +// +// PARAMS: +// - args: the arguments to batch rebuild instances +// +// RETURNS: +// - *BatchRebuildResponse: the result of batch rebuild the instances +// - error: nil if success otherwise the specific error +func (c *Client) BatchRebuildInstances(args *RebuildBatchInstanceArgs) (*BatchRebuildResponse, error) { + if len(args.AdminPass) > 0 { + encryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + args.AdminPass = encryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return BatchRebuildInstances(c, body) +} + +// BatchRebuildInstancesV2 - batch rebuild instances +// +// PARAMS: +// - args: the arguments to batch rebuild instances +// +// RETURNS: +// - *BatchRebuildResponse: the result of batch rebuild the instances +// - error: nil if success otherwise the specific error +func (c *Client) BatchRebuildInstancesV2(argsV2 *RebuildBatchInstanceArgsV2) (*BatchRebuildResponse, error) { + if len(argsV2.AdminPass) > 0 { + encryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, argsV2.AdminPass) + if err != nil { + return nil, err + } + argsV2.AdminPass = encryptedPass + } + defaultTrue := true + if argsV2.IsPreserveData == nil { + argsV2.IsPreserveData = &defaultTrue + } + jsonBytes, jsonErr := json.Marshal(argsV2) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return BatchRebuildInstances(c, body) +} + +// InstancePurchaseReserved - purchase reserve an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to purchase reserved an instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstancePurchaseReserved(instanceId string, args *PurchaseReservedArgs) error { + // this api only support Prepaid instance + args.Billing.PaymentTiming = PaymentTimingPrePaid + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return InstancePurchaseReserved(c, instanceId, args.ClientToken, body) +} + +// DeleteInstance - delete an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstance(instanceId string) error { + return DeleteInstance(c, instanceId) +} + +// ListInstances - list all instance with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance +// +// RETURNS: +// - *ListInstanceResult: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) ListRecycledInstances(args *ListRecycledInstancesArgs) (*ListRecycledInstancesResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return ListRecycledInstances(c, body) +} + +// ListInstances - list all instance with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance +// +// RETURNS: +// - *ListInstanceResult: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) RecoveryInstances(args *RecoveryInstancesArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return RecoveryInstances(c, body) +} + +// DeleteInstance - delete an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstances(args *DeleteInstanceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return DeleteInstances(c, body) +} + +// ModifyInstancePassword - modify an instance's password +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments of now instance's password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyInstancePassword(instanceId string, args *ModifyInstancePasswordArgs) error { + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return err + } + args.AdminPass = cryptedPass + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return ModifyInstancePassword(c, instanceId, body) +} + +// InstanceChangeSubnet - change an instance's subnet +// +// PARAMS: +// - args: the arguments to change an instance's subnet +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceChangeSubnet(args *InstanceChangeSubnetArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return InstanceChangeSubnet(c, body) +} + +// InstanceChangeVpc - change an instance's vpc +// +// PARAMS: +// - args: the arguments to change an instance's vpc +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceChangeVpc(args *InstanceChangeVpcArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return InstanceChangeVpc(c, body) +} + +// GetVpcSubnet - get multi instances vpc and subnet +// +// PARAMS: +// - args: the instanceId of bbc instances +// +// RETURNS: +// - *GetVpcSubnetResult: result of vpc and subnet +// - error: nil if success otherwise the specific error +func (c *Client) GetVpcSubnet(args *GetVpcSubnetArgs) (*GetVpcSubnetResult, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return GetVpcSubnet(c, body) +} + +// BatchAddIP - Add ips to instance +// +// PARAMS: +// - args: the arguments to add ips to bbc instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchAddIP(args *BatchAddIpArgs) (*BatchAddIpResponse, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return BatchAddIp(c, args, body) +} + +// BatchDelIP - Delete ips of instance +// +// PARAMS: +// - args: the arguments to add ips to bbc instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDelIP(args *BatchDelIpArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return BatchDelIp(c, args, body) +} + +// BatchAddIPCrossSubnet - Add ips to instance cross subnet +// +// PARAMS: +// - args: the arguments to add ips to bbc instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchAddIPCrossSubnet(args *BatchAddIpCrossSubnetArgs) (*BatchAddIpResponse, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return BatchAddIpCrossSubnet(c, args, body) +} + +// BindTags - bind an instance tags +// +// PARAMS: +// - instanceId: the id of the instance +// - args: tags of an instance to bind +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindTags(instanceId string, args *BindTagsArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return BindTags(c, instanceId, body) +} + +// UnbindTags - unbind an instance tags +// +// PARAMS: +// - instanceId: the id of the instance +// - args: tags of an instance to unbind +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnbindTags(instanceId string, args *UnbindTagsArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return UnbindTags(c, instanceId, body) +} + +// ListFlavors - list all available flavors +// +// RETURNS: +// - *ListFlavorsResult: the result of list all flavors +// - error: nil if success otherwise the specific error +func (c *Client) ListFlavors() (*ListFlavorsResult, error) { + return ListFlavors(c) +} + +// GetFlavorDetail - get details of the specified flavor +// +// PARAMS: +// - flavorId: the id of the flavor +// +// RETURNS: +// - *GetFlavorDetailResult: the detail of the specified flavor +// - error: nil if success otherwise the specific error +func (c *Client) GetFlavorDetail(flavorId string) (*GetFlavorDetailResult, error) { + return GetFlavorDetail(c, flavorId) +} + +// GetFlavorRaid - get the RAID detail and disk size of the specified flavor +// +// PARAMS: +// - flavorId: the id of the flavor +// +// RETURNS: +// - *GetFlavorRaidResult: the detail of the raid of the specified flavor +// - error: nil if success otherwise the specific error +func (c *Client) GetFlavorRaid(flavorId string) (*GetFlavorRaidResult, error) { + return GetFlavorRaid(c, flavorId) +} + +// CreateImageFromInstanceId - create image from specified instance +// +// PARAMS: +// - args: the arguments to create image +// +// RETURNS: +// - *CreateImageResult: the result of create Image +// - error: nil if success otherwise the specific error +func (c *Client) CreateImageFromInstanceId(args *CreateImageArgs) (*CreateImageResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateImageFromInstanceId(c, args.ClientToken, body) +} + +// ListImage - list all images +// +// PARAMS: +// - args: the arguments to list all images +// +// RETURNS: +// - *ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func (c *Client) ListImage(args *ListImageArgs) (*ListImageResult, error) { + return ListImage(c, args) +} + +// GetImageDetail - get an image's detail info +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - *GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetImageDetail(imageId string) (*GetImageDetailResult, error) { + return GetImageDetail(c, imageId) +} + +// DeleteImage - delete an image +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteImage(imageId string) error { + return DeleteImage(c, imageId) +} + +// GetOperationLog - get operation log +// +// PARAMS: +// - args: the arguments to get operation log +// +// RETURNS: +// - *GetOperationLogResult: results of getting operation log +// - error: nil if success otherwise the specific error +func (c *Client) GetOperationLog(args *GetOperationLogArgs) (*GetOperationLogResult, error) { + return GetOperationLog(c, args) +} + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - args: the arguments to create a deploy set +// +// RETURNS: +// - *CreateDeploySetResult: results of creating a deploy set +// - error: nil if success otherwise the specific error +func (c *Client) CreateDeploySet(args *CreateDeploySetArgs) (*CreateDeploySetResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateDeploySet(c, args.ClientToken, body) +} + +// ListDeploySets - list all deploy sets +// +// RETURNS: +// - *ListDeploySetsResult: the result of list all deploy sets +// - error: nil if success otherwise the specific error +func (c *Client) ListDeploySets() (*ListDeploySetsResult, error) { + return ListDeploySets(c) +} + +// ListDeploySets - list all deploy sets +// PARAMS: +// - args: the arguments to filter +// +// RETURNS: +// - *ListDeploySetsResult: the result of list all deploy sets +// - error: nil if success otherwise the specific error +func (c *Client) ListDeploySetsPage(args *ListDeploySetsArgs) (*ListDeploySetsResult, error) { + return ListDeploySetsPage(c, args) +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *GetDeploySetResult: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *Client) GetDeploySet(deploySetId string) (*DeploySetResult, error) { + return GetDeploySet(c, deploySetId) +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDeploySet(deploySetId string) error { + return DeleteDeploySet(c, deploySetId) +} + +// BindSecurityGroups - Bind Security Groups +// +// PARAMS: +// - args: the arguments of bind security groups +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindSecurityGroups(args *BindSecurityGroupsArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return BindSecurityGroups(c, body) +} + +// UnBindSecurityGroups - UnBind Security Groups +// +// PARAMS: +// - args: the arguments of bind security groups +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindSecurityGroups(args *UnBindSecurityGroupsArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return UnBindSecurityGroups(c, body) +} + +// ListFlavorZones - get the zone list of the specified flavor which can buy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorId: the id of the flavor +// +// RETURNS: +// - *ListZonesResult: the list of zone names +// - error: nil if success otherwise the specific error +func (c *Client) ListFlavorZones(args *ListFlavorZonesArgs) (*ListZonesResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return ListFlavorZones(c, body) +} + +// ListZoneFlavors - get the flavor detail of the specific zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: the zone name +// +// RETURNS: +// - *ListZoneResult: flavor detail of the specific zone +// - error: nil if success otherwise the specific error +func (c *Client) ListZoneFlavors(args *ListZoneFlavorsArgs) (*ListFlavorInfosResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return ListZoneFlavors(c, body) +} + +// GetCommonImage - get common flavor image list +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorIds: the specific flavorIds, can be nil +// +// RETURNS: +// - *GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetCommonImage(args *GetFlavorImageArgs) (*GetImagesResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return GetCommonImage(c, body) +} + +// GetCustomImage - get user onwer flavor image list +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorIds: the specific flavorIds, can be nil +// +// RETURNS: +// - *GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetCustomImage(args *GetFlavorImageArgs) (*GetImagesResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return GetCustomImage(c, body) +} + +// ShareImage - share an image +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to share an image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ShareImage(imageId string, args *SharedUser) error { + return ShareImage(c, imageId, args) +} + +// UnShareImage - cancel share an image +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to cancel share an image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnShareImage(imageId string, args *SharedUser) error { + return UnShareImage(c, imageId, args) +} + +// GetImageSharedUser - get user list use this image +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - *api.GetImageSharedUserResult: the result of user list +// - error: nil if success otherwise the specific error +func (c *Client) GetImageSharedUser(imageId string) (*GetImageSharedUserResult, error) { + return GetImageSharedUser(c, imageId) +} + +// RemoteCopyImage - copy a bbc image from other region +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to remote copy an image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RemoteCopyImage(imageId string, args *RemoteCopyImageArgs) error { + return RemoteCopyImage(c, imageId, args) +} + +// RemoteCopyImageReturnImageIds - copy an image from other region +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to remote copy an image +// +// RETURNS: +// - imageIds of destination region if success otherwise the specific error +func (c *Client) RemoteCopyImageReturnImageIds(imageId string, args *RemoteCopyImageArgs) (*RemoteCopyImageResult, error) { + return RemoteCopyImageReturnImageIds(c, imageId, args) +} + +// CancelRemoteCopyImage - cancel a copy image from other region operation +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CancelRemoteCopyImage(imageId string) error { + return CancelRemoteCopyImage(c, imageId) +} + +// GetInstanceEni - get the eni of the bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the bbc instance id +// RETURNS: +// - error: nil if success otherwise the specific error + +func (c *Client) GetInstanceEni(instanceId string) (*GetInstanceEniResult, error) { + return GetInstanceEni(c, instanceId) +} + +func (c *Client) GetInstanceCreateStock(args *CreateInstanceStockArgs) (*InstanceStockResult, error) { + return GetInstanceCreateStock(c, args) +} + +func (c *Client) GetSimpleFlavor(args *GetSimpleFlavorArgs) (*SimpleFlavorResult, error) { + return GetSimpleFlavor(c, args) +} + +func (c *Client) GetInstancePirce(args *InstancePirceArgs) (*InstancePirceResult, error) { + return GetInstancePirce(c, args) +} + +func (c *Client) ListRepairTasks(args *ListRepairTaskArgs) (*ListRepairTaskResult, error) { + return ListRepairTasks(c, args) +} + +func (c *Client) ListClosedRepairTasks(args *ListClosedRepairTaskArgs) (*ListClosedRepairTaskResult, error) { + return ListClosedRepairTasks(c, args) +} + +func (c *Client) GetRepairTaskDetail(taskId string) (*GetRepairTaskResult, error) { + return GetTaskDetail(c, taskId) +} + +func (c *Client) AuthorizeRepairTask(args *TaskIdArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return AuthorizeRepairTask(c, body) +} + +func (c *Client) UnAuthorizeRepairTask(args *TaskIdArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return UnAuthorizeRepairTask(c, body) +} + +func (c *Client) ConfirmRepairTask(args *TaskIdArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return ConfirmRepairTask(c, body) +} + +func (c *Client) DisConfirmRepairTask(args *DisconfirmTaskArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return DisConfirmRepairTask(c, body) +} + +func (c *Client) GetRepairTaskRecord(args *TaskIdArgs) (*GetRepairRecords, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return GetRepairTaskReocrd(c, body) +} + +// ListRule - list the repair plat rules +// +// PARAMS: +// - args: the arguments of listing the repair plat rules +// +// RETURNS: +// - *ListRuleResult: results of listing the repair plat rules +// - error: nil if success otherwise the specific error +func (c *Client) ListRule(args *ListRuleArgs) (*ListRuleResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return ListRule(c, body) +} + +// GetRuleDetail - list the repair plat rules +// +// PARAMS: +// - ruleId: the specified rule id +// +// RETURNS: +// - *Rule: results of the specified repair plat rule +// - error: nil if success otherwise the specific error +func (c *Client) GetRuleDetail(ruleId string) (*Rule, error) { + return GetRuleDetail(c, ruleId) +} + +// CreateRule - create the repair plat rule +// +// PARAMS: +// - args: the arguments of creating the repair plat rule +// +// RETURNS: +// - *CreateRuleResult: results of the id of the repair plat rule which is created +// - error: nil if success otherwise the specific error +func (c *Client) CreateRule(args *CreateRuleArgs) (*CreateRuleResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return CreateRule(c, body) +} + +// DeleteRule - delete the repair plat rule +// +// PARAMS: +// - args: the arguments of deleting the repair plat rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRule(args *DeleteRuleArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return DeleteRule(c, body) +} + +// DisableRule - disable the repair plat rule +// +// PARAMS: +// - args: the arguments of disabling the repair plat rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DisableRule(args *DisableRuleArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return DisableRule(c, body) +} + +// EnableRule - enable the repair plat rule +// +// PARAMS: +// - args: the arguments of enabling the repair plat rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EnableRule(args *EnableRuleArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return EnableRule(c, body) +} + +// BatchCreateAutoRenewRules - Batch Create AutoRenew Rules +// +// PARAMS: +// - args: the arguments to batch create autorenew rules +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchCreateAutoRenewRules(args *BbcCreateAutoRenewArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return BatchCreateAutoRenewRules(c, body) +} + +// BatchDeleteAutoRenewRules - Batch Delete AutoRenew Rules +// +// PARAMS: +// - args: the arguments to batch delete autorenew rules +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDeleteAutoRenewRules(args *BbcDeleteAutoRenewArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return BatchDeleteAutoRenewRules(c, body) +} + +func (c *Client) DeleteInstanceIngorePayment(args *DeleteInstanceIngorePaymentArgs) (*DeleteInstanceResult, error) { + return DeleteBbcIngorePayment(c, args) +} + +// DeleteRecycledInstance - delete an recycled instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecycledInstance(instanceId string) error { + return DeleteRecycledInstance(c, instanceId) +} + +// ListCDSVolume - list all cds volume with the specific parameters +// +// PARAMS: +// - args: the arguments to list all cds +// +// RETURNS: +// - *api.ListCDSVolumeResult: the result of list all CDS volume +// - error: nil if success otherwise the specific error +func (c *Client) ListCDSVolume(queryArgs *ListCDSVolumeArgs) (*ListCDSVolumeResult, error) { + return ListCDSVolume(c, queryArgs) +} + +// GetBbcStockWithDeploySet - get the bbc's stock with deploySet +// +// RETURNS: +// - *GetBbcStocksResult: the result of the bbc's stock +// - error: nil if success otherwise the specific error +func (c *Client) GetBbcStockWithDeploySet(args *GetBbcStockArgs) (*GetBbcStocksResult, error) { + return GetStockWithDeploySet(c, args) +} + +// ListInstanceByInstanceIds - list bbc detail info by instanceId +// +// RETURNS: +// - *ListInstancesResult: the result of list bbc detail info +// - error: nil if success otherwise the specific error +func (c *Client) ListInstanceByInstanceIds(args *ListInstanceByInstanceIdArgs) (*ListInstancesResult, error) { + return ListInstanceByInstanceIds(c, args) +} diff --git a/bce-sdk-go/services/bbc/client_test.go b/bce-sdk-go/services/bbc/client_test.go new file mode 100644 index 0000000..5f66808 --- /dev/null +++ b/bce-sdk-go/services/bbc/client_test.go @@ -0,0 +1,923 @@ +package bbc + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BBC_CLIENT *Client + BBC_TestBbcId string + BBC_TestImageId string + BBC_TestFlavorId string + BBC_TestRaidId string + BBC_TestZoneName string + BBC_TestSubnetId string + BBC_TestName string + BBC_TestAdminPass string + BBC_TestDeploySetId string + BBC_TestClientToken string + BBC_TestSecurityGroupId string + BBC_TestTaskId string + BBC_TestErrResult string + BBC_TestRuleId string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 6; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fmt.Println(conf) + fp, err := os.Open(conf) + if err != nil { + fmt.Println("config json file of ak/sk not given: ", conf) + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + BBC_TestFlavorId = "flavor-id" + BBC_TestImageId = "image-id" + BBC_TestRaidId = "raid-id" + BBC_TestZoneName = "zone-name" + BBC_TestSubnetId = "subnet-id" + BBC_TestName = "sdkTest" + BBC_TestAdminPass = "123@adminPass" + BBC_TestDeploySetId = "deployset-id" + BBC_TestBbcId = "bbc_id" + BBC_TestSecurityGroupId = "bbc-security-group-id" + BBC_TestTaskId = "task-id" + BBC_TestErrResult = "err-result" + BBC_TestRuleId = "rule-id" + BBC_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) + //log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestCreateInstance(t *testing.T) { + InternalIps := []string{"ip"} + createInstanceArgs := &CreateInstanceArgs{ + FlavorId: BBC_TestFlavorId, + ImageId: BBC_TestImageId, + RaidId: BBC_TestRaidId, + RootDiskSizeInGb: 40, + PurchaseCount: 1, + AdminPass: "AdminPass", + ZoneName: BBC_TestZoneName, + SubnetId: BBC_TestSubnetId, + SecurityGroupId: BBC_TestSecurityGroupId, + ClientToken: BBC_TestClientToken, + Billing: Billing{ + PaymentTiming: PaymentTimingPostPaid, + }, + DeploySetId: BBC_TestDeploySetId, + Name: BBC_TestName, + EnableNuma: false, + InternalIps: InternalIps, + Tags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, + } + res, err := BBC_CLIENT.CreateInstance(createInstanceArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateSpecialInstance(t *testing.T) { + InternalIps := []string{"ip"} + createSpecialInstanceArgs := &CreateSpecialInstanceArgs{ + FlavorId: BBC_TestFlavorId, + ImageId: BBC_TestImageId, + RaidId: BBC_TestRaidId, + RootDiskSizeInGb: 40, + PurchaseCount: 1, + AdminPass: "AdminPass", + ZoneName: BBC_TestZoneName, + SubnetId: BBC_TestSubnetId, + SecurityGroupId: BBC_TestSecurityGroupId, + ClientToken: BBC_TestClientToken, + Billing: Billing{ + PaymentTiming: PaymentTimingPostPaid, + }, + DeploySetId: BBC_TestDeploySetId, + Name: BBC_TestName, + EnableNuma: false, + InternalIps: InternalIps, + Tags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, + LabelConstraints: []LabelConstraint{{ + Key: "feaA", + Operator: LabelOperatorExist, + }, { + Key: "feaB", + Value: "typeB", + Operator: LabelOperatorNotEqual, + }}, + } + // 将使用『没有 feaC 这个 label』且『feaD 这个 label 的值为 typeD』的测试机创建实例 + res, err := BBC_CLIENT.CreateInstanceByLabel(createSpecialInstanceArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateSpecialInstanceV2(t *testing.T) { + InternalIps := []string{"ip"} + createSpecialInstanceArgs := &CreateSpecialInstanceArgsV2{ + FlavorId: BBC_TestFlavorId, + ImageId: BBC_TestImageId, + RaidId: BBC_TestRaidId, + RootDiskSizeInGb: 40, + PurchaseCount: 1, + AdminPass: "AdminPass", + ZoneName: BBC_TestZoneName, + SubnetId: BBC_TestSubnetId, + SecurityGroupId: BBC_TestSecurityGroupId, + ClientToken: BBC_TestClientToken, + Billing: Billing{ + PaymentTiming: PaymentTimingPostPaid, + }, + DeploySetId: BBC_TestDeploySetId, + Name: BBC_TestName, + InternalIps: InternalIps, + Tags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, + LabelConstraints: []LabelConstraint{{ + Key: "feaA", + Operator: LabelOperatorExist, + }, { + Key: "feaB", + Value: "typeB", + Operator: LabelOperatorNotEqual, + }}, + } + // 将使用『没有 feaC 这个 label』且『feaD 这个 label 的值为 typeD』的测试机创建实例 + res, err := BBC_CLIENT.CreateInstanceByLabelV2(createSpecialInstanceArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListInstances(t *testing.T) { + listArgs := &ListInstancesArgs{ + MaxKeys: 500, + } + res, err := BBC_CLIENT.ListInstances(listArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetInstanceDetail(t *testing.T) { + res, err := BBC_CLIENT.GetInstanceDetail("i-4PvLVv37") + fmt.Println(res.Status) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetInstanceDetailWithDeploySetAndFailed(t *testing.T) { + res, err := BBC_CLIENT.GetInstanceDetailWithDeploySetAndFailed(BBC_TestBbcId, false, true) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestStopInstance(t *testing.T) { + err := BBC_CLIENT.StopInstance(BBC_TestBbcId, false) + ExpectEqual(t.Errorf, err, nil) +} + +func TestStartInstance(t *testing.T) { + err := BBC_CLIENT.StartInstance(BBC_TestBbcId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRebootInstance(t *testing.T) { + err := BBC_CLIENT.RebootInstance(BBC_TestBbcId, true) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyInstanceName(t *testing.T) { + modifyInstanceNameArgs := &ModifyInstanceNameArgs{ + Name: "new_bbc_name", + } + err := BBC_CLIENT.ModifyInstanceName(BBC_TestBbcId, modifyInstanceNameArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyInstanceDesc(t *testing.T) { + modifyInstanceDescArgs := &ModifyInstanceDescArgs{ + Description: "new_bbc_description_02", + ClientToken: "be31b98c-5e42-4838-9230-9be700de5a20", + } + err := BBC_CLIENT.ModifyInstanceDesc(BBC_TestBbcId, modifyInstanceDescArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRebuildInstance(t *testing.T) { + rebuildArgs := &RebuildInstanceArgs{ + ImageId: BBC_TestImageId, + AdminPass: BBC_TestAdminPass, + IsPreserveData: true, + RaidId: BBC_TestRaidId, + SysRootSize: 20, + RootPartitionType: "xfs", + DataPartitionType: "xfs", + } + err := BBC_CLIENT.RebuildInstance(BBC_TestBbcId, true, rebuildArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchRebuildInstances(t *testing.T) { + rebuildArgs := &RebuildBatchInstanceArgs{ + ImageId: "ImageId", + AdminPass: "123qaz!@#", + InstanceIds: []string{"BBC_TestBbcId"}, + IsPreserveData: true, + RaidId: BBC_TestRaidId, + SysRootSize: 20, + RootPartitionType: "xfs", + DataPartitionType: "xfs", + } + result, err := BBC_CLIENT.BatchRebuildInstances(rebuildArgs) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchRebuildInstancesV2(t *testing.T) { + argsV2 := &RebuildBatchInstanceArgsV2{ + ImageId: "ImageId", + AdminPass: "123qaz!@#", + InstanceIds: []string{"BBC_TestBbcId"}, + RaidId: BBC_TestRaidId, + SysRootSize: 20, + RootPartitionType: "xfs", + DataPartitionType: "xfs", + } + result, err := BBC_CLIENT.BatchRebuildInstancesV2(argsV2) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) +} + +func TestReleaseInstance(t *testing.T) { + err := BBC_CLIENT.DeleteInstance(BBC_TestBbcId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyInstancePassword(t *testing.T) { + modifyInstancePasswordArgs := &ModifyInstancePasswordArgs{ + AdminPass: BBC_TestAdminPass, + } + err := BBC_CLIENT.ModifyInstancePassword(BBC_TestBbcId, modifyInstancePasswordArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetVpcSubnet(t *testing.T) { + getVpcSubnetArgs := &GetVpcSubnetArgs{ + BbcIds: []string{BBC_TestBbcId}, + } + result, err := BBC_CLIENT.GetVpcSubnet(getVpcSubnetArgs) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchAddIp(t *testing.T) { + privateIps := []string{"192.168.200.25"} + batchAddIpArgs := &BatchAddIpArgs{ + InstanceId: BBC_TestBbcId, + PrivateIps: privateIps, + ClientToken: "be31b98c-5e41-4838-9230-9be700de5a20", + } + result, err := BBC_CLIENT.BatchAddIP(batchAddIpArgs) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchAddIpCrossSubnet(t *testing.T) { + batchAddIpCrossSubnetArgs := &BatchAddIpCrossSubnetArgs{ + InstanceId: BBC_TestBbcId, + SingleEniAndSubentIps: []SingleEniAndSubentIp{ + { + EniId: "eni-cc31j8i1nq5f", + IpAndSubnets: []IpAndSubnet{ + { + PrivateIp: "192.168.0.6", + SubnetId: "sbn-af5iegk24se1", + }, + }, + }, + }, + ClientToken: "be31b98c-5e41-4838-9230-9be700de5a20", + } + result, err := BBC_CLIENT.BatchAddIPCrossSubnet(batchAddIpCrossSubnetArgs) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchDelIp(t *testing.T) { + privateIps := []string{"192.168.1.25"} + batchDelIpArgs := &BatchDelIpArgs{ + InstanceId: BBC_TestBbcId, + PrivateIps: privateIps, + ClientToken: "be31b98c-5e41-4e38-9230-9be700de5120", + } + err := BBC_CLIENT.BatchDelIP(batchDelIpArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBindTags(t *testing.T) { + bindTagsArgs := &BindTagsArgs{ + ChangeTags: []model.TagModel{ + { + TagKey: "BBCTestKey", + TagValue: "BBCTestValue", + }, + }, + } + err := BBC_CLIENT.BindTags(BBC_TestBbcId, bindTagsArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnbindTags(t *testing.T) { + unbindTagsArgs := &UnbindTagsArgs{ + ChangeTags: []model.TagModel{ + { + TagKey: "BCC", + TagValue: "aaa", + }, + }, + } + err := BBC_CLIENT.UnbindTags(BBC_TestBbcId, unbindTagsArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListFlavors(t *testing.T) { + res, err := BBC_CLIENT.ListFlavors() + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetFlavorDetail(t *testing.T) { + testFlavorId := BBC_TestFlavorId + rep, err := BBC_CLIENT.GetFlavorDetail(testFlavorId) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetFlavorRaid(t *testing.T) { + testFlavorId := "BBC-G4-01S" + rep, err := BBC_CLIENT.GetFlavorRaid(testFlavorId) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateImageFromInstanceId(t *testing.T) { + testInstanceId := BBC_TestBbcId + testImageName := "testCreateImage" + queryArgs := &CreateImageArgs{ + ImageName: testImageName, + InstanceId: testInstanceId, + } + rep, err := BBC_CLIENT.CreateImageFromInstanceId(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListImage(t *testing.T) { + queryArgs := &ListImageArgs{} + rep, err := BBC_CLIENT.ListImage(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetImageDetail(t *testing.T) { + testImageId := "" + rep, err := BBC_CLIENT.GetImageDetail(testImageId) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteImage(t *testing.T) { + testImageId := BBC_TestImageId + err := BBC_CLIENT.DeleteImage(testImageId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetOperationLog(t *testing.T) { + queryArgs := &GetOperationLogArgs{ + StartTime: "2021-03-28T15:00:27Z", + EndTime: "2021-03-30T15:00:27Z", + } + rep, err := BBC_CLIENT.GetOperationLog(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateDeploySet(t *testing.T) { + testDeploySetName := "testName" + testDeployDesc := "testDesc" + testConcurrency := 1 + testStrategy := "tor_ha" + queryArgs := &CreateDeploySetArgs{ + Strategy: testStrategy, + Concurrency: testConcurrency, + Name: testDeploySetName, + Desc: testDeployDesc, + } + rep, err := BBC_CLIENT.CreateDeploySet(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListDeploySets(t *testing.T) { + rep, err := BBC_CLIENT.ListDeploySets() + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListDeploySetsPage(t *testing.T) { + queryArgs := &ListDeploySetsArgs{ + Strategy: "TOR_HA", // RACK_HA or TOR_HA + MaxKeys: 100, + Marker: "your-marker", + } + rep, err := BBC_CLIENT.ListDeploySetsPage(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetDeploySet(t *testing.T) { + testDeploySetID := BBC_TestDeploySetId + rep, err := BBC_CLIENT.GetDeploySet(testDeploySetID) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteDeploySet(t *testing.T) { + testDeleteDeploySetId := BBC_TestDeploySetId + err := BBC_CLIENT.DeleteDeploySet(testDeleteDeploySetId) + fmt.Println(err) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBindSecurityGroups(t *testing.T) { + instanceIds := []string{""} + sg := []string{""} + args := &BindSecurityGroupsArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: sg, + } + err := BBC_CLIENT.BindSecurityGroups(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnBindSecurityGroups(t *testing.T) { + args := &UnBindSecurityGroupsArgs{ + InstanceId: "", + SecurityGroupId: "", + } + err := BBC_CLIENT.UnBindSecurityGroups(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetFlavorZone(t *testing.T) { + flavorId := "BBC-G3-01" + queryArgs := &ListFlavorZonesArgs{ + FlavorId: flavorId, + } + if res, err := BBC_CLIENT.ListFlavorZones(queryArgs); err != nil { + fmt.Println("Get flavor zoneName failed: ", err) + } else { + fmt.Println("Get flavor zoneName success, result: ", res) + } +} + +func TestListZoneFlavors(t *testing.T) { + zoneName := "cn-bj-b" + queryArgs := &ListZoneFlavorsArgs{ + ZoneName: zoneName, + } + if res, err := BBC_CLIENT.ListZoneFlavors(queryArgs); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) + } else { + fmt.Println("Get the specific zone flavor success, result: ", res) + } +} + +func TestGetCommonImage(t *testing.T) { + flavorIds := []string{"BBC-S3-02"} + queryArgs := &GetFlavorImageArgs{ + FlavorIds: flavorIds, + } + if res, err := BBC_CLIENT.GetCommonImage(queryArgs); err != nil { + fmt.Println("Get specific flavor common image failed: ", err) + } else { + fmt.Println("Get specific flavor common image success, result: ", res) + } +} + +func TestGetCustomImage(t *testing.T) { + flavorIds := []string{"flavorId"} + queryArgs := &GetFlavorImageArgs{ + FlavorIds: flavorIds, + } + if res, err := BBC_CLIENT.GetCustomImage(queryArgs); err != nil { + fmt.Println("Get specific flavor common image failed: ", err) + } else { + fmt.Println("Get specific flavor common image success, result: ", res) + } +} + +func TestShareImage(t *testing.T) { + args := &SharedUser{ + AccountId: "id", + } + err := BBC_CLIENT.ShareImage(BBC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnShareImage(t *testing.T) { + args := &SharedUser{ + AccountId: "id", + } + err := BBC_CLIENT.UnShareImage(BBC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetImageSharedUser(t *testing.T) { + users, err := BBC_CLIENT.GetImageSharedUser(BBC_TestImageId) + if err != nil { + fmt.Println("error: ", err) + } else { + fmt.Println(users) + } +} + +func TestRemoteCopyImage(t *testing.T) { + args := &RemoteCopyImageArgs{ + Name: "testRemoteCopy", + DestRegion: []string{"hkg"}, + } + err := BBC_CLIENT.RemoteCopyImage(BBC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCancelRemoteCopyImage(t *testing.T) { + err := BBC_CLIENT.CancelRemoteCopyImage(BBC_TestImageId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRemoteCopyImageReturnImageIds(t *testing.T) { + args := &RemoteCopyImageArgs{ + Name: "Copy", + DestRegion: []string{"hkg"}, + } + result, err := BBC_CLIENT.RemoteCopyImageReturnImageIds(BBC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestGetInstanceEni(t *testing.T) { + instanceId := "instanceId" + if res, err := BBC_CLIENT.GetInstanceEni(instanceId); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success, result: ", res) + } +} + +func TestGetInstanceStock(t *testing.T) { + args := &CreateInstanceStockArgs{ + FlavorId: "BBC-G4-PDDAS", + ZoneName: "cn-su-a", + } + if res, err := BBC_CLIENT.GetInstanceCreateStock(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success, result: ", res) + } +} + +func TestListRepairTasks(t *testing.T) { + listArgs := &ListRepairTaskArgs{ + MaxKeys: 100, + } + res, err := BBC_CLIENT.ListRepairTasks(listArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListClosedRepairTasks(t *testing.T) { + listArgs := &ListClosedRepairTaskArgs{ + MaxKeys: 100, + } + res, err := BBC_CLIENT.ListClosedRepairTasks(listArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetTaskDetail(t *testing.T) { + res, err := BBC_CLIENT.GetRepairTaskDetail(BBC_TestTaskId) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAuthorizeTask(t *testing.T) { + taskIdArgs := &TaskIdArgs{ + TaskId: BBC_TestTaskId, + } + err := BBC_CLIENT.AuthorizeRepairTask(taskIdArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnAuthorizeTask(t *testing.T) { + taskIdArgs := &TaskIdArgs{ + TaskId: BBC_TestTaskId, + } + err := BBC_CLIENT.UnAuthorizeRepairTask(taskIdArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestConfirmTask(t *testing.T) { + taskIdArgs := &TaskIdArgs{ + TaskId: BBC_TestTaskId, + } + err := BBC_CLIENT.ConfirmRepairTask(taskIdArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDisConfirmTask(t *testing.T) { + disconfirmTaskArgs := &DisconfirmTaskArgs{ + TaskId: BBC_TestTaskId, + NewErrResult: BBC_TestErrResult, + } + err := BBC_CLIENT.DisConfirmRepairTask(disconfirmTaskArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetRepairRecord(t *testing.T) { + taskIdArgs := &TaskIdArgs{ + TaskId: BBC_TestTaskId, + } + res, err := BBC_CLIENT.GetRepairTaskRecord(taskIdArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListRule(t *testing.T) { + args := &ListRuleArgs{ + Marker: "your-marker", + MaxKeys: 100, + RuleName: "your-choose-rule-name", + RuleId: "your-choose-rule-id", + } + res, err := BBC_CLIENT.ListRule(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestGetRuleDetail(t *testing.T) { + ruleId := BBC_TestRuleId + res, err := BBC_CLIENT.GetRuleDetail(ruleId) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestCreateRule(t *testing.T) { + args := &CreateRuleArgs{ + RuleName: "goSdkRule", + Limit: 2, + Enabled: 1, + TagStr: "msinstancekey:msinstancevalue", + Extra: "extra", + } + res, err := BBC_CLIENT.CreateRule(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestDeleteRule(t *testing.T) { + args := &DeleteRuleArgs{ + RuleId: BBC_TestRuleId, + } + err := BBC_CLIENT.DeleteRule(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDisableRule(t *testing.T) { + args := &DisableRuleArgs{ + RuleId: BBC_TestRuleId, + } + err := BBC_CLIENT.DisableRule(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestEnableRule(t *testing.T) { + args := &EnableRuleArgs{ + RuleId: BBC_TestRuleId, + } + err := BBC_CLIENT.EnableRule(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchCreateAutoRenewRules(t *testing.T) { + bccAutoRenewArgs := &BbcCreateAutoRenewArgs{ + InstanceId: BBC_TestBbcId, + RenewTimeUnit: "month", + RenewTime: 1, + } + err := BBC_CLIENT.BatchCreateAutoRenewRules(bccAutoRenewArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchDeleteAutoRenewRules(t *testing.T) { + bccAutoRenewArgs := &BbcDeleteAutoRenewArgs{ + InstanceId: BBC_TestBbcId, + } + err := BBC_CLIENT.BatchDeleteAutoRenewRules(bccAutoRenewArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteInstanceIngorePayment(t *testing.T) { + args := &DeleteInstanceIngorePaymentArgs{ + InstanceId: "InstanceId", + RelatedReleaseFlag: true, + } + if res, err := BBC_CLIENT.DeleteInstanceIngorePayment(args); err != nil { + fmt.Println("delete instance failed: ", err) + } else { + fmt.Println("delelte instance success, result: ", res) + } +} + +func TestListCDSVolume(t *testing.T) { + queryArgs := &ListCDSVolumeArgs{ + MaxKeys: 100, + InstanceId: "InstanceId", + Marker: "VolumeId", + ZoneName: "zoneName", + } + if res, err := BBC_CLIENT.ListCDSVolume(queryArgs); err != nil { + fmt.Println("list volume failed: ", err) + } else { + fmt.Println("list volume success, result: ", res) + } +} + +func TestDeleteInstanceV2(t *testing.T) { + instanceIds := []string{"instanceId"} + queryArgs := &DeleteInstanceArgs{ + BbcRecycleFlag: true, + InstanceIds: instanceIds, + } + if err := BBC_CLIENT.DeleteInstances(queryArgs); err != nil { + fmt.Println("delete instance failed: ", err) + } else { + fmt.Println("delete instance success") + } +} + +func TestListRecycledInstances(t *testing.T) { + queryArgs := &ListRecycledInstancesArgs{ + Marker: "your marker", + PaymentTiming: "your paymentTiming", + RecycleBegin: "RecycleBegin", // recycled begin time ,eg: 2020-11-23T17:18:24Z + RecycleEnd: "RecycleEnd", + MaxKeys: 10, + InstanceId: "InstanceId", + Name: "InstanceName", + } + if res, err := BBC_CLIENT.ListRecycledInstances(queryArgs); err != nil { + fmt.Println("list recycled bbc failed: ", err) + } else { + fmt.Println("list recycled bbc success, result: ", res) + } +} + +func TestInstanceChangeSubnet(t *testing.T) { + args := &InstanceChangeSubnetArgs{ + InstanceId: "i-DFlNGqLf", + SubnetId: "sbn-z1y9tcedqnh6", + InternalIp: "10.10.10.1", + Reboot: true, + } + + err := BBC_CLIENT.InstanceChangeSubnet(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestInstanceChangeVpc(t *testing.T) { + args := &InstanceChangeVpcArgs{ + InstanceId: "i-xxxxx", + SubnetId: "sbn-zyyyyyyy", + Reboot: true, + } + + err := BBC_CLIENT.InstanceChangeVpc(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRecoveryInstances(t *testing.T) { + instanceIds := []string{"instanceId"} + queryArgs := &RecoveryInstancesArgs{ + InstanceIds: instanceIds, + } + if err := BBC_CLIENT.RecoveryInstances(queryArgs); err != nil { + fmt.Println("recovery instance failed: ", err) + } else { + fmt.Println("recovery instance success") + } +} + +func TestGetInstanceVnc(t *testing.T) { + res, err := BBC_CLIENT.GetInstanceVNC(BBC_TestBbcId) + ExpectEqual(t.Errorf, err, nil) + fmt.Println("get instance vnc success: ", res.VNCUrl) +} + +func TestGetBbcStockWithDeploySet(t *testing.T) { + queryArgs := &GetBbcStockArgs{ + Flavor: "BBC-S3-02", + DeploySetIds: []string{"dset-0RHZYUfF"}, + } + if res, err := BBC_CLIENT.GetBbcStockWithDeploySet(queryArgs); err != nil { + fmt.Println("get bbc stock failed: ", err) + } else { + data, e := json.Marshal(res) + if e != nil { + fmt.Println("json marshal failed!") + return + } + fmt.Printf("get bbc stock, result : %s", data) + } +} + +func TestListInstanceByInstanceIds(t *testing.T) { + args := &ListInstanceByInstanceIdArgs{ + InstanceIds: []string{"i-3s8MUcfl"}, + } + result, err := BBC_CLIENT.ListInstanceByInstanceIds(args) + if err != nil { + fmt.Println("list instance failed: ", err) + } else { + fmt.Println("list instance success") + data, e := json.Marshal(result) + if e != nil { + fmt.Println("json marshal failed!") + return + } + fmt.Printf("list instance : %s", data) + } +} diff --git a/bce-sdk-go/services/bbc/deploySet.go b/bce-sdk-go/services/bbc/deploySet.go new file mode 100644 index 0000000..0254110 --- /dev/null +++ b/bce-sdk-go/services/bbc/deploySet.go @@ -0,0 +1,207 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// deploySet.go - the deploy set APIs definition supported by the BBC service + +// Package bbc defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// - reqBody: http request body +// +// RETURNS: +// - *CreateDeploySetResult: results of creating a deploy set +// - error: nil if success otherwise the specific error +func CreateDeploySet(cli bce.Client, clientToken string, reqBody *bce.Body) (*CreateDeploySetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateDeploySetResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListDeploySets - list all deploy sets +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListDeploySetsResult: the result of list all deploy sets +// - error: nil if success otherwise the specific error +func ListDeploySets(cli bce.Client) (*ListDeploySetsResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUri()) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListDeploySetsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListDeploySets - list all deploy sets +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the filter of deployset +// +// RETURNS: +// - *ListDeploySetsResult: the result of list all deploy sets +// - error: nil if success otherwise the specific error +func ListDeploySetsPage(cli bce.Client, args *ListDeploySetsArgs) (*ListDeploySetsResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.Strategy) != 0 { + req.SetParam("strategy", args.Strategy) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "500") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListDeploySetsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *GetDeploySetResult: the detail of the deploy set +// - error: nil if success otherwise the specific error +func GetDeploySet(cli bce.Client, deploySetId string) (*DeploySetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(deploySetId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeploySetResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteDeploySet(cli bce.Client, deploySetId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(deploySetId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + + return nil +} + +func getDeploySetUri() string { + return URI_PREFIX_V1 + REQUEST_DEPLOY_SET_URI +} + +func getDeploySetUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_DEPLOY_SET_URI + "/" + id +} diff --git a/bce-sdk-go/services/bbc/flavor.go b/bce-sdk-go/services/bbc/flavor.go new file mode 100644 index 0000000..1ab028d --- /dev/null +++ b/bce-sdk-go/services/bbc/flavor.go @@ -0,0 +1,207 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// flavor.go - the flavor APIs definition supported by the BBC service + +// Package defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListFlavors - list all available flavors +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListFlavorsResult: the result of list all flavors +// - error: nil if success otherwise the specific error +func ListFlavors(cli bce.Client) (*ListFlavorsResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavorUri()) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListFlavorsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetFlavorDetail - get details of the specified flavor +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorId: the id of the flavor +// +// RETURNS: +// - *GetFlavorDetailResult: the detail of the specified flavor +// - error: nil if success otherwise the specific error +func GetFlavorDetail(cli bce.Client, flavorId string) (*GetFlavorDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavorUriWithId(flavorId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetFlavorDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetFlavorRaid - get the RAID detail and disk size of the specified flavor +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorId: the id of the flavor +// +// RETURNS: +// - *GetFlavorRaidResult: the detail of the raid of the specified flavor +// - error: nil if success otherwise the specific error +func GetFlavorRaid(cli bce.Client, flavorId string) (*GetFlavorRaidResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavorRaidUriWithId(flavorId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetFlavorRaidResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListFlavorZones - get the zone list of the specified flavor which can buy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorId: the id of the flavor +// +// RETURNS: +// - *ListZonesResult: the list of zone names +// - error: nil if success otherwise the specific error +func ListFlavorZones(cli bce.Client, reqBody *bce.Body) (*ListZonesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavorZoneUrl()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + fmt.Println(getFlavorZoneUrl()) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListZonesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListZoneFlavors - get the flavor detail of the specific zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: the zone name +// +// RETURNS: +// - *ListZoneResult: flavor detail of the specific zone +// - error: nil if success otherwise the specific error +func ListZoneFlavors(cli bce.Client, reqBody *bce.Body) (*ListFlavorInfosResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavors()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListFlavorInfosResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func getFlavorUri() string { + return URI_PREFIX_V1 + REQUEST_FLAVOR_URI +} + +func getFlavorUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_FLAVOR_URI + "/" + id +} + +func getFlavorRaidUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_FLAVOR_RAID_URI + "/" + id +} + +func getFlavorZoneUrl() string { + return URI_PREFIX_V1 + REQUEST_FLAVOR_ZONE_URI +} + +func getFlavors() string { + return URI_PREFIX_V1 + REQUEST_FLAVORS_URI +} diff --git a/bce-sdk-go/services/bbc/image.go b/bce-sdk-go/services/bbc/image.go new file mode 100644 index 0000000..daf813d --- /dev/null +++ b/bce-sdk-go/services/bbc/image.go @@ -0,0 +1,478 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// image.go - the image APIs definition supported by the BBC service + +// Package bbc defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "encoding/json" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateImageFromInstanceId - create image from specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// - reqBody: http request body +// +// RETURNS: +// - *CreateImageResult: the result of create Image +// - error: nil if success otherwise the specific error +func CreateImageFromInstanceId(cli bce.Client, clientToken string, reqBody *bce.Body) (*CreateImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListImage - list all images +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list all images +// +// RETURNS: +// - *ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func ListImage(cli bce.Client, queryArgs *ListImageArgs) (*ListImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.ImageType) != 0 { + req.SetParam("imageType", queryArgs.ImageType) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetImageDetail - get an image's detail info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: the specific image ID +// +// RETURNS: +// - *GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func GetImageDetail(cli bce.Client, imageId string) (*GetImageDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImageDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// DeleteImage - delete an image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: the specific image ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteImage(cli bce.Client, imageId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// GetCommonImage - get common flavor image list +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorIds: the specific flavorIds, can be nil +// +// RETURNS: +// - *GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func GetCommonImage(cli bce.Client, reqBody *bce.Body) (*GetImagesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCommonImageUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImagesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetCustomImage - get user onwer flavor image list +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - flavorIds: the specific flavorIds, can be nil +// +// RETURNS: +// - *GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func GetCustomImage(cli bce.Client, reqBody *bce.Body) (*GetImagesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCustomImageUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImagesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ShareImage - share a specified custom image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be shared +// - args: the arguments to share image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ShareImage(cli bce.Client, imageId string, args *SharedUser) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("share", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// UnShareImage - unshare a specified image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be unshared +// - args: the arguments to unshare image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UnShareImage(cli bce.Client, imageId string, args *SharedUser) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("unshare", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// GetImageSharedUser - get the list of users that the image has been shared with +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image +// +// RETURNS: +// - *GetImageSharedUserResult: result of the shared users +// - error: nil if success otherwise the specific error +func GetImageSharedUser(cli bce.Client, imageId string) (*GetImageSharedUserResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageSharedUserUri(imageId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImageSharedUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// RemoteCopyImage - copy bbc custom images across regions, only custom images supported, the system \ +// and service integration images cannot be copied. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be copied +// - args: the arguments to copy image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RemoteCopyImage(cli bce.Client, imageId string, args *RemoteCopyImageArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("remoteCopy", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// CancelRemoteCopyImage - cancel the image copy across regions +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CancelRemoteCopyImage(cli bce.Client, imageId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("cancelRemoteCopy", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RemoteCopyImageReturnImageIds - copy custom images across regions, only custom images supported, the system \ +// and service integration images cannot be copied. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be copied +// - args: the arguments to copy image +// +// RETURNS: +// - imageIds of destination region if success otherwise the specific error +func RemoteCopyImageReturnImageIds(cli bce.Client, imageId string, args *RemoteCopyImageArgs) (*RemoteCopyImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("remoteCopy", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &RemoteCopyImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func getImageUri() string { + return URI_PREFIX_V1 + REQUEST_IMAGE_URI +} + +func getImageUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_IMAGE_URI + "/" + id +} + +func getCommonImageUri() string { + return URI_PREFIX_V1 + REQUEST_COMMON_IMAGE_URI +} + +func getCustomImageUri() string { + return URI_PREFIX_V1 + REQUEST_CUSTOM_IMAGE_URI +} + +func getImageSharedUserUri(id string) string { + return URI_PREFIX_V1 + REQUEST_IMAGE_URI + "/" + id + REQUEST_IMAGE_SHAREDUSER_URI +} diff --git a/bce-sdk-go/services/bbc/instance.go b/bce-sdk-go/services/bbc/instance.go new file mode 100644 index 0000000..8fa9128 --- /dev/null +++ b/bce-sdk-go/services/bbc/instance.go @@ -0,0 +1,1295 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// instance.go - the instance APIs definition supported by the BBC service + +// Package bbc defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateInstance - create a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// - reqBody: http request body +// +// RETURNS: +// - *CreateInstanceResult: results of creating a bbc instance +// - error: nil if success otherwise the specific error +func CreateInstance(cli bce.Client, args *CreateInstanceArgs, reqBody *bce.Body) (*CreateInstanceResult, + error) { + clientToken := args.ClientToken + requestToken := args.RequestToken + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetHeader("x-request-token", requestToken) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// CreateInstance - create a bbc instance and support the passing in of label +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// - reqBody: http request body +// +// RETURNS: +// - *CreateInstanceResult: results of creating a bbc instance +// - error: nil if success otherwise the specific error +func CreateInstanceByLabel(cli bce.Client, args *CreateSpecialInstanceArgs, reqBody *bce.Body) (*CreateInstanceResult, + error) { + clientToken := args.ClientToken + requestToken := args.RequestToken + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceByLabelUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetHeader("x-request-token", requestToken) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListInstances - list all bbc instances +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list bbc instances +// +// RETURNS: +// - *ListInstanceResult: results of list bbc instances +// - error: nil if success otherwise the specific error +func ListInstances(cli bce.Client, args *ListInstancesArgs) (*ListInstancesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.InternalIp) != 0 { + req.SetParam("internalIp", args.InternalIp) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstancesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetInstanceDetail - get a bbc instance detail msg +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - *InstanceModel: instance detail msg +// - error: nil if success otherwise the specific error +func GetInstanceDetailWithDeploySet(cli bce.Client, instanceId string, isDeploySet bool) (*InstanceModel, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.GET) + if isDeploySet == true { + req.SetParam("isDeploySet", "true") + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstanceModel{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetInstanceDetail - get a bbc instance detail msg +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - *InstanceModel: instance detail msg +// - error: nil if success otherwise the specific error +func GetInstanceDetailWithDeploySetAndFailed(cli bce.Client, instanceId string, + isDeploySet bool, containsFailed bool) (*InstanceModel, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.GET) + if isDeploySet == true { + req.SetParam("isDeploySet", "true") + } + if containsFailed == true { + req.SetParam("containsFailed", "true") + } else { + req.SetParam("containsFailed", "false") + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstanceModel{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func GetInstanceDetail(cli bce.Client, instanceId string) (*InstanceModel, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.GET) + req.SetParam("isDeploySet", "false") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstanceModel{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// StartInstance - start a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func StartInstance(cli bce.Client, instanceId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("start", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// StopInstance - stop a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func StopInstance(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("stop", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ListInstances - list all bbc instances +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list bbc instances +// +// RETURNS: +// - *ListInstanceResult: results of list bbc instances +// - error: nil if success otherwise the specific error +func ListRecycledInstances(cli bce.Client, reqBody *bce.Body) (*ListRecycledInstancesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRecycledInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListRecycledInstancesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func RecoveryInstances(cli bce.Client, reqBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getRecoveryInstancesUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteInstance - delete a specified instance,contains prepay or postpay instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// RETURNS: +// - error: nil if success otherwise the specific error + +func DeleteBbcIngorePayment(cli bce.Client, args *DeleteInstanceIngorePaymentArgs) (*DeleteInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeleteBbcDeleteIngorePaymentUri()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeleteInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func getDeleteBbcDeleteIngorePaymentUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/delete" +} + +// RebootInstance - reboot a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RebootInstance(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("reboot", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyInstanceName - modify a bbc instance name +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyInstanceName(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("rename", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyInstanceDesc - modify a bbc instance desc +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyInstanceDesc(cli bce.Client, instanceId string, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("updateDesc", "") + req.SetBody(reqBody) + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RebuildInstance - rebuild a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RebuildInstance(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("rebuild", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchRebuildInstances - batch rebuild instances +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to rebuild instance +// +// RETURNS: +// - *BatchRebuildResponse: result of batch rebuild instances +// - error: nil if success otherwise the specific error +func BatchRebuildInstances(cli bce.Client, reqBody *bce.Body) (*BatchRebuildResponse, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRebuildBatchInstanceUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + fmt.Println(resp) + jsonBody := &BatchRebuildResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// InstancePurchaseReserved - renew a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be renewed +// - reqBody: the request body to renew instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func InstancePurchaseReserved(cli bce.Client, instanceId string, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("purchaseReserved", "") + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteInstance - delete a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteInstance(cli bce.Client, instanceId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithIdV2(instanceId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteInstance - delete a bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteInstances(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchDeleteInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteRecycledInstance - delete a recycled bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteRecycledInstance(cli bce.Client, instanceId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeleteRecycledInstanceUri(instanceId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// GetVpcSubnet - get multi instances vpc and subnet +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - *GetVpcSubnetResult: result of vpc and subnet +// - error: nil if success otherwise the specific error +func GetVpcSubnet(cli bce.Client, reqBody *bce.Body) (*GetVpcSubnetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSubnetUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetVpcSubnetResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ModifyInstancePassword - modify a bbc instance password +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyInstancePassword(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("changePass", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchAddIp - Add ips to instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchAddIp(cli bce.Client, args *BatchAddIpArgs, reqBody *bce.Body) (*BatchAddIpResponse, error) { + // Build the request + clientToken := args.ClientToken + req := &bce.BceRequest{} + req.SetUri(getBatchAddIpUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BatchAddIpResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// BatchAddIp - Add ips to instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchAddIpCrossSubnet(cli bce.Client, args *BatchAddIpCrossSubnetArgs, reqBody *bce.Body) (*BatchAddIpResponse, + error) { + // Build the request + clientToken := args.ClientToken + req := &bce.BceRequest{} + req.SetUri(getBatchAddIpCrossSubnetUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BatchAddIpResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// BatchDelIp - Delete ips of instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchDelIp(cli bce.Client, args *BatchDelIpArgs, reqBody *bce.Body) error { + // Build the request + clientToken := args.ClientToken + req := &bce.BceRequest{} + req.SetUri(getBatchDelIpUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func GetInstanceCreateStock(cli bce.Client, args *CreateInstanceStockArgs) (*InstanceStockResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCreateInstanceStock()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstanceStockResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetSimpleFlavor(cli bce.Client, args *GetSimpleFlavorArgs) (*SimpleFlavorResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getsimpleFlavor()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &SimpleFlavorResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetInstancePirce(cli bce.Client, args *InstancePirceArgs) (*InstancePirceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstancePirce()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstancePirceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetInstanceEni - get the eni of the bbc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the bbc instance id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func GetInstanceEni(cli bce.Client, instanceId string) (*GetInstanceEniResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceEniUri(instanceId)) + req.SetMethod(http.GET) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetInstanceEniResult{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetInstanceVNC - get VNC address of the specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetInstanceVNCResult: result of the VNC address of the instance +// - error: nil if success otherwise the specific error +func GetInstanceVNC(cli bce.Client, instanceId string) (*GetInstanceVNCResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceVNCUri(instanceId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetInstanceVNCResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// BatchCreateAutoRenewRules - Batch Create AutoRenew Rules +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchCreateAutoRenewRules(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchCreateAutoRenewRulesUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchDeleteAutoRenewRules - Batch Delete AutoRenew Rules +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchDeleteAutoRenewRules(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchDeleteAutoRenewRulesUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// InstanceChangeVpc - change the subnet to which the instance belongs +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to change subnet of instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func InstanceChangeSubnet(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getChangeSubnetUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// InstanceChangeVpc - change the vpc to which the instance belongs +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to change vpc of instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func InstanceChangeVpc(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getChangeVpcUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func getInstanceVNCUri(instanceId string) string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/" + instanceId + "/vnc" +} + +func getInstanceEniUri(instanceId string) string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_PORT_URI + "/" + instanceId +} + +func getInstanceUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI +} + +func getInstanceByLabelUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_LABEL_URI +} + +func getRecycledInstanceUri() string { + return URI_PREFIX_V1 + REQUEST_RECYCLE_URI + REQUEST_INSTANCE_URI +} + +func getRecoveryInstancesUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_RECOVERY_URI +} + +func getInstanceUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/" + id +} + +func getBatchAddIpUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCHADDIP_URI +} + +func getBatchAddIpCrossSubnetUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCHADDIPCROSSSUBNET_URI +} + +func getBatchDelIpUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCHDELIP_URI +} + +func getBatchDeleteInstanceUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCH_DELETE_URI +} + +func getInstanceUriWithIdV2(id string) string { + return URI_PREFIX_V2 + REQUEST_INSTANCE_URI + "/" + id +} + +func getDeleteRecycledInstanceUri(id string) string { + return URI_PREFIX_V1 + "/recycle" + REQUEST_INSTANCE_URI + "/" + id +} + +func getSubnetUri() string { + return URI_PREFIX_V1 + REQUEST_SUBNET_URI +} + +func getCreateInstanceStock() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/stock/createInstance" +} + +func getsimpleFlavor() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/simpleFlavor" +} + +func getInstancePirce() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/price" +} + +func getBatchCreateAutoRenewRulesUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCH_CREATE_AUTORENEW_RULES_URI +} + +func getBatchDeleteAutoRenewRulesUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCH_Delete_AUTORENEW_RULES_URI +} + +func getRebuildBatchInstanceUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + REQUEST_BATCH_REBUILD_INSTANCE_URI +} + +func getChangeSubnetUri() string { + return URI_PREFIX_V1 + "/subnet" + "/changeSubnet" +} + +func getChangeVpcUri() string { + return URI_PREFIX_V1 + REQUEST_VPC_URI + "/changeVpc" +} + +// GetStockWithDeploySet - get the bbc's stock with deploySet +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get the bbc's stock with deploySet +// +// RETURNS: +// - *GetBbcStocksResult: the result of the bbc's stock +// - error: nil if success otherwise the specific error +func GetStockWithDeploySet(cli bce.Client, args *GetBbcStockArgs) (*GetBbcStocksResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(geBbcStockWithDeploySetUri()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetBbcStocksResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListInstanceByInstanceIds - list instance by instanceId +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListInstancesResult: result of the instance list +// - error: nil if success otherwise the specific error +func ListInstanceByInstanceIds(cli bce.Client, args *ListInstanceByInstanceIdArgs) (*ListInstancesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getListInstancesByIdsUrl()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstancesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/bbc/model.go b/bce-sdk-go/services/bbc/model.go new file mode 100644 index 0000000..21ec6f8 --- /dev/null +++ b/bce-sdk-go/services/bbc/model.go @@ -0,0 +1,1049 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package bbc + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type PaymentTimingType string + +const ( + PaymentTimingPrePaid PaymentTimingType = "Prepaid" + PaymentTimingPostPaid PaymentTimingType = "Postpaid" +) + +type InstanceStatus string + +const ( + InstanceStatusRunning InstanceStatus = "Running" + InstanceStatusStarting InstanceStatus = "Starting" + InstanceStatusStopping InstanceStatus = "Stopping" + InstanceStatusStopped InstanceStatus = "Stopped" + InstanceStatusDeleted InstanceStatus = "Deleted" + InstanceStatusExpired InstanceStatus = "Expired" + InstanceStatusError InstanceStatus = "Error" + InstanceStatusImageProcessing InstanceStatus = "ImageProcessing" + InstanceStatusChangeVpcProcessing InstanceStatus = "ChangeVpc" + InstanceStatusRecycled InstanceStatus = "Recycled" + InstanceStatusRecharging InstanceStatus = "Recharging" +) + +type ImageType string + +const ( + ImageTypeIntegration ImageType = "Integration" + ImageTypeSystem ImageType = "System" + ImageTypeCustom ImageType = "Custom" +) + +type ImageStatus string + +const ( + ImageStatusCreating ImageStatus = "Creating" + ImageStatusCreateFailed ImageStatus = "CreateFailed" + ImageStatusAvailable ImageStatus = "Available" + ImageStatusNotAvailable ImageStatus = "NotAvailable" + ImageStatusError ImageStatus = "Error" +) + +type VolumeType string + +const ( + VolumeTypeSYSTEM VolumeType = "System" + VolumeTypeEPHEMERAL VolumeType = "Ephemeral" + VolumeTypeCDS VolumeType = "Cds" +) + +type StorageType string + +const ( + StorageTypeStd1 StorageType = "std1" + StorageTypeHP1 StorageType = "hp1" + StorageTypeCloudHP1 StorageType = "cloud_hp1" + StorageTypeLocal StorageType = "local" + StorageTypeSATA StorageType = "sata" + StorageTypeSSD StorageType = "ssd" + StorageTypeHDDThroughput StorageType = "HDD_Throughput" + StorageTypeHdd StorageType = "hdd" +) + +type VolumeStatus string + +const ( + VolumeStatusAVAILABLE VolumeStatus = "Available" + VolumeStatusINUSE VolumeStatus = "InUse" + VolumeStatusSNAPSHOTPROCESSING VolumeStatus = "SnapshotProcessing" + VolumeStatusRECHARGING VolumeStatus = "Recharging" + VolumeStatusDETACHING VolumeStatus = "Detaching" + VolumeStatusDELETING VolumeStatus = "Deleting" + VolumeStatusEXPIRED VolumeStatus = "Expired" + VolumeStatusNOTAVAILABLE VolumeStatus = "NotAvailable" + VolumeStatusDELETED VolumeStatus = "Deleted" + VolumeStatusSCALING VolumeStatus = "Scaling" + VolumeStatusIMAGEPROCESSING VolumeStatus = "ImageProcessing" + VolumeStatusCREATING VolumeStatus = "Creating" + VolumeStatusATTACHING VolumeStatus = "Attaching" + VolumeStatusERROR VolumeStatus = "Error" +) + +type CreateInstanceArgs struct { + FlavorId string `json:"flavorId"` + ImageId string `json:"imageId"` + RaidId string `json:"raidId"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb"` + PurchaseCount int `json:"purchaseCount"` + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Billing Billing `json:"billing"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + DeploySetId string `json:"deploySetId,omitempty"` + ClientToken string `json:"-"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` + RequestToken string `json:"requestToken"` + EnableNuma bool `json:"enableNuma"` + EnableHt bool `json:"enableHt"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type CreateInstanceArgsV2 struct { + FlavorId string `json:"flavorId"` + ImageId string `json:"imageId"` + RaidId string `json:"raidId"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb"` + PurchaseCount int `json:"purchaseCount"` + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Billing Billing `json:"billing"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + DeploySetId string `json:"deploySetId,omitempty"` + ClientToken string `json:"-"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` + RequestToken string `json:"requestToken"` + EnableNuma *bool `json:"enableNuma"` + EnableHt *bool `json:"enableHt"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +const ( + LabelOperatorEqual LabelOperator = "equal" + LabelOperatorNotEqual LabelOperator = "not_equal" + LabelOperatorExist LabelOperator = "exist" + LabelOperatorNotExist LabelOperator = "not_exist" +) + +type LabelOperator string + +type LabelConstraint struct { + Key string `json:"labelKey,omitempty"` + Value string `json:"labelValue,omitempty"` + Operator LabelOperator `json:"operatorName,omitempty"` +} + +type CreateSpecialInstanceArgs struct { + FlavorId string `json:"flavorId"` + ImageId string `json:"imageId"` + RaidId string `json:"raidId"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb"` + PurchaseCount int `json:"purchaseCount"` + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Billing Billing `json:"billing"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + DeploySetId string `json:"deploySetId,omitempty"` + ClientToken string `json:"-"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` + RequestToken string `json:"requestToken"` + EnableNuma bool `json:"enableNuma"` + EnableHt bool `json:"enableHt"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` + // CreateInstanceArgs 的基础上增加的参数 + LabelConstraints []LabelConstraint `json:"labelConstraints,omitempty"` +} + +type CreateSpecialInstanceArgsV2 struct { + FlavorId string `json:"flavorId"` + ImageId string `json:"imageId"` + RaidId string `json:"raidId"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb"` + PurchaseCount int `json:"purchaseCount"` + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Billing Billing `json:"billing"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + DeploySetId string `json:"deploySetId,omitempty"` + ClientToken string `json:"-"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` + RequestToken string `json:"requestToken"` + EnableNuma *bool `json:"enableNuma"` + EnableHt *bool `json:"enableHt"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` + // CreateInstanceArgs 的基础上增加的参数 + LabelConstraints []LabelConstraint `json:"labelConstraints,omitempty"` +} + +type CreateSpecialInstanceResult struct { + InstanceIds []string `json:"instanceIds"` +} + +type Billing struct { + PaymentTiming PaymentTimingType `json:"paymentTiming,omitempty"` + Reservation Reservation `json:"reservation,omitempty"` +} + +type Reservation struct { + Length int `json:"reservationLength"` + TimeUnit string `json:"reservationTimeUnit"` +} + +type CreateInstanceResult struct { + InstanceIds []string `json:"instanceIds"` +} + +type ListInstancesArgs struct { + Marker string + MaxKeys int + InternalIp string + VpcId string `json:"vpcId"` +} + +type RecoveryInstancesArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type ListRecycledInstancesArgs struct { + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + InstanceId string `json:"instanceId,omitempty"` + Name string `json:"name,omitempty"` + PaymentTiming string `json:"paymentTiming,omitempty"` + RecycleBegin string `json:"recycleBegin,omitempty"` + RecycleEnd string `json:"recycleEnd,omitempty"` +} + +type ListRecycledInstancesResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RecycledInstances []RecycledInstancesModel `json:"instances"` +} + +type RecycledInstancesModel struct { + ServiceType string `json:"serviceType"` + ServiceName string `json:"serviceName"` + Name string `json:"name"` + Id string `json:"id"` + SerialNumber string `json:"serialNumber"` + RecycleTime string `json:"recycleTime"` + DeleteTime string `json:"deleteTime"` + PaymentTiming string `json:"paymentTiming"` + ConfigItems []string `json:"configItems"` + ConfigItem RecycleInstanceModelConfigItem `json:"configItem"` +} + +type RecycleInstanceModelConfigItem struct { + Cpu int `json:"cpu"` + Memory int `json:"memory"` + Type string `json:"type"` + ZoneName string `json:"zoneName"` +} + +type ListInstancesResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []InstanceModel `json:"instances"` +} + +type InstanceModel struct { + Id string `json:"id"` + Name string `json:"name"` + Hostname string `json:"hostname"` + Uuid string `json:"uuid"` + Desc string `json:"desc"` + Status InstanceStatus `json:"status"` + PaymentTiming string `json:"paymentTiming"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + PublicIp string `json:"publicIp"` + InternalIp string `json:"internalIp"` + RdmaIp string `json:"rdmaIp"` + ImageId string `json:"imageId"` + FlavorId string `json:"flavorId"` + Zone string `json:"zone"` + Region string `json:"region"` + HasAlive int `json:"hasAlive"` + Tags []model.TagModel `json:"tags"` + SwitchId string `json:"switchId"` + HostId string `json:"hostId"` + DeploysetId string `json:"deploysetId"` + NetworkCapacityInMbps int `json:"networkCapacityInMbps"` + RackId string `json:"rackId"` +} + +type StopInstanceArgs struct { + ForceStop bool `json:"forceStop,omitempty"` +} + +type ModifyInstanceNameArgs struct { + Name string `json:"name"` +} + +type InstanceChangeSubnetArgs struct { + InstanceId string `json:"instanceId"` + SubnetId string `json:"subnetId"` + InternalIp string `json:"internalIp"` + Reboot bool `json:"reboot"` +} + +type InstanceChangeVpcArgs struct { + InstanceId string `json:"instanceId"` + SubnetId string `json:"subnetId"` + InternalIp string `json:"internalIp"` + Reboot bool `json:"reboot"` +} + +type ModifyInstanceDescArgs struct { + Description string `json:"desc"` + ClientToken string `json:"clientToken"` +} + +type ModifyInstanceHostnameArgs struct { + Hostname string `json:"hostname"` + Reboot bool `json:"reboot"` +} + +type RebuildInstanceArgs struct { + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + IsPreserveData bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type RebuildBatchInstanceArgs struct { + InstanceIds []string `json:"instanceIds"` + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + IsPreserveData bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type RebuildBatchInstanceArgsV2 struct { + InstanceIds []string `json:"instanceIds"` + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + IsPreserveData *bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type BatchRebuildResponse struct { + Result []BatchRebuild `json:"result"` +} + +type BatchRebuild struct { + InstanceIds []string `json:"instanceIds"` + ErrMsp string `json:"errMsg"` + Code string `json:"code"` +} + +type GetVpcSubnetArgs struct { + BbcIds []string `json:"bbcIds"` +} + +type GetVpcSubnetResult struct { + NetworkInfo []BbcNetworkModel `json:"networkInfo"` +} + +type BbcNetworkModel struct { + BbcId string `json:"bbcId"` + Vpc VpcModel `json:"vpc"` + Subnet SubnetModel `json:"subnet"` +} + +type VpcModel struct { + VpcId string `json:"vpcId"` + Cidr string `json:"cidr"` + Name string `json:"name"` + IsDefault bool `json:"isDefault"` + Description string `json:"description"` +} + +type SubnetModel struct { + VpcId string `json:"vpcId"` + Name string `json:"name"` + SubnetType string `json:"subnetType"` + SubnetId string `json:"subnetId"` + Cidr string `json:"cidr"` + ZoneName string `json:"zoneName"` +} + +type ModifyInstancePasswordArgs struct { + AdminPass string `json:"adminPass"` +} + +type BatchAddIpArgs struct { + InstanceId string `json:"instanceId"` + PrivateIps []string `json:"privateIps"` + SecondaryPrivateIpAddressCount int `json:"secondaryPrivateIpAddressCount"` + AllocateMultiIpv6Addr bool `json:"allocateMultiIpv6Addr"` + ClientToken string `json:"-"` +} + +type BatchAddIpCrossSubnetArgs struct { + InstanceId string `json:"instanceId"` + SingleEniAndSubentIps []SingleEniAndSubentIp `json:"singleEniAndSubentIps"` + ClientToken string `json:"-"` +} + +type SingleEniAndSubentIp struct { + EniId string `json:"eniId"` + SubnetId string `json:"subnetId"` + SecondaryPrivateIpAddressCount int `json:"secondaryPrivateIpAddressCount"` + IpAndSubnets []IpAndSubnet `json:"ipAndSubnets"` +} + +type IpAndSubnet struct { + PrivateIp string `json:"privateIp"` + SubnetId string `json:"subnetId"` +} + +type BatchAddIpResponse struct { + PrivateIps []string `json:"privateIps"` +} + +type BatchDelIpArgs struct { + InstanceId string `json:"instanceId"` + PrivateIps []string `json:"privateIps"` + ClientToken string `json:"-"` +} + +type BindTagsArgs struct { + ChangeTags []model.TagModel `json:"changeTags"` +} + +type UnbindTagsArgs struct { + ChangeTags []model.TagModel `json:"changeTags"` +} + +type ListImageArgs struct { + Marker string + MaxKeys int + ImageType string +} + +type ListImageResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Images []ImageModel `json:"images"` +} + +type ImageModel struct { + OsVersion string `json:"osVersion"` + OsArch string `json:"osArch"` + Status ImageStatus `json:"status"` + Desc string `json:"desc"` + Id string `json:"id"` + Name string `json:"name"` + OsName string `json:"osName"` + OsBuild string `json:"osBuild"` + CreateTime string `json:"createTime"` + Type ImageType `json:"type"` + OsType string `json:"osType"` + SpecialVersion string `json:"specialVersion"` +} + +type FlavorImageModel struct { + FlavorId string `json:"flavorId"` + Images []ImageModel `json:"images"` +} + +type GetImageDetailResult struct { + Result *ImageModel `json:"image"` +} + +type GetImagesResult struct { + Result []FlavorImageModel `json:"result"` +} + +type ListFlavorsResult struct { + Flavors []FlavorModel `json:"flavors"` +} + +type FlavorModel struct { + FlavorId string `json:"flavorID"` + CpuCount int `json:"cpuCount"` + CpuType string `json:"cpuType"` + MemoryCapacityInGB int `json:"memoryCapacityInGb"` + Disk string `json:"disk"` + NetworkCard string `json:"networkCard"` + Others string `json:"others"` +} + +type GetFlavorDetailResult struct { + FlavorModel +} + +type GetFlavorRaidResult struct { + FlavorId string `json:"flavorId"` + Raids []RaidModel `json:"raids"` +} + +type RaidModel struct { + RaidId string `json:"raidId"` + Raid string `json:"raid"` + SysSwapSize int `json:"sysSwapSize"` + SysRootSize int `json:"sysRootSize"` + SysHomeSize int `json:"sysHomeSize"` + SysDiskSize int `json:"sysDiskSize"` + DataDiskSize float64 `json:"dataDiskSize"` +} + +type CreateImageArgs struct { + ImageName string `json:"imageName"` + InstanceId string `json:"instanceId"` + ClientToken string `json:"-"` +} + +type CreateImageResult struct { + ImageId string `json:"imageId"` +} + +type GetOperationLogArgs struct { + Marker string + MaxKeys int + StartTime string + EndTime string +} + +type GetOperationLogResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + OperationLogs []OperationLogModel `json:"operationLogs"` +} + +type GetInstanceVNCResult struct { + VNCUrl string `json:"vncUrl"` +} + +type OperationLogModel struct { + OperationStatus bool `json:"operationStatus"` + OperationTime string `json:"operationTime"` + OperationDesc string `json:"operationDesc"` + OperationIp string `json:"operationIp"` +} + +type CreateDeploySetArgs struct { + Strategy string `json:"strategy"` + Concurrency int `json:"concurrency"` + Name string `json:"name,omitempty"` + Desc string `json:"desc,omitempty"` + ClientToken string `json:"-"` +} + +type GetFlavorImageArgs struct { + FlavorIds []string `json:"flavorIds"` + ClientToken string `json:"-"` +} + +type CreateDeploySetResult struct { + DeploySetId string `json:"deploySetId"` +} + +type ListDeploySetsArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"MaxKeys"` + Strategy string `json:"strategy"` +} + +type ListDeploySetsResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + DeploySetList []DeploySetModel `json:"deploySetList"` +} + +type AzIntstanceStatis struct { + ZoneName string `json:"zoneName"` + Count int `json:"instanceCount"` + BbcCount int `json:"bbcInstanceCnt"` + BccCount int `json:"bccInstanceCnt"` + Total int `json:"instanceTotal"` +} + +type DeploySetModel struct { + Strategy string `json:"strategy"` + AzIntstanceStatisList []AzIntstanceStatis `json:"azIntstanceStatisList"` + Name string `json:"name"` + Desc string `json:"desc"` + DeploySetId string `json:"deploysetId"` + Concurrency int `json:"concurrency"` +} + +type GetDeploySetResult struct { + DeploySetModel +} + +type BindSecurityGroupsArgs struct { + InstanceIds []string `json:"instanceIds"` + SecurityGroupIds []string `json:"securityGroups"` +} + +type UnBindSecurityGroupsArgs struct { + InstanceId string `json:"instanceId"` + SecurityGroupId string `json:"securityGroupId"` +} +type ListZonesResult struct { + ZoneNames []string `json:"zoneNames"` +} + +type DiskInfo struct { + Raid string `json:"raid"` + Description string `json:"description"` + DataDiskName string `json:"dataDiskName"` + RaidDisplay string `json:"raidDisplay"` + SysAndHomeSize float64 `json:"sysAndHomeSize"` + DataDiskSize float64 `json:"dataDiskSize"` + RaidId string `json:"raidId"` +} + +type BbcFlavorInfo struct { + Count int `json:"count"` + SataInfo string `json:"sataInfo"` + Cpu int `json:"cpu"` + CpuGhz string `json:"cpuGhz"` + Memory int `json:"memory"` + StorageType string `json:"type"` + FlavorId string `json:"id"` + DiskInfos map[string]DiskInfo `json:"diskInfos"` +} + +type ListFlavorInfosResult struct { + BbcFlavorInfoList []BbcFlavorInfo `json:"bbcFlavorInfoList"` +} + +type ListFlavorZonesArgs struct { + FlavorId string `json:"flavorId"` + ProductType PaymentTimingType `json:"productType"` +} + +type ListZoneFlavorsArgs struct { + ZoneName string `json:"zoneName"` + ProductType PaymentTimingType `json:"productType"` +} + +type PurchaseReservedArgs struct { + Billing Billing `json:"billing"` + ClientToken string `json:"-"` +} + +type PrivateIP struct { + PublicIpAddress string `json:"publicIpAddress"` + Primary bool `json:"primary"` + PrivateIpAddress string `json:"privateIpAddress"` + Ipv6Address string `json:"ipv6Address"` + SubnetId string `json:"subnetId"` +} + +type GetInstanceEniResult struct { + Id string `json:"eniId"` + Name string `json:"name"` + ZoneName string `json:"zoneName"` + Description string `json:"description"` + InstanceId string `json:"instanceId"` + MacAddress string `json:"macAddress"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Status string `json:"status"` + PrivateIpSet []PrivateIP `json:"privateIpSet"` +} + +type CreateInstanceStockArgs struct { + FlavorId string `json:"flavorId"` + ZoneName string `json:"zoneName,omitempty"` +} + +type InstanceStockResult struct { + FlaovrId string `json:"flavorId"` + Count int `json:"Count"` +} + +type GetSimpleFlavorArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type SimpleFlavorResult struct { + SimpleFlavorModel []SimpleFlavorModel `json:"flavorInfo"` +} + +type SimpleFlavorModel struct { + GpuCard string `json:"gpuCard"` + DiskDescription string `json:"diskDescription"` + InstanceId string `json:"instanceId"` + MemDescription string `json:"memDescription"` + NicDescription string `json:"nicDescription"` + RamType string `json:"ramType"` + RamRate string `json:"ramRate"` + CpuDescription string `json:"cpuDescription"` + RaidDescription string `json:"raidDescription"` +} + +type InstancePirceArgs struct { + FlaovrId string `json:"flavorId"` + PurchaseCount int `json:"purchaseCount"` + Billing Billing `json:"billing"` +} + +type InstancePirceResult struct { + Pirce string `json:"price"` +} + +type ListRepairTaskArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"MaxKeys"` + ErrResult string `json:"errResult"` + InstanceId string `json:"instanceId"` +} + +type RepairTask struct { + TaskId string `json:"taskId"` + InstanceId string `json:"instanceId"` + ErrResult string `json:"errResult"` + Status string `json:"status"` +} + +type ListRepairTaskResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RepairTasks []RepairTask `json:"RepairTask"` +} + +type ListClosedRepairTaskArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"MaxKeys"` + ErrResult string `json:"errResult"` + InstanceId string `json:"instanceId"` + TaskId string `json:"taskId"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` +} + +type ClosedRepairTask struct { + TaskId string `json:"taskId"` + InstanceId string `json:"instanceId"` + ErrResult string `json:"errResult"` + CreateTime string `json:"createTime"` + EndTime string `json:"endTime"` +} + +type ListClosedRepairTaskResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RepairTasks []ClosedRepairTask `json:"RepairTask"` +} + +type GetRepairTaskResult struct { + TaskId string `json:"taskId"` + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + ErrResult string `json:"errResult"` + Status string `json:"status"` + ServerStatus string `json:"serverStatus"` + Region string `json:"region"` + InternalIp string `json:"internalIp"` + FloatingIp string `json:"floatingIp"` +} + +type TaskIdArgs struct { + TaskId string `json:"taskId"` + RetainDataDisk int `json:"retainDataDisk,omitempty"` +} + +type DisconfirmTaskArgs struct { + TaskId string `json:"taskId"` + NewErrResult string `json:"newErrResult"` +} + +type RepairRecord struct { + Name string `json:"name"` + Operator string `json:"operator"` + OperateTime string `json:"operateTime"` +} + +type GetRepairRecords struct { + RepairRecords []RepairRecord `json:"RepairRecord"` +} + +type ListRuleArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + RuleName string `json:"ruleName"` + RuleId string `json:"ruleId"` +} + +type ListRuleResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RuleList []Rule `json:"RuleList"` +} + +type Rule struct { + RuleId string `json:"ruleId"` + RuleName string `json:"ruleName"` + TagCount int `json:"tagCount"` + AssociateBbcNum int `json:"associateBbcNum"` + ErrorBbcNum int `json:"errorBbcNum"` + ErrResult string `json:"errResult"` + Limit int `json:"limit"` + Status string `json:"status"` + AssociateBbcList []string `json:"associateBbcList"` + Tags []model.TagModel `json:"tags"` +} + +type CreateRuleArgs struct { + RuleName string `json:"ruleName"` + Limit int `json:"limit"` + Enabled int `json:"enabled"` + TagStr string `json:"tagStr"` + Extra string `json:"extra"` +} + +type CreateRuleResult struct { + RuleId string `json:"ruleId"` +} + +type DeleteRuleArgs struct { + RuleId string `json:"ruleId"` +} + +type DisableRuleArgs struct { + RuleId string `json:"ruleId"` +} + +type EnableRuleArgs struct { + RuleId string `json:"ruleId"` +} + +type DeploySetResult struct { + Strategy string `json:"strategy"` + Name string `json:"name"` + Desc string `json:"desc"` + DeploySetId string `json:"deploySetId"` + InstanceList []AzIntstanceStatisDetail `json:"azIntstanceStatisList"` + Concurrency int `json:"concurrency"` +} + +type AzIntstanceStatisDetail struct { + ZoneName string `json:"zoneName"` + Count int `json:"instanceCount"` + BccCount int `json:"bccInstanceCnt"` + BbcCount int `json:"bbcInstanceCnt"` + Total int `json:"instanceTotal"` + InstanceIds []string `json:"instanceIds"` + BccInstanceIds []string `json:"bccInstanceIds"` + BbcInstanceIds []string `json:"bbcInstanceIds"` +} + +type BbcCreateAutoRenewArgs struct { + InstanceId string `json:"instanceId"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` +} + +type BbcDeleteAutoRenewArgs struct { + InstanceId string `json:"instanceId"` +} + +type DeleteInstanceIngorePaymentArgs struct { + InstanceId string `json:"instanceId"` + RelatedReleaseFlag bool `json:"relatedReleaseFlag"` + DeleteCdsSnapshotFlag bool `json:"deleteCdsSnapshotFlag"` + DeleteRelatedEnisFlag bool `json:"deleteRelatedEnisFlag"` + DeleteImmediate bool `json:"deleteImmediate"` +} + +type DeleteInstanceModel struct { + InstanceId string `json:"instanceId"` + Eip string `json:"eip"` +} + +type DeleteInstanceResult struct { + SuccessResources *DeleteInstanceModel `json:"successResources"` + FailResources *DeleteInstanceModel `json:"failResources"` +} + +type SharedUser struct { + AccountId string `json:"accountId,omitempty"` + Account string `json:"account,omitempty"` +} + +type GetImageSharedUserResult struct { + Users []SharedUser `json:"users"` +} + +type RemoteCopyImageModel struct { + Region string `json:"region"` + ImageId string `json:"imageId"` + ErrMsg string `json:"errMsg"` + Code string `json:"code"` +} + +type RemoteCopyImageArgs struct { + Name string `json:"name,omitempty"` + DestRegion []string `json:"destRegion"` +} + +type RemoteCopyImageResult struct { + RemoteCopyImages []RemoteCopyImageModel `json:"result"` +} + +type ListCDSVolumeArgs struct { + MaxKeys int + InstanceId string + ZoneName string + Marker string +} + +type ListCDSVolumeResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Volumes []VolumeModel `json:"volumes"` +} + +type VolumeModel struct { + Type VolumeType `json:"type"` + StorageType StorageType `json:"storageType"` + Id string `json:"id"` + Name string `json:"name"` + DiskSizeInGB int `json:"diskSizeInGB"` + PaymentTiming string `json:"paymentTiming"` + ExpireTime string `json:"expireTime"` + Status VolumeStatus `json:"status"` + Desc string `json:"desc"` + Attachments []VolumeAttachmentModel `json:"attachments"` + ZoneName string `json:"zoneName"` + AutoSnapshotPolicy *AutoSnapshotPolicyModel `json:"autoSnapshotPolicy"` + CreateTime string `json:"createTime"` + IsSystemVolume bool `json:"isSystemVolume"` + RegionId string `json:"regionId"` + SourceSnapshotId string `json:"sourceSnapshotId"` + SnapshotNum string `json:"snapshotNum"` + Tags []model.TagModel `json:"tags"` + Encrypted bool `json:"encrypted"` +} + +type VolumeAttachmentModel struct { + VolumeId string `json:"volumeId"` + InstanceId string `json:"instanceId"` + Device string `json:"device"` + Serial string `json:"serial"` +} + +type AutoSnapshotPolicyModel struct { + CreatedTime string `json:"createdTime"` + Id string `json:"id"` + Status string `json:"status"` + RetentionDays int `json:"retentionDays"` + UpdatedTime string `json:"updatedTime"` + DeletedTime string `json:"deletedTime"` + LastExecuteTime string `json:"lastExecuteTime"` + VolumeCount int `json:"volumeCount"` + Name string `json:"name"` + TimePoints []int `json:"timePoints"` + RepeatWeekdays []int `json:"repeatWeekdays"` +} + +type DeleteInstanceArgs struct { + BbcRecycleFlag bool `json:"bbcRecycleFlag"` + InstanceIds []string `json:"instanceIds"` +} + +type GetBbcStockArgs struct { + Flavor string `json:"flavor"` + DeploySetIds []string `json:"deploySetIds"` +} + +type GetBbcStocksResult struct { + BbcStocks []BbcStock `json:"bbcStocks"` +} + +type BbcStock struct { + FlavorId string `json:"flavorId"` + InventoryQuantity int `json:"inventoryQuantity"` + UpdatedTime string `json:"updatedTime"` + CollectionTime string `json:"collectionTime"` + ZoneName string `json:"logicalZone"` +} + +type ListInstanceByInstanceIdArgs struct { + InstanceIds []string `json:"instanceIdList"` +} diff --git a/bce-sdk-go/services/bbc/operationLog.go b/bce-sdk-go/services/bbc/operationLog.go new file mode 100644 index 0000000..c89250c --- /dev/null +++ b/bce-sdk-go/services/bbc/operationLog.go @@ -0,0 +1,75 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// operationLog.go - the operationLog APIs definition supported by the BBC service + +// Package bbc defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// GetOperationLog - get operation log +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get operation log +// +// RETURNS: +// - *GetOperationLogResult: results of getting operation log +// - error: nil if success otherwise the specific error +func GetOperationLog(cli bce.Client, args *GetOperationLogArgs) (*GetOperationLogResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getOperationLogUri()) + req.SetMethod(http.GET) + + if args.Marker != "" { + req.SetParam("marker", args.Marker) + } + + if args.MaxKeys != 0 { + req.SetParam("maxKeys", fmt.Sprintf("%d", args.MaxKeys)) + } + + if args.StartTime != "" { + req.SetParam("startTime", args.StartTime) + } + + if args.EndTime != "" { + req.SetParam("endTime", args.EndTime) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetOperationLogResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func getOperationLogUri() string { + return URI_PREFIX_V1 + REQUEST_OPERATION_LOG_URI +} diff --git a/bce-sdk-go/services/bbc/repairPlat.go b/bce-sdk-go/services/bbc/repairPlat.go new file mode 100644 index 0000000..55f028f --- /dev/null +++ b/bce-sdk-go/services/bbc/repairPlat.go @@ -0,0 +1,480 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// repairPlat.go - the repair plat APIs definition supported by the BBC service + +// Package bbc defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +func ListRepairTasks(cli bce.Client, args *ListRepairTaskArgs) (*ListRepairTaskResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRepairTaskUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.InstanceId) != 0 { + req.SetParam("instanceId", args.InstanceId) + } + if len(args.ErrResult) != 0 { + req.SetParam("errResult", args.ErrResult) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListRepairTaskResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func ListClosedRepairTasks(cli bce.Client, args *ListClosedRepairTaskArgs) (*ListClosedRepairTaskResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getClosedRepairTaskUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.InstanceId) != 0 { + req.SetParam("instanceId", args.InstanceId) + } + if len(args.TaskId) != 0 { + req.SetParam("taskId", args.TaskId) + } + if len(args.ErrResult) != 0 { + req.SetParam("errResult", args.ErrResult) + } + if args.StartTime != "" { + req.SetParam("startTime", args.StartTime) + } + if args.EndTime != "" { + req.SetParam("endTime", args.EndTime) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListClosedRepairTaskResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func GetTaskDetail(cli bce.Client, instanceId string) (*GetRepairTaskResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getTaskUriWithId(instanceId)) + req.SetMethod(http.GET) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetRepairTaskResult{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func AuthorizeRepairTask(cli bce.Client, reqBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getAuthorizeTaskUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func UnAuthorizeRepairTask(cli bce.Client, reqBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getUnAuthorizeTaskUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func ConfirmRepairTask(cli bce.Client, reqBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getConfirmTaskUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func DisConfirmRepairTask(cli bce.Client, reqBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getDisConfirmTaskUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func GetRepairTaskReocrd(cli bce.Client, reqBody *bce.Body) (*GetRepairRecords, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getTaskRecordUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetRepairRecords{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListRule - list the repair plat rules +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - *ListRuleResult: results of listing the repair plat rules +// - error: nil if success otherwise the specific error +func ListRule(cli bce.Client, reqBody *bce.Body) (*ListRuleResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getListRuleUri()) + req.SetMethod(http.GET) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListRuleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetRuleDetail - get the repair plat rule detail +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - ruleId: the specified rule id +// +// RETURNS: +// - *Rule: results of listing the repair plat rules +// - error: nil if success otherwise the specific error +func GetRuleDetail(cli bce.Client, ruleId string) (*Rule, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRuleDetailUri(ruleId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &Rule{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// CreateRule - create the repair plat rule +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - *CreateRuleResult: results of the id of the repair plat rule which is created +// - error: nil if success otherwise the specific error +func CreateRule(cli bce.Client, reqBody *bce.Body) (*CreateRuleResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCreateRuleUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateRuleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// DeleteRule - delete the repair plat rule +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteRule(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeleteRuleUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DisableRule - disable the repair plat rule +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DisableRule(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDisableRuleUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// EnableRule - enable the repair plat rule +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func EnableRule(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getEnableRuleUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func getRepairTaskUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI +} + +func getClosedRepairTaskUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_CLOSED_TASK_URI +} + +func getTaskUriWithId(id string) string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI + "/" + id +} + +func getAuthorizeTaskUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI + "/authorize" +} + +func getUnAuthorizeTaskUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI + "/unauthorize" +} + +func getConfirmTaskUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI + "/confirm" +} + +func getDisConfirmTaskUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI + "/disconfirm" +} + +func getTaskRecordUri() string { + return URI_PREFIX_V2 + REQUEST_REPAIR_TASK_URI + "/record" +} + +func getListRuleUri() string { + return URI_PREFIX_V2 + REQUEST_RULE_URI +} + +func getRuleDetailUri(ruleId string) string { + return URI_PREFIX_V2 + REQUEST_RULE_URI + "/" + ruleId +} + +func getCreateRuleUri() string { + return URI_PREFIX_V2 + REQUEST_RULE_URI + REQUEST_CREATE_URI +} + +func getDeleteRuleUri() string { + return URI_PREFIX_V2 + REQUEST_RULE_URI + REQUEST_DELETE_URI +} + +func getEnableRuleUri() string { + return URI_PREFIX_V2 + REQUEST_RULE_URI + REQUEST_ENABLE_URI +} + +func getDisableRuleUri() string { + return URI_PREFIX_V2 + REQUEST_RULE_URI + REQUEST_DISABLE_URI +} diff --git a/bce-sdk-go/services/bbc/securityGroup.go b/bce-sdk-go/services/bbc/securityGroup.go new file mode 100644 index 0000000..543d3f3 --- /dev/null +++ b/bce-sdk-go/services/bbc/securityGroup.go @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2020 Baidu, Inc. All Rights Reserved. + */ +package bbc + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// BindSecurityGroups - Bind Security Groups +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BindSecurityGroups(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBindSecurityGroupsUri()) + req.SetMethod(http.POST) + req.SetParam("bind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// UnBindSecurityGroups - UnBind Security Groups +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UnBindSecurityGroups(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getUnBindSecurityGroupsUri()) + req.SetMethod(http.POST) + req.SetParam("unbind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func getBindSecurityGroupsUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + SECURITY_GROUP_URI +} + +func getUnBindSecurityGroupsUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + SECURITY_GROUP_URI +} diff --git a/bce-sdk-go/services/bbc/tag.go b/bce-sdk-go/services/bbc/tag.go new file mode 100644 index 0000000..b83bcb7 --- /dev/null +++ b/bce-sdk-go/services/bbc/tag.go @@ -0,0 +1,89 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// tag.go - the tag APIs definition supported by the BBC service + +// Package bbc defines all APIs supported by the BBC service of BCE. +package bbc + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// bindTags - bind a bbc instance tags +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BindTags(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBindTagsUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("bind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// UnbindTags - unbind a bbc instance tags +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UnbindTags(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getUnbindTagsUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("unbind", "") + req.SetBody(reqBody) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func getBindTagsUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/" + id + "/tag" +} + +func getUnbindTagsUriWithId(id string) string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/" + id + "/tag" +} diff --git a/bce-sdk-go/services/bbc/util.go b/bce-sdk-go/services/bbc/util.go new file mode 100644 index 0000000..863870c --- /dev/null +++ b/bce-sdk-go/services/bbc/util.go @@ -0,0 +1,95 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BBC service +package bbc + +import ( + "encoding/hex" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +const ( + URI_PREFIX_V1 = bce.URI_PREFIX + "v1" + URI_PREFIX_V2 = bce.URI_PREFIX + "v2" + + REQUEST_INSTANCE_URI = "/instance" + REQUEST_INSTANCE_LABEL_URI = "/instanceByLabel" + REQUEST_BATCH_DELETE_URI = "/batchDelete" + REQUEST_RECYCLE_URI = "/recycle" + REQUEST_RECOVERY_URI = "/recovery" + REQUEST_SUBNET_URI = "/vpcSubnet" + REQUEST_VPC_URI = "/vpc" + SECURITY_GROUP_URI = "/securitygroup" + + REQUEST_IMAGE_URI = "/image" + REQUEST_BATCHADDIP_URI = "/batchAddIp" + REQUEST_BATCHADDIPCROSSSUBNET_URI = "/batchAddIpCrossSubnet" + REQUEST_BATCHDELIP_URI = "/batchDelIp" + REQUEST_BATCH_CREATE_AUTORENEW_RULES_URI = "/batchCreateAutoRenewRules" + REQUEST_BATCH_Delete_AUTORENEW_RULES_URI = "/batchDeleteAutoRenewRules" + REQUEST_BATCH_REBUILD_INSTANCE_URI = "/batchRebuild" + + REQUEST_FLAVOR_URI = "/flavor" + REQUEST_FLAVOR_RAID_URI = "/flavorRaid" + REQUEST_COMMON_IMAGE_URI = "/flavor/image" + REQUEST_CUSTOM_IMAGE_URI = "/customFlavor/image" + REQUEST_IMAGE_SHAREDUSER_URI = "/sharedUsers" + + REQUEST_FLAVOR_ZONE_URI = "/order/flavorZone" + REQUEST_FLAVORS_URI = "/order/flavor" + + REQUEST_OPERATION_LOG_URI = "/operationLog" + + REQUEST_DEPLOY_SET_URI = "/deployset" + REQUEST_INSTANCE_PORT_URI = "/vpcPort" + + REQUEST_REPAIR_TASK_URI = "/task" + REQUEST_REPAIR_CLOSED_TASK_URI = "/closedTask" + + REQUEST_RULE_URI = "/rule" + REQUEST_CREATE_URI = "/create" + REQUEST_DELETE_URI = "/delete" + REQUEST_DISABLE_URI = "/disable" + REQUEST_ENABLE_URI = "/enable" + REQUEST_VOLUME_URI = "/volume" +) + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} + +func getVolumeUri() string { + return URI_PREFIX_V1 + REQUEST_VOLUME_URI +} + +func geBbcStockWithDeploySetUri() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/getStockWithDeploySet" +} + +func getListInstancesByIdsUrl() string { + return URI_PREFIX_V1 + REQUEST_INSTANCE_URI + "/listByInstanceId" +} diff --git a/bce-sdk-go/services/bcc/api/autoSnapshotPolicy.go b/bce-sdk-go/services/bcc/api/autoSnapshotPolicy.go new file mode 100644 index 0000000..afa5a27 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/autoSnapshotPolicy.go @@ -0,0 +1,298 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// autoSnapshotPolicy.go - the autoSnapshotPolicy APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateAutoSnapshotPolicy - create an automatic snapshot policy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create automatic snapshot policy +// +// RETURNS: +// - *CreateASPResult: the ID of the automatic snapshot policy newly created +// - error: nil if success otherwise the specific error +func CreateAutoSnapshotPolicy(cli bce.Client, args *CreateASPArgs) (*CreateASPResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUri()) + req.SetMethod(http.POST) + + if args != nil && len(args.ClientToken) != 0 { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateASPResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// AttachAutoSnapshotPolicy - attach an automatic snapshot policy to specified volumes +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - aspId: the id of the automatic snapshot policy +// - args: the arguments to attach automatic snapshot policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func AttachAutoSnapshotPolicy(cli bce.Client, aspId string, args *AttachASPArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUriWithId(aspId)) + req.SetMethod(http.PUT) + + req.SetParam("attach", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DetachAutoSnapshotPolicy - detach an automatic snapshot policy for specified volumes +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - aspId: the id of the automatic snapshot policy +// - args: the arguments to detach automatic snapshot policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DetachAutoSnapshotPolicy(cli bce.Client, aspId string, args *DetachASPArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUriWithId(aspId)) + req.SetMethod(http.PUT) + + req.SetParam("detach", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteAutoSnapshotPolicy - delete an automatic snapshot policy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - aspId: the id of the automatic snapshot policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteAutoSnapshotPolicy(cli bce.Client, aspId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUriWithId(aspId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ListAutoSnapshotPolicy - list all automatic snapshot policies with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: the arguments to list automatic snapshot policies +// - : +// +// RETURNS: +// - *ListASPResult: the result of the automatic snapshot policies +// - error: nil if success otherwise the specific error +func ListAutoSnapshotPolicy(cli bce.Client, queryArgs *ListASPArgs) (*ListASPResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.AspName) != 0 { + req.SetParam("aspName", queryArgs.AspName) + } + if len(queryArgs.VolumeName) != 0 { + req.SetParam("volumeName", queryArgs.VolumeName) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListASPResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetAutoSnapshotPolicyDetail - get details of the specified automatic snapshot policy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - aspId: the id of the automatic snapshot policy +// +// RETURNS: +// - *GetASPDetailResult: the result of the given automatic snapshot policy +// - error: nil if success otherwise the specific error +func GetAutoSnapshotPolicyDetail(cli bce.Client, aspId string) (*GetASPDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUriWithId(aspId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetASPDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// UpdateAutoSnapshotPolicy - update an automatic snapshot policy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to update automatic snapshot policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateAutoSnapshotPolicy(cli bce.Client, args *UpdateASPArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getASPUri() + "/update") + req.SetMethod(http.PUT) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} diff --git a/bce-sdk-go/services/bcc/api/cds.go b/bce-sdk-go/services/bcc/api/cds.go new file mode 100644 index 0000000..95cf9f9 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/cds.go @@ -0,0 +1,900 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// cds.go - the cds APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateCDSVolume - create a specified count of cds volumes +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create cds volumes +// +// RETURNS: +// - *CreateCDSVolumeResult: the result of volume ids newly created +// - error: nil if success otherwise the specific error +func CreateCDSVolume(cli bce.Client, args *CreateCDSVolumeArgs) (*CreateCDSVolumeResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUri()) + req.SetMethod(http.POST) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateCDSVolumeResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// CreateCDSVolumeV3 - create a specified count of cds volumes +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create cds volumes +// +// RETURNS: +// - *CreateCDSVolumeResult: the result of volume ids newly created +// - error: nil if success otherwise the specific error +func CreateCDSVolumeV3(cli bce.Client, args *CreateCDSVolumeV3Args) (*CreateCDSVolumeResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeV3Uri()) + req.SetMethod(http.POST) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateCDSVolumeResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListCDSVolume - list all cds volumes with the given parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: the optional arguments to list cds volumes +// +// RETURNS: +// - *ListCDSVolumeResult: the result of cds volume list +// - error: nil if success otherwise the specific error +func ListCDSVolume(cli bce.Client, queryArgs *ListCDSVolumeArgs) (*ListCDSVolumeResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.InstanceId) != 0 { + req.SetParam("instanceId", queryArgs.InstanceId) + } + if len(queryArgs.ZoneName) != 0 { + req.SetParam("zoneName", queryArgs.ZoneName) + } + if len(queryArgs.ClusterId) != 0 { + req.SetParam("clusterId", queryArgs.ClusterId) + } + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.ChargeFilter) != 0 { + req.SetParam("chargeFilter", queryArgs.ChargeFilter) + } + if len(queryArgs.UsageFilter) != 0 { + req.SetParam("usageFilter", queryArgs.UsageFilter) + } + if len(queryArgs.Name) != 0 { + req.SetParam("name", queryArgs.Name) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListCDSVolumeResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListCDSVolumeV3 - list all cds volumes with the given parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: the optional arguments to list cds volumes +// +// RETURNS: +// - *ListCDSVolumeResultV3: the result of cds volume list +// - error: nil if success otherwise the specific error +func ListCDSVolumeV3(cli bce.Client, queryArgs *ListCDSVolumeArgs) (*ListCDSVolumeResultV3, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeV3Uri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.InstanceId) != 0 { + req.SetParam("instanceId", queryArgs.InstanceId) + } + if len(queryArgs.ZoneName) != 0 { + req.SetParam("zoneName", queryArgs.ZoneName) + } + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.ChargeFilter) != 0 { + req.SetParam("chargeFilter", queryArgs.ChargeFilter) + } + if len(queryArgs.UsageFilter) != 0 { + req.SetParam("usageFilter", queryArgs.UsageFilter) + } + if len(queryArgs.Name) != 0 { + req.SetParam("name", queryArgs.Name) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListCDSVolumeResultV3{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetCDSVolumeDetail - get details of the specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume +// +// RETURNS: +// - *GetVolumeDetailResult: the result of the specified cds volume details +// - error: nil if success otherwise the specific error +func GetCDSVolumeDetail(cli bce.Client, volumeId string) (*GetVolumeDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetVolumeDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetCDSVolumeDetail - get details of the specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume +// +// RETURNS: +// - *GetVolumeDetailResultV3: the result of the specified cds volume details +// - error: nil if success otherwise the specific error +func GetCDSVolumeDetailV3(cli bce.Client, volumeId string) (*GetVolumeDetailResultV3, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeV3UriWithId(volumeId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetVolumeDetailResultV3{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// AttachCDSVolume - attach an cds volume to a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume +// - args: the arguments of instance id +// +// RETURNS: +// - *AttachVolumeResult: the result of the attachment +// - error: nil if success otherwise the specific error +func AttachCDSVolume(cli bce.Client, volumeId string, args *AttachVolumeArgs) (*AttachVolumeResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + req.SetParam("attach", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &AttachVolumeResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// DetachCDSVolume - detach an cds volume for a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume +// - args: the arguments of instance id detached from +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DetachCDSVolume(cli bce.Client, volumeId string, args *DetachVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + req.SetParam("detach", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteCDSVolume - delete a specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume to be deleted +// - : +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteCDSVolume(cli bce.Client, volumeId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteCDSVolumeNew - delete a specified cds volume, the difference from the above api is that \ +// can control whether to delete the snapshot associated with the volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume to be deleted +// - args: the arguments to delete cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteCDSVolumeNew(cli bce.Client, volumeId string, args *DeleteCDSVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ResizeCDSVolume - resize a specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume to be resized +// - args: the arguments to resize cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ResizeCDSVolume(cli bce.Client, volumeId string, args *ResizeCSDVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + req.SetParam("resize", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RollbackCDSVolume - roll back a specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the cds volume to be rolled back +// - args: the arguments to roll back the cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RollbackCDSVolume(cli bce.Client, volumeId string, args *RollbackCSDVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + req.SetParam("rollback", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// PurchaseReservedCDSVolume - renew a specified volume to extend expiration time. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the volume to be renewed +// - args: the arguments to renew cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PurchaseReservedCDSVolume(cli bce.Client, volumeId string, args *PurchaseReservedCSDVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + req.SetParam("purchaseReserved", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RenameCDSVolume - rename a specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the volume to be renamed +// - args: the arguments to rename volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RenameCDSVolume(cli bce.Client, volumeId string, args *RenameCSDVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + req.SetParam("rename", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyCDSVolume - modify attributes of the specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the volume to be modified +// - args: arguments to modify volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyCDSVolume(cli bce.Client, volumeId string, args *ModifyCSDVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + req.SetParam("modify", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyChargeTypeCDSVolume - modify the volume billing method, only support Postpaid to Prepaid and Prepaid to Postpaid +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - volumeId: id of the volume to be modified +// - args: the arguments to modify volume billing method +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyChargeTypeCDSVolume(cli bce.Client, volumeId string, args *ModifyChargeTypeCSDVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeUriWithId(volumeId)) + req.SetMethod(http.PUT) + + req.SetParam("modifyChargeType", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// AutoRenewCDSVolume - auto renew the specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to auto renew the cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func AutoRenewCDSVolume(cli bce.Client, args *AutoRenewCDSVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getAutoRenewVolumeUri()) + req.SetMethod(http.POST) + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + + return nil +} + +// CancelAutoRenewCDSVolume - cancel auto renew the specified cds volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to cancel auto renew the cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CancelAutoRenewCDSVolume(cli bce.Client, args *CancelAutoRenewCDSVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCancelAutoRenewVolumeUri()) + req.SetMethod(http.POST) + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + + return nil +} + +// GetAvailableDiskInfo - get available diskInfos of the specified zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: the zone name eg:cn-bj-a +// +// RETURNS: +// - *GetAvailableDiskInfoResult: the result of the specified zone diskInfos +// - error: nil if success otherwise the specific error +func GetAvailableDiskInfo(cli bce.Client, zoneName string) (*GetAvailableDiskInfoResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getAvailableDiskInfo()) + req.SetMethod(http.GET) + req.SetParam("zoneName", zoneName) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetAvailableDiskInfoResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// DeletePrepayVolume - delete the volumes for prepay +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments of method +// +// RETURNS: +// - *VolumeDeleteResultResponse: the result of deleting volumes +// - error: nil if success otherwise the specific error +func DeletePrepayVolume(cli bce.Client, args *VolumePrepayDeleteRequestArgs) (*VolumeDeleteResultResponse, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeletePrepayVolumeUri()) + req.SetMethod(http.POST) + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &VolumeDeleteResultResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func TagVolume(cli bce.Client, volumeId string, args *TagVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getTagVolumeUri(volumeId)) + req.SetMethod(http.PUT) + req.SetParam("bind", "") + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func UntagVolume(cli bce.Client, volumeId string, args *TagVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getUntagVolumeUri(volumeId)) + req.SetMethod(http.PUT) + req.SetParam("unbind", "") + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/bcc/api/deploySet.go b/bce-sdk-go/services/bcc/api/deploySet.go new file mode 100644 index 0000000..92974b6 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/deploySet.go @@ -0,0 +1,264 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// deploySet.go - the deploy set APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// - reqBody: http request body +// +// RETURNS: +// - *CreateDeploySetResult: results of creating a deploy set +// - error: nil if success otherwise the specific error +func CreateDeploySet(cli bce.Client, clientToken string, reqBody *bce.Body) (*CreateDeploySetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetCreateUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateDeploySetResp{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + if jsonBody != nil && len(jsonBody.DeploySetIds) > 0 { + jsonResp := &CreateDeploySetResult{ + DeploySetId: jsonBody.DeploySetIds[0], + } + return jsonResp, nil + } + return nil, nil +} + +// ListDeploySets - list all deploy sets +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// +// RETURNS: +// - *ListDeploySetsResult: the result of list all deploy sets +// - error: nil if success otherwise the specific error +func ListDeploySets(cli bce.Client) (*ListDeploySetsResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetListUri()) + req.SetMethod(http.GET) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListDeploySetsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ModifyDeploySet - modify the deploy set atrribute +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyDeploySet(cli bce.Client, deploySetId string, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(deploySetId)) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + req.SetParam("modifyAttribute", "") + + // Send request and get response + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteDeploySet(cli bce.Client, deploySetId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(deploySetId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + + return nil +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *GetDeploySetResult: the detail of the deploy set +// - error: nil if success otherwise the specific error +func GetDeploySet(cli bce.Client, deploySetId string) (*DeploySetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUrl(deploySetId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeploySetResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func UpdateInstanceDeploy(cli bce.Client, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getUpdateInstanceDeployUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func DelInstanceDeploy(cli bce.Client, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDelInstanceDeployUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func getDeploySetCreateUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_DEPLOYSET_URI + REQUEST_CREATE_URI +} + +func getDeploySetListUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_DEPLOYSET_URI + REQUEST_LIST_URI +} + +func getDeploySetUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_DEPLOYSET_URI + "/" + id +} + +func getDeploySetUrl(id string) string { + return URI_PREFIXV2 + REQUEST_DEPLOYSET_URI + "/" + id +} + +func getUpdateInstanceDeployUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_DEPLOYSET_URI + REQUEST_UPDATE_URI +} + +func getDelInstanceDeployUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_DEPLOYSET_URI + REQUEST_DEL_URI +} diff --git a/bce-sdk-go/services/bcc/api/image.go b/bce-sdk-go/services/bcc/api/image.go new file mode 100644 index 0000000..1560bd4 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/image.go @@ -0,0 +1,557 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// image.go - the image APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "errors" + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" + "strings" +) + +// CreateImage - create an image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create image +// +// RETURNS: +// - *CreateImageResult: the result of the image newly created +// - error: nil if success otherwise the specific error +func CreateImage(cli bce.Client, args *CreateImageArgs) (*CreateImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUri()) + req.SetMethod(http.POST) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListImage - list all images with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: the arguments to list images +// +// RETURNS: +// - *ListImageResult: result of the image list +// - error: nil if success otherwise the specific error +func ListImage(cli bce.Client, queryArgs *ListImageArgs) (*ListImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.ImageName) != 0 { + if len(queryArgs.ImageType) != 0 && strings.EqualFold("custom", queryArgs.ImageType) { + req.SetParam("imageName", queryArgs.ImageName) + } else { + return nil, errors.New("only the custom image type could filter by name") + } + } + if len(queryArgs.ImageType) != 0 { + req.SetParam("imageType", queryArgs.ImageType) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetImageDetail - get details of the specified image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image +// +// RETURNS: +// - *GetImageDetailResult: result of image details +// - error: nil if success otherwise the specific error +func GetImageDetail(cli bce.Client, imageId string) (*GetImageDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImageDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// DeleteImage - delete a specified image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of image to be deleted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteImage(cli bce.Client, imageId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RemoteCopyImage - copy custom images across regions, only custom images supported, the system \ +// and service integration images cannot be copied. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be copied +// - args: the arguments to copy image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RemoteCopyImage(cli bce.Client, imageId string, args *RemoteCopyImageArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("remoteCopy", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RemoteCopyImageReturnImageIds - copy custom images across regions, only custom images supported, the system \ +// and service integration images cannot be copied. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be copied +// - args: the arguments to copy image +// +// RETURNS: +// - imageIds of destination region if success otherwise the specific error +func RemoteCopyImageReturnImageIds(cli bce.Client, imageId string, args *RemoteCopyImageArgs) (*RemoteCopyImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("remoteCopy", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &RemoteCopyImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// CancelRemoteCopyImage - cancel the image copy across regions +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CancelRemoteCopyImage(cli bce.Client, imageId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("cancelRemoteCopy", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ShareImage - share a specified custom image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be shared +// - args: the arguments to share image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ShareImage(cli bce.Client, imageId string, args *SharedUser) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("share", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// UnShareImage - unshare a specified image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image to be unshared +// - args: the arguments to unshare image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UnShareImage(cli bce.Client, imageId string, args *SharedUser) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageUriWithId(imageId)) + req.SetMethod(http.POST) + + req.SetParam("unshare", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// GetImageSharedUser - get the list of users that the image has been shared with +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - imageId: id of the image +// +// RETURNS: +// - *GetImageSharedUserResult: result of the shared users +// - error: nil if success otherwise the specific error +func GetImageSharedUser(cli bce.Client, imageId string) (*GetImageSharedUserResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageSharedUserUri(imageId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImageSharedUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetImageOS - get the operating system information of the instance in batches according to the instance ids +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments of instance ids +// +// RETURNS: +// - *GetImageOsResult: result of the operating system information +// - error: nil if success otherwise the specific error +func GetImageOS(cli bce.Client, args *GetImageOsArgs) (*GetImageOsResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageOsUri()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetImageOsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func BindImageToTags(cli bce.Client, imageId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageToTagsUri(imageId)) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + req.SetParam("bind", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func UnBindImageToTags(cli bce.Client, imageId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImageToTagsUri(imageId)) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + req.SetParam("unbind", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func ImportCustomImage(cli bce.Client, args *ImportCustomImageArgs) (*ImportCustomImageResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getImportCustomImageUri()) + req.SetMethod(http.POST) + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ImportCustomImageResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetAvailableImagesBySpec(cli bce.Client, args *GetAvailableImagesBySpecArg) (*GetAvailableImagesBySpecResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getAvailableImagesBySpecUri()) + req.SetMethod(http.GET) + + if len(args.Spec) > 0 { + req.SetParam("spec", args.Spec) + } + if len(args.OsName) > 0 { + req.SetParam("osName", args.OsName) + } + if len(args.Marker) > 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys > 0 { + req.SetParam("maxKeys", fmt.Sprint(args.MaxKeys)) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetAvailableImagesBySpecResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/bcc/api/instance.go b/bce-sdk-go/services/bcc/api/instance.go new file mode 100644 index 0000000..a3e33bb --- /dev/null +++ b/bce-sdk-go/services/bcc/api/instance.go @@ -0,0 +1,2238 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// instance.go - the instance APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateInstance - create an instance with specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to create instance +// +// RETURNS: +// - *CreateInstanceResult: result of the instance ids newly created +// - error: nil if success otherwise the specific error +func CreateInstance(cli bce.Client, args *CreateInstanceArgs, reqBody *bce.Body) (*CreateInstanceResult, + error) { + // Build the request + clientToken := args.ClientToken + requestToken := args.RequestToken + req := &bce.BceRequest{} + req.SetUri(getInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetHeader("x-request-token", requestToken) + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// CreateInstance - create an instance with specified parameters and support the passing in of label +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to create instance +// +// RETURNS: +// - *CreateInstanceResult: result of the instance ids newly created +// - error: nil if success otherwise the specific error +func CreateInstanceByLabel(cli bce.Client, args *CreateSpecialInstanceBySpecArgs, reqBody *bce.Body) (*CreateInstanceResult, + error) { + // Build the request + clientToken := args.ClientToken + requestToken := args.RequestToken + req := &bce.BceRequest{} + req.SetUri(getInstanceByLabelUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetHeader("x-request-token", requestToken) + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// CreateInstanceBySpec - create an instance with specified spec. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to create instance +// +// RETURNS: +// - *CreateInstanceBySpecResult: result of the instance ids newly created +// - error: nil if success otherwise the specific error +func CreateInstanceBySpec(cli bce.Client, args *CreateInstanceBySpecArgs, reqBody *bce.Body) ( + *CreateInstanceBySpecResult, error) { + // Build the request + clientToken := args.ClientToken + requestToken := args.RequestToken + req := &bce.BceRequest{} + req.SetUri(getInstanceBySpecUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetHeader("x-request-token", requestToken) + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceBySpecResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// CreateInstanceV3 - create an instance with specified spec. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to create instance +// +// RETURNS: +// - *CreateInstanceV3Result: result of the instance ids newly created +// - error: nil if success otherwise the specific error +func CreateInstanceV3(cli bce.Client, args *CreateInstanceV3Args, reqBody *bce.Body) ( + *CreateInstanceV3Result, error) { + // Build the request + clientToken := args.ClientToken + requestToken := args.RequestToken + req := &bce.BceRequest{} + req.SetUri(getInstanceUriV3()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetHeader("x-request-token", requestToken) + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceV3Result{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListInstances - list all instances with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list instances +// +// RETURNS: +// - *ListInstanceResult: result of the instance list +// - error: nil if success otherwise the specific error +func ListInstances(cli bce.Client, args *ListInstanceArgs) (*ListInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.DedicatedHostId) != 0 { + req.SetParam("dedicateHostId", args.DedicatedHostId) + } + if len(args.InternalIp) != 0 { + req.SetParam("internalIp", args.InternalIp) + } + if len(args.ZoneName) != 0 { + req.SetParam("zoneName", args.ZoneName) + } + if len(args.KeypairId) != 0 { + req.SetParam("keypairId", args.KeypairId) + } + if args.AutoRenew { + req.SetParam("autoRenew", fmt.Sprint(args.AutoRenew)) + } + if len(args.InstanceIds) != 0 { + req.SetParam("instanceIds", args.InstanceIds) + } + if len(args.InstanceNames) != 0 { + req.SetParam("instanceNames", args.InstanceNames) + } + if len(args.CdsIds) != 0 { + req.SetParam("cdsIds", args.CdsIds) + } + if len(args.DeploySetIds) != 0 { + req.SetParam("deploySetIds", args.DeploySetIds) + } + if len(args.SecurityGroupIds) != 0 { + req.SetParam("securityGroupIds", args.SecurityGroupIds) + } + if len(args.PaymentTiming) != 0 { + req.SetParam("paymentTiming", args.PaymentTiming) + } + if len(args.Status) != 0 { + req.SetParam("status", args.Status) + } + if len(args.Tags) != 0 { + req.SetParam("tags", args.Tags) + } + if len(args.PrivateIps) != 0 { + req.SetParam("privateIps", args.PrivateIps) + } + if len(args.VpcId) != 0 { + req.SetParam("vpcId", args.VpcId) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListRecycleInstances - list all instances in the recycle bin with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list instances in the recycle bin +// +// RETURNS: +// - *ListRecycleInstanceResult: result of the instance in the recycle bin list +// - error: nil if success otherwise the specific error +func ListRecycleInstances(cli bce.Client, args *ListRecycleInstanceArgs) (*ListRecycleInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRecycleInstanceListUri()) + req.SetMethod(http.POST) + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListRecycleInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// listServersByMarkerV3 - list all instances with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list instances +// +// RETURNS: +// - *LogicMarkerResultResponseV3: result of the instance +// - error: nil if success otherwise the specific error +func ListServersByMarkerV3(cli bce.Client, args *ListServerRequestV3Args) (*LogicMarkerResultResponseV3, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getServersByMarkerV3Uri()) + req.SetMethod(http.POST) + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &LogicMarkerResultResponseV3{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetInstanceDetail - get details of the specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetInstanceDetailResult: result of the instance details +// - error: nil if success otherwise the specific error +func GetInstanceDetail(cli bce.Client, instanceId string) (*GetInstanceDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.GET) + req.SetParam("isDeploySet", "false") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetInstanceDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func GetInstanceDetailWithDeploySet(cli bce.Client, instanceId string, isDeploySet bool) (*GetInstanceDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.GET) + if isDeploySet == true { + req.SetParam("isDeploySet", "true") + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetInstanceDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func GetInstanceDetailWithDeploySetAndFailed(cli bce.Client, instanceId string, + isDeploySet bool, containsFailed bool) (*GetInstanceDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.GET) + if isDeploySet == true { + req.SetParam("isDeploySet", "true") + } + if containsFailed == true { + req.SetParam("containsFailed", "true") + } else { + req.SetParam("containsFailed", "false") + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetInstanceDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// DeleteInstance - delete a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteInstance(cli bce.Client, instanceId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteInstance - delete a specified instance,contains prepay or postpay instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// RETURNS: +// - error: nil if success otherwise the specific error + +func DeleteInstanceIngorePayment(cli bce.Client, args *DeleteInstanceIngorePaymentArgs) (*DeleteInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeleteInstanceDeleteIngorePaymentUri()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeleteInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// DeleteRecycledInstance - delete a recycled bcc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteRecycledInstance(cli bce.Client, instanceId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeleteRecycledInstanceUri(instanceId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// AutoReleaseInstance - set releaseTime of a postpay instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the specific instance ID +// - args: the arguments to auto release instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func AutoReleaseInstance(cli bce.Client, instanceId string, args *AutoReleaseArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("autorelease", "") + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ResizeInstance - resize a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be resized +// - reqBody: the request body to resize instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ResizeInstance(cli bce.Client, instanceId, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("resize", "") + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RebuildInstance - rebuild a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebuilded +// - reqBody: the request body to rebuild instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RebuildInstance(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("rebuild", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// StartInstance - start a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be started +// +// RETURNS: +// - error: nil if success otherwise the specific error +func StartInstance(cli bce.Client, instanceId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("start", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// StopInstance - stop a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be stoped +// - reqBody: the request body to stop instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func StopInstance(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("stop", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RebootInstance - reboot a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebooted +// - reqBody: the request body to reboot instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RebootInstance(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("reboot", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func RecoveryInstance(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRecoveryInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ChangeInstancePass - change password of specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - reqBody: the request body to change paasword of instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ChangeInstancePass(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("changePass", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyDeletionProtection - Modify deletion protection of specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - reqBody: the request body to set an instance, default 0 for deletable and 1 for deletion protection +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyDeletionProtection(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceDeletionProtectionUri(instanceId)) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyInstanceAttribute - modify attribute of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be modified +// - reqBody: the request body to modify instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyInstanceAttribute(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("modifyAttribute", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyInstanceDesc - modify desc of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be modified +// - reqBody: the request body to modify instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyInstanceDesc(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("modifyDesc", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ModifyInstanceHostname - modify hostname of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be modified +// - reqBody: the request body to modify instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ModifyInstanceHostname(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("changeHostname", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BindSecurityGroup - bind security group for a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - reqBody: the request body to bind security group associate to the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BindSecurityGroup(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("bind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// UnBindSecurityGroup - unbind security group for a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - reqBody: the request body to unbind security group associate to the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UnBindSecurityGroup(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("unbind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// GetInstanceVNC - get VNC address of the specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetInstanceVNCResult: result of the VNC address of the instance +// - error: nil if success otherwise the specific error +func GetInstanceVNC(cli bce.Client, instanceId string) (*GetInstanceVNCResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceVNCUri(instanceId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetInstanceVNCResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// InstancePurchaseReserved - renew a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be renewed +// - reqBody: the request body to renew instance +// +// RETURNS: +// - *api.InstancePurchaseReservedResult: the result of renew a specified instance +// - error: nil if success otherwise the specific error +func InstancePurchaseReserved(cli bce.Client, instanceId, relatedRenewFlag, clientToken string, reqBody *bce.Body) (*InstancePurchaseReservedResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("purchaseReserved", "") + req.SetParam("relatedRenewFlag", relatedRenewFlag) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstancePurchaseReservedResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// DeleteInstanceWithRelatedResource - delete an instance with related resources +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// - reqBody: request body to delete instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteInstanceWithRelatedResource(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceUriWithId(instanceId)) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// InstanceChangeSubnet - change the subnet to which the instance belongs +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to change subnet of instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func InstanceChangeSubnet(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getChangeSubnetUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// InstanceChangeVpc - change the vpc to which the instance belongs +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to change vpc of instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func InstanceChangeVpc(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getChangeVpcUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchAddIp - Add ips to instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchAddIp(cli bce.Client, args *BatchAddIpArgs, reqBody *bce.Body) (*BatchAddIpResponse, error) { + // Build the request + clientToken := args.ClientToken + req := &bce.BceRequest{} + req.SetUri(getBatchAddIpUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BatchAddIpResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// BatchDelIp - Delete ips of instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchDelIp(cli bce.Client, args *BatchDelIpArgs, reqBody *bce.Body) error { + // Build the request + clientToken := args.ClientToken + req := &bce.BceRequest{} + req.SetUri(getBatchDelIpUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ResizeInstanceBySpec - resize a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be resized +// - reqBody: the request body to resize instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ResizeInstanceBySpec(cli bce.Client, instanceId, clientToken string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getResizeInstanceBySpec(instanceId)) + req.SetMethod(http.PUT) + req.SetParam("resize", "") + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchRebuildInstances - batch rebuild instances +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to rebuild instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchRebuildInstances(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRebuildBatchInstanceUri()) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ChangeToPrepaid - to prepaid +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to ChangeToPrepaid +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ChangeToPrepaid(cli bce.Client, instanceId string, reqBody *bce.Body) (*ChangeToPrepaidResponse, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getChangeToPrepaidUri(instanceId)) + req.SetMethod(http.POST) + req.SetBody(reqBody) + req.SetParam("toPrepay", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ChangeToPrepaidResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// bindInstanceToTags - bind instance to tags +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to bindInstanceToTags +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BindInstanceToTags(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getbindInstanceToTagsUri(instanceId)) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + req.SetParam("bind", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// UnBindInstanceToTags - unbind instance to tags +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to unbindInstanceToTags +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UnBindInstanceToTags(cli bce.Client, instanceId string, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getbindInstanceToTagsUri(instanceId)) + req.SetMethod(http.PUT) + req.SetBody(reqBody) + req.SetParam("unbind", "") + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// GetInstanceNoChargeList - get instance with nocharge list +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list instances +// +// RETURNS: +// - *ListInstanceResult: result of the instance list +// - error: nil if success otherwise the specific error +func GetInstanceNoChargeList(cli bce.Client, args *ListInstanceArgs) (*ListInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(GetInstanceNoChargeListUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.InternalIp) != 0 { + req.SetParam("internalIp", args.InternalIp) + } + if len(args.ZoneName) != 0 { + req.SetParam("zoneName", args.ZoneName) + } + if len(args.KeypairId) != 0 { + req.SetParam("keypairId", args.KeypairId) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// createBidInstance - create an instance with specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to create instance +// +// RETURNS: +// - *CreateInstanceResult: result of the instance ids newly created +// - error: nil if success otherwise the specific error +func CreateBidInstance(cli bce.Client, clientToken string, reqBody *bce.Body) (*CreateInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(GetCreateBidInstanceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// CancelBidOrder - Cancel the bidding instance order. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to cancel bid order +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CancelBidOrder(cli bce.Client, clientToken string, reqBody *bce.Body) (*CreateBidInstanceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(GetCancelBidOrderUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateBidInstanceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetBidInstancePrice - get the market price of the specified bidding instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - *GetBidInstancePriceResult: result of the market price of the specified bidding instance +// - error: nil if success otherwise the specific error +func GetBidInstancePrice(cli bce.Client, clientToken string, reqBody *bce.Body) (*GetBidInstancePriceResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBidInstancePriceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + if clientToken != "" { + req.SetParam("clientToken", clientToken) + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetBidInstancePriceResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListBidFlavor - list all flavors of the bidding instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListBidFlavorResult: result of the flavor list +// - error: nil if success otherwise the specific error +func ListBidFlavor(cli bce.Client) (*ListBidFlavorResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(listBidFlavorUri()) + req.SetMethod(http.POST) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListBidFlavorResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetInstanceResizeStock(cli bce.Client, args *ResizeInstanceStockArgs) (*InstanceStockResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getResizeInstanceStock()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstanceStockResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetAllStocks - get the bcc and bbc's stock +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *GetAllStocksResult: the result of the bcc and bbc's stock +// - error: nil if success otherwise the specific error +func GetAllStocks(cli bce.Client) (*GetAllStocksResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getAllStocks()) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetAllStocksResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetStockWithDeploySet - get the bcc's stock with deploySet +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get the bcc's stock with deploySet +// +// RETURNS: +// - *GetStockWithDeploySetResults: the result of the bcc's stock +// - error: nil if success otherwise the specific error +func GetStockWithDeploySet(cli bce.Client, args *GetStockWithDeploySetArgs) (*GetStockWithDeploySetResults, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getStockWithDeploySet()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetStockWithDeploySetResults{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetStockWithSpec - get the bcc's stock with spec +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get the bcc's stock with spec +// +// RETURNS: +// - *GetStockWithSpecResults: the result of the bcc's stock +// - error: nil if success otherwise the specific error +func GetStockWithSpec(cli bce.Client, args *GetStockWithSpecArgs) (*GetStockWithSpecResults, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getStockWithSpec()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetStockWithSpecResults{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetInstanceCreateStock(cli bce.Client, args *CreateInstanceStockArgs) (*InstanceStockResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getCreateInstanceStock()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &InstanceStockResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// BatchCreateAutoRenewRules - Batch Create AutoRenew Rules +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchCreateAutoRenewRules(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchCreateAutoRenewRulesUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + //print(resp) + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchDeleteAutoRenewRules - Batch Delete AutoRenew Rules +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchDeleteAutoRenewRules(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchDeleteAutoRenewRulesUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + //print(resp) + + defer func() { resp.Body().Close() }() + return nil +} + +// ListInstanceByInstanceIds - list instance by instanceId +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListInstancesResult: result of the instance list +// - error: nil if success otherwise the specific error +func ListInstanceByInstanceIds(cli bce.Client, args *ListInstanceByInstanceIdArgs) (*ListInstancesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getListInstancesByIdsUrl()) + req.SetMethod(http.POST) + + if args != nil { + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstancesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// BatchDeleteInstanceWithRelatedResource - delete instance with related resources +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to delete instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchDeleteInstanceWithRelatedResource(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchDeleteInstanceWithRelatedResourceUri()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// BatchStartInstance - batch start specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: request body to batch start instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchStartInstance(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchStartInstanceUri()) + req.SetMethod(http.PUT) + req.SetParam("start", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { _ = resp.Body().Close() }() + return nil +} + +// BatchStopInstance - batch stop specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to batch stop instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchStopInstance(cli bce.Client, reqBody *bce.Body) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchStopInstanceUri()) + req.SetMethod(http.PUT) + req.SetParam("stop", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// ListInstanceTypes - list all instances type with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list instances type +// +// RETURNS: +// - *ListInstanceTypeResults: result of the instance type list +// - error: nil if success otherwise the specific error +func ListInstanceTypes(cli bce.Client, args *ListInstanceTypeArgs) (*ListInstanceTypeResults, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getListInstanceTypesUri()) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.ZoneName) != 0 { + req.SetParam("zoneName", args.ZoneName) + } + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstanceTypeResults{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListIdMappings - Long and short ID conversion parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to Long and short ID conversion +// +// RETURNS: +// - *ListIdMappingResults: result of the Long short mapping +// - error: nil if success otherwise the specific error +func ListIdMappings(cli bce.Client, args *ListIdMappingArgs) (*ListIdMappingResults, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getListIdMappingsUri()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListIdMappingResults{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// BatchResizeInstance - batch resize a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to resize instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BatchResizeInstance(cli bce.Client, reqBody *bce.Body) (*BatchResizeInstanceResults, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchResizeInstanceUri()) + req.SetMethod(http.PUT) + req.SetParam("resize", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BatchResizeInstanceResults{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func GetInstanceDeleteProgress(cli bce.Client, reqBody *bce.Body) (map[string]interface{}, error) { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceDeleteProgress()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + var jsonBody map[string]interface{} + if err := resp.ParseJsonBody(&jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func ListAvailableResizeSpecs(cli bce.Client, reqBody *bce.Body) ( + *ListAvailableResizeSpecResults, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getListAvailableResizeSpecsUri()) + req.SetParam("resizeList", "") + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListAvailableResizeSpecResults{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func BatchChangeInstanceToPrepay(cli bce.Client, reqBody *bce.Body) (*BatchChangeInstanceBillingMethodResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchChangeInstanceToPrepay()) + req.SetParam("toPrepay", "") + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BatchChangeInstanceBillingMethodResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func BatchChangeInstanceToPostpay(cli bce.Client, reqBody *bce.Body) (*BatchChangeInstanceBillingMethodResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getBatchChangeInstanceToPostpay()) + req.SetParam("toPostpay", "") + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BatchChangeInstanceBillingMethodResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func ListInstanceRoles(cli bce.Client) (*ListInstanceRolesResult, error) { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(listInstanceRoles()) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListInstanceRolesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func BindInstanceRole(cli bce.Client, reqBody *bce.Body) (*BindInstanceRoleResult, error) { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(postInstanceRole()) + req.SetMethod(http.POST) + req.SetParam("bind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &BindInstanceRoleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func UnBindInstanceRole(cli bce.Client, reqBody *bce.Body) (*UnBindInstanceRoleResult, error) { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(postInstanceRole()) + req.SetMethod(http.POST) + req.SetParam("unbind", "") + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &UnBindInstanceRoleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +func DeleteIpv6(cli bce.Client, reqBody *bce.Body) error { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(deleteIpv6()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func AddIpv6(cli bce.Client, reqBody *bce.Body) (*AddIpv6Result, error) { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(addIpv6()) + req.SetMethod(http.POST) + req.SetBody(reqBody) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &AddIpv6Result{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} diff --git a/bce-sdk-go/services/bcc/api/keypair.go b/bce-sdk-go/services/bcc/api/keypair.go new file mode 100644 index 0000000..1d908c1 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/keypair.go @@ -0,0 +1,298 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// keypair.go - the keypair APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateKeypair(cli bce.Client, args *CreateKeypairArgs) (*KeypairResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairUri()) + req.SetMethod(http.POST) + //req.SetParam("create", "") + + if len(args.ClientToken) != 0 { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &KeypairResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func ImportKeypair(cli bce.Client, args *ImportKeypairArgs) (*KeypairResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairUri()) + req.SetMethod(http.PUT) + req.SetParam("import", "") + + if len(args.ClientToken) != 0 { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &KeypairResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func AttachKeypair(cli bce.Client, args *AttackKeypairArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairWithId(args.KeypairId)) + req.SetMethod(http.PUT) + req.SetParam("attach", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func DetachKeypair(cli bce.Client, args *DetachKeypairArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairWithId(args.KeypairId)) + req.SetMethod(http.PUT) + req.SetParam("detach", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func DeleteKeypair(cli bce.Client, args *DeleteKeypairArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairWithId(args.KeypairId)) + req.SetMethod(http.DELETE) + req.SetParam("delete", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func GetKeypairDetail(cli bce.Client, keypairId string) (*KeypairResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairWithId(keypairId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &KeypairResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func ListKeypairs(cli bce.Client, queryArgs *ListKeypairArgs) (*ListKeypairResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + if len(queryArgs.Name) != 0 { + req.SetParam("name", queryArgs.Name) + } + } + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListKeypairResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func RenameKeypair(cli bce.Client, args *RenameKeypairArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairWithId(args.KeypairId)) + req.SetMethod(http.PUT) + req.SetParam("rename", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func UpdateKeypairDescription(cli bce.Client, args *KeypairUpdateDescArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getKeypairWithId(args.KeypairId)) + req.SetMethod(http.PUT) + req.SetParam("updateDesc", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/bcc/api/model.go b/bce-sdk-go/services/bcc/api/model.go new file mode 100644 index 0000000..51e1e09 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/model.go @@ -0,0 +1,2278 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type InstanceStatus string + +const ( + InstanceStatusRunning InstanceStatus = "Running" + InstanceStatusStarting InstanceStatus = "Starting" + InstanceStatusStopping InstanceStatus = "Stopping" + InstanceStatusStopped InstanceStatus = "Stopped" + InstanceStatusDeleted InstanceStatus = "Deleted" + InstanceStatusScaling InstanceStatus = "Scaling" + InstanceStatusExpired InstanceStatus = "Expired" + InstanceStatusError InstanceStatus = "Error" + InstanceStatusSnapshotProcessing InstanceStatus = "SnapshotProcessing" + InstanceStatusImageProcessing InstanceStatus = "ImageProcessing" + InstanceStatusChangeVpcProcessing InstanceStatus = "ChangeVpc" + InstanceStatusRecycled InstanceStatus = "Recycled" +) + +type InstanceType string + +const ( + InstanceTypeN1 InstanceType = "N1" + InstanceTypeN2 InstanceType = "N2" + InstanceTypeN3 InstanceType = "N3" + InstanceTypeC1 InstanceType = "C1" + InstanceTypeC2 InstanceType = "C2" + InstanceTypeS1 InstanceType = "S1" + InstanceTypeG1 InstanceType = "G1" + InstanceTypeF1 InstanceType = "F1" + + // InstanceTypeN4 网络增强型 BCC 实例: 通用网络增强型g3ne、计算网络增强型c3ne、内存网络增强型m3ne + InstanceTypeN4 InstanceType = "N4" + + // InstanceTypeN5 普通型Ⅳ BCC实例: 通用型g4、密集计算型ic4、计算型c4、内存型m4 + InstanceTypeN5 InstanceType = "N5" +) + +type StorageType string + +const ( + StorageTypeStd1 StorageType = "std1" + StorageTypeHP1 StorageType = "hp1" + StorageTypeCloudHP1 StorageType = "cloud_hp1" + StorageTypeLocal StorageType = "local" + StorageTypeSATA StorageType = "sata" + StorageTypeSSD StorageType = "ssd" + StorageTypeHDDThroughput StorageType = "HDD_Throughput" + StorageTypeHdd StorageType = "hdd" + StorageTypeLocalSSD StorageType = "local-ssd" + StorageTypeLocalHDD StorageType = "local-hdd" + StorageTypeLocalNVME StorageType = "local-nvme" + StorageTypeEnhancedPl1 StorageType = "enhanced_ssd_pl1" + StorageTypeEnhancedPl2 StorageType = "enhanced_ssd_pl2" +) + +type StorageTypeV3 string + +const ( + StorageTypeV3CloudSATA StorageTypeV3 = "Cloud_Sata" + StorageTypeV3CloudHDDGeneral StorageTypeV3 = "Cloud_HDD_General" + StorageTypeV3CloudHDDThroughput StorageTypeV3 = "Cloud_HDD_Throughput" + StorageTypeV3CloudPremium StorageTypeV3 = "Cloud_Premium" + StorageTypeV3CloudSSDGeneral StorageTypeV3 = "Cloud_SSD_General" + StorageTypeV3CloudSSDEnhanced StorageTypeV3 = "Cloud_SSD_Enhanced" + StorageTypeV3LocalHDD StorageTypeV3 = "Local_HDD" + StorageTypeV3LocalSSD StorageTypeV3 = "Local_SSD" + StorageTypeV3LocalNVME StorageTypeV3 = "Local_NVME" + StorageTypeV3LocalPVHDD StorageTypeV3 = "Local_PV_HDD" + StorageTypeV3LocalPVSSD StorageTypeV3 = "Local_PV_SSD" + StorageTypeV3LocalPVNVME StorageTypeV3 = "Local_PV_NVME" + StorageTypeV3EnhancedPl2 StorageTypeV3 = "enhanced_ssd_pl2" +) + +type PaymentTimingType string + +const ( + PaymentTimingPrePaid PaymentTimingType = "Prepaid" + PaymentTimingPostPaid PaymentTimingType = "Postpaid" + + // v3 + PaymentTimingSpotPaid PaymentTimingType = "Spotpaid" + PaymentTimingBidding PaymentTimingType = "bidding" +) + +// Instance define instance model +type InstanceModel struct { + InstanceId string `json:"id"` + SerialNumber string `json:"serialNumber"` + InstanceName string `json:"name"` + Hostname string `json:"hostname"` + InstanceType InstanceType `json:"instanceType"` + Spec string `json:"spec"` + Description string `json:"desc"` + Status InstanceStatus `json:"status"` + PaymentTiming string `json:"paymentTiming"` + CreationTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + ReleaseTime string `json:"releaseTime"` + PublicIP string `json:"publicIp"` + InternalIP string `json:"internalIp"` + CpuCount int `json:"cpuCount"` + IsomerismCard string `json:"isomerismCard"` + NpuVideoMemory string `json:"npuVideoMemory"` + GpuCard string `json:"gpuCard"` + FpgaCard string `json:"fpgaCard"` + CardCount string `json:"cardCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + LocalDiskSizeInGB int `json:"localDiskSizeInGB"` + ImageId string `json:"imageId"` + NetworkCapacityInMbps int `json:"networkCapacityInMbps"` + PlacementPolicy string `json:"placementPolicy"` + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` + VpcId string `json:"vpcId"` + AutoRenew bool `json:"autoRenew"` + KeypairId string `json:"keypairId"` + KeypairName string `json:"keypairName"` + DedicatedHostId string `json:"dedicatedHostId"` + Tags []model.TagModel `json:"tags"` + Ipv6 string `json:"ipv6"` + EniQuota int `json:"eniQuota"` + EriQuota int `json:"eriQuota"` + RdmaTypeApi string `json:"rdmaTypeApi"` + SwitchId string `json:"switchId"` + HostId string `json:"hostId"` + DeploysetId string `json:"deploysetId"` + RackId string `json:"rackId"` + NicInfo NicInfo `json:"nicInfo"` + EniNum string `json:"eniNum"` + DeploySetList []DeploySetSimpleModel `json:"deploysetList"` + DeletionProtection int `json:"deletionProtection"` + NetEthQueueCount string `json:"netEthQueueCount"` +} + +type DeploySetSimpleModel struct { + Strategy string `json:"strategy"` + Name string `json:"name"` + Desc string `json:"desc"` + DeploySetId string `json:"deploysetId"` + Concurrency int `json:"concurrency"` +} + +type GetAllStocksResult struct { + BccStocks []BccStock `json:"bccStocks"` + BbcStocks []BbcStock `json:"bbcStocks"` +} + +type BccStock struct { + Spec string `json:"spec"` + SpecId string `json:"specId"` + InventoryQuantity int `json:"inventoryQuantity"` + RootOnLocal bool `json:"rootOnLocal"` + UpdatedTime string `json:"updatedTime"` + CollectionTime string `json:"collectionTime"` + ZoneName string `json:"logicalZone"` +} + +type BbcStock struct { + FlavorId string `json:"flavorId"` + InventoryQuantity int `json:"inventoryQuantity"` + UpdatedTime string `json:"updatedTime"` + CollectionTime string `json:"collectionTime"` + ZoneName string `json:"logicalZone"` +} + +type NicInfo struct { + Status string `json:"status"` + MacAddress string `json:"macAddress"` + DeviceId string `json:"deviceId"` + VpcId string `json:"vpcId"` + EniId string `json:"eniId"` + Name string `json:"name"` + Type string `json:"type"` + CreatedTime string `json:"createdTime"` + SubnetType string `json:"subnetType"` + SubnetId string `json:"subnetId"` + EniNum int `json:"eniNum"` + Az string `json:"az"` + EniUuid string `json:"eniUuid"` + Description string `json:"description"` + Ips []IpModel `json:"ips"` + SecurityGroups []string `json:"securityGroups"` +} + +type IpModel struct { + Eip string `json:"eip"` + EipStatus string `json:"eipStatus"` + EipSize string `json:"eipSize"` + EipId string `json:"eipId"` + Primary string `json:"primary"` + PrivateIp string `json:"privateIp"` + EipAllocationId string `json:"eipAllocationId"` + EipType string `json:"eipType"` + EipGroupId string `json:"eipGroupId"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} + +type Billing struct { + PaymentTiming PaymentTimingType `json:"paymentTiming,omitempty"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +type EphemeralDisk struct { + StorageType StorageType `json:"storageType"` + SizeInGB int `json:"sizeInGB"` + FreeSizeInGB int `json:"freeSizeInGB"` +} + +type EphemeralDiskV3 struct { + StorageType StorageTypeV3 `json:"storageType"` + SizeInGB int `json:"sizeInGB"` + FreeSizeInGB int `json:"freeSizeInGB"` +} + +type CreateCdsModel struct { + CdsSizeInGB int `json:"cdsSizeInGB"` + StorageType StorageType `json:"storageType"` + SnapShotId string `json:"snapshotId,omitempty"` +} + +type CreateCdsModelV3 struct { + CdsSizeInGB int `json:"cdsSizeInGB"` + StorageType StorageTypeV3 `json:"storageType"` + SnapShotId string `json:"snapshotId,omitempty"` +} + +type DiskInfo struct { + StorageType StorageType `json:"storageType"` + MinDiskSize int `json:"minDiskSize"` + MaxDiskSize int `json:"maxDiskSize"` +} + +type DiskZoneResource struct { + ZoneName string `json:"zoneName"` + DiskInfos []DiskInfo `json:"diskInfos"` +} + +type CreateInstanceArgs struct { + ImageId string `json:"imageId"` + Billing Billing `json:"billing"` + InstanceType InstanceType `json:"instanceType,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType StorageType `json:"rootDiskStorageType,omitempty"` + LocalDiskSizeInGB int `json:"localDiskSizeInGB,omitempty"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CreateCdsList []CreateCdsModel `json:"createCdsList,omitempty"` + NetWorkCapacityInMbps int `json:"networkCapacityInMbps,omitempty"` + EipName string `json:"eipName,omitempty"` + DedicateHostId string `json:"dedicatedHostId,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + IsOpenHostnameDomain bool `json:"isOpenHostnameDomain,omitempty"` + AutoSeqSuffix bool `json:"autoSeqSuffix,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds,omitempty"` + GpuCard string `json:"gpuCard,omitempty"` + FpgaCard string `json:"fpgaCard,omitempty"` + KunlunCard string `json:"kunlunCard,omitempty"` + IsomerismCard string `json:"isomerismCard,omitempty"` + CardCount string `json:"cardCount,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` + CdsAutoRenew bool `json:"cdsAutoRenew"` + RelationTag bool `json:"relationTag,omitempty"` + IsOpenIpv6 bool `json:"isOpenIpv6,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + DeployId string `json:"deployId,omitempty"` + BidModel string `json:"bidModel,omitempty"` + BidPrice string `json:"bidPrice,omitempty"` + KeypairId string `json:"keypairId,omitempty"` + AspId string `json:"aspId,omitempty"` + InternetChargeType string `json:"internetChargeType,omitempty"` + UserData string `json:"userData,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` + ClientToken string `json:"-"` + RequestToken string `json:"requestToken"` + DeployIdList []string `json:"deployIdList"` + DetetionProtection int `json:"deletionProtection"` + FileSystems []FileSystemModel `json:"fileSystems,omitempty"` + IsOpenHostEye bool `json:"isOpenHostEye,omitempty"` + ResGroupId string `json:"resGroupId,omitempty"` +} + +type CreateInstanceArgsV2 struct { + ImageId string `json:"imageId"` + Billing Billing `json:"billing"` + InstanceType InstanceType `json:"instanceType,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType StorageType `json:"rootDiskStorageType,omitempty"` + LocalDiskSizeInGB int `json:"localDiskSizeInGB,omitempty"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CreateCdsList []CreateCdsModel `json:"createCdsList,omitempty"` + NetWorkCapacityInMbps int `json:"networkCapacityInMbps,omitempty"` + EipName string `json:"eipName,omitempty"` + DedicateHostId string `json:"dedicatedHostId,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + IsOpenHostnameDomain *bool `json:"isOpenHostnameDomain"` + AutoSeqSuffix *bool `json:"autoSeqSuffix"` + AdminPass string `json:"adminPass,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds,omitempty"` + GpuCard string `json:"gpuCard,omitempty"` + FpgaCard string `json:"fpgaCard,omitempty"` + KunlunCard string `json:"kunlunCard,omitempty"` + IsomerismCard string `json:"isomerismCard,omitempty"` + CardCount string `json:"cardCount,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` + CdsAutoRenew *bool `json:"cdsAutoRenew"` + RelationTag *bool `json:"relationTag"` + IsOpenIpv6 *bool `json:"isOpenIpv6"` + Tags []model.TagModel `json:"tags,omitempty"` + DeployId string `json:"deployId,omitempty"` + BidModel string `json:"bidModel,omitempty"` + BidPrice string `json:"bidPrice,omitempty"` + KeypairId string `json:"keypairId,omitempty"` + AspId string `json:"aspId,omitempty"` + InternetChargeType string `json:"internetChargeType,omitempty"` + UserData string `json:"userData,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` + ClientToken string `json:"-"` + RequestToken string `json:"requestToken"` + DeployIdList []string `json:"deployIdList"` + DetetionProtection int `json:"deletionProtection"` + FileSystems []FileSystemModel `json:"fileSystems,omitempty"` + IsOpenHostEye *bool `json:"isOpenHostEye"` + ResGroupId string `json:"resGroupId,omitempty"` +} + +type FileSystemModel struct { + FsID string `json:"fsId"` + MountAds string `json:"mountAds"` + Path string `json:"path"` + Protocol string `json:"protocol"` +} + +type CreateInstanceStockArgs struct { + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + CardCount string `json:"cardCount"` + InstanceType InstanceType `json:"instanceType"` + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + GpuCard string `json:"gpuCard"` +} + +type ResizeInstanceStockArgs struct { + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + InstanceId string `json:"instanceId"` +} + +type GetStockWithDeploySetArgs struct { + Spec string `json:"spec"` + DeploySetIds []string `json:"deploySetIds"` +} + +type GetStockWithDeploySetResults struct { + BccStocks []BccStock `json:"bccStocks"` +} + +type GetStockWithSpecArgs struct { + Spec string `json:"spec"` + DeploySetIds []string `json:"deploySetIds"` +} + +type GetStockWithSpecResults struct { + BccStocks []BccStock `json:"bccStocks"` +} + +type InstanceStockResult struct { + FlaovrId string `json:"flavorId"` + Count int `json:"Count"` +} + +type GetBidInstancePriceArgs struct { + InstanceType InstanceType `json:"instanceType"` + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType StorageType `json:"rootDiskStorageType,omitempty"` + CreateCdsList []CreateCdsModel `json:"createCdsList,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + Name string `json:"name,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + KeypairId string `json:"keypairId,omitempty"` + AspId string `json:"aspId,omitempty"` + ImageId string `json:"imageId,omitempty"` + BidModel string `json:"bidModel,omitempty"` + BidPrice string `json:"bidPrice,omitempty"` + NetWorkCapacityInMbps int `json:"networkCapacityInMbps,omitempty"` + RelationTag bool `json:"relationTag,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + InternetChargeType string `json:"internetChargeType,omitempty"` + ClientToken string `json:"-"` +} + +type CreateInstanceResult struct { + InstanceIds []string `json:"instanceIds"` +} + +type CreateInstanceBySpecArgs struct { + ImageId string `json:"imageId"` + Spec string `json:"spec"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType StorageType `json:"rootDiskStorageType,omitempty"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CreateCdsList []CreateCdsModel `json:"createCdsList,omitempty"` + NetWorkCapacityInMbps int `json:"networkCapacityInMbps,omitempty"` + EipName string `json:"eipName,omitempty"` + InternetChargeType string `json:"internetChargeType,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + PurchaseMinCount int `json:"purchaseMinCount,omitempty"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + IsOpenHostnameDomain bool `json:"isOpenHostnameDomain,omitempty"` + AutoSeqSuffix bool `json:"autoSeqSuffix,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + Billing Billing `json:"billing"` + ZoneName string `json:"zoneName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds,omitempty"` + RelationTag bool `json:"relationTag,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + KeypairId string `json:"keypairId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` + RaidId string `json:"raidId,omitempty"` + EnableNuma bool `json:"enableNuma,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + CdsAutoRenew bool `json:"cdsAutoRenew"` + AspId string `json:"aspId"` + InternalIps []string `json:"internalIps,omitempty"` + DeployId string `json:"deployId,omitempty"` + UserData string `json:"userData,omitempty"` + ClientToken string `json:"-"` + RequestToken string `json:"requestToken"` + DeployIdList []string `json:"deployIdList"` + DetetionProtection int `json:"deletionProtection"` + IsOpenIpv6 bool `json:"isOpenIpv6,omitempty"` + SpecId string `json:"specId,omitempty"` + IsOpenHostEye bool `json:"isOpenHostEye,omitempty"` + BidModel string `json:"bidModel,omitempty"` + BidPrice string `json:"bidPrice,omitempty"` + ResGroupId string `json:"resGroupId,omitempty"` +} + +type CreateInstanceBySpecArgsV2 struct { + ImageId string `json:"imageId"` + Spec string `json:"spec"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType StorageType `json:"rootDiskStorageType,omitempty"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CreateCdsList []CreateCdsModel `json:"createCdsList,omitempty"` + NetWorkCapacityInMbps int `json:"networkCapacityInMbps,omitempty"` + EipName string `json:"eipName,omitempty"` + InternetChargeType string `json:"internetChargeType,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + PurchaseMinCount int `json:"purchaseMinCount,omitempty"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + IsOpenHostnameDomain *bool `json:"isOpenHostnameDomain"` + AutoSeqSuffix *bool `json:"autoSeqSuffix"` + AdminPass string `json:"adminPass,omitempty"` + Billing Billing `json:"billing"` + ZoneName string `json:"zoneName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds,omitempty"` + RelationTag *bool `json:"relationTag"` + Tags []model.TagModel `json:"tags,omitempty"` + KeypairId string `json:"keypairId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` + RaidId string `json:"raidId,omitempty"` + EnableNuma *bool `json:"enableNuma"` + DataPartitionType string `json:"dataPartitionType,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + CdsAutoRenew *bool `json:"cdsAutoRenew"` + AspId string `json:"aspId"` + InternalIps []string `json:"internalIps,omitempty"` + DeployId string `json:"deployId,omitempty"` + UserData string `json:"userData,omitempty"` + ClientToken string `json:"-"` + RequestToken string `json:"requestToken"` + DeployIdList []string `json:"deployIdList"` + DetetionProtection int `json:"deletionProtection"` + IsOpenIpv6 *bool `json:"isOpenIpv6"` + SpecId string `json:"specId,omitempty"` + IsOpenHostEye *bool `json:"isOpenHostEye"` + BidModel string `json:"bidModel,omitempty"` + BidPrice string `json:"bidPrice,omitempty"` + ResGroupId string `json:"resGroupId,omitempty"` + EnableHt *bool `json:"enableHt"` +} + +const ( + LabelOperatorEqual LabelOperator = "equal" + LabelOperatorNotEqual LabelOperator = "not_equal" + LabelOperatorExist LabelOperator = "exist" + LabelOperatorNotExist LabelOperator = "not_exist" +) + +type LabelOperator string + +type LabelConstraint struct { + Key string `json:"labelKey,omitempty"` + Value string `json:"labelValue,omitempty"` + Operator LabelOperator `json:"operatorName,omitempty"` +} + +// --- 创建 BCC 的新接口的参数和返回值 + +type CreateSpecialInstanceBySpecArgs struct { + ImageId string `json:"imageId"` + Spec string `json:"spec"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType StorageType `json:"rootDiskStorageType,omitempty"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CreateCdsList []CreateCdsModel `json:"createCdsList,omitempty"` + NetWorkCapacityInMbps int `json:"networkCapacityInMbps,omitempty"` + InternetChargeType string `json:"internetChargeType,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + Name string `json:"name,omitempty"` + Hostname string `json:"hostname,omitempty"` + IsOpenHostnameDomain bool `json:"isOpenHostnameDomain,omitempty"` + UserData string `json:"userData,omitempty"` + AutoSeqSuffix bool `json:"autoSeqSuffix,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + Billing Billing `json:"billing"` + ZoneName string `json:"zoneName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds,omitempty"` + RelationTag bool `json:"relationTag,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + KeypairId string `json:"keypairId"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` + CdsAutoRenew bool `json:"cdsAutoRenew"` + AspId string `json:"aspId"` + InternalIps []string `json:"internalIps,omitempty"` + DeployId string `json:"deployId,omitempty"` + ClientToken string `json:"-"` + RequestToken string `json:"requestToken"` + DeployIdList []string `json:"deployIdList"` + DetetionProtection int `json:"deletionProtection"` + + // CreateInstanceBySpecArgs 的基础上增加的参数 + LabelConstraints []LabelConstraint `json:"labelConstraints,omitempty"` + ResGroupId string `json:"resGroupId,omitempty"` +} + +type CreateSpecialInstanceBySpecResult struct { + InstanceIds []string `json:"instanceIds"` +} + +type CreateInstanceV3Args struct { + InstanceSpec string `json:"instanceSpec,omitempty"` + SystemVolume SystemVolume `json:"systemVolume,omitempty"` + DataVolumes []DataVolume `json:"dataVolumes,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + HostName string `json:"hostName,omitempty"` + AutoSeqSuffix bool `json:"autoSeqSuffix,omitempty"` + HostNameDomain bool `json:"hostNameDomain,omitempty"` + Password string `json:"password,omitempty"` + Billing Billing `json:"billing"` + ZoneName string `json:"zoneName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + AssociatedResourceTag bool `json:"associatedResourceTag,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + KeypairId string `json:"keypairId,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + CdsAutoRenew bool `json:"cdsAutoRenew,omitempty"` + AutoSnapshotPolicyId string `json:"autoSnapshotPolicyId,omitempty"` + PrivateIpAddresses []string `json:"privateIpAddresses,omitempty"` + DeploymentSetId string `json:"deploymentSetId,omitempty"` + DeployIdList []string `json:"deployIdList"` + ImageId string `json:"imageId,omitempty"` + UserData string `json:"userData,omitempty"` + InstanceMarketOptions InstanceMarketOptions `json:"instanceMarketOptions,omitempty"` + Ipv6 bool `json:"ipv6,omitempty"` + DedicatedHostId string `json:"dedicatedHostId,omitempty"` + InternetAccessible InternetAccessible `json:"internetAccessible,omitempty"` + ClientToken string `json:"-"` + RequestToken string `json:"requestToken"` + ResGroupId string `json:"resGroupId,omitempty"` +} + +type CreateInstanceV3Result struct { + InstanceIds []string `json:"instanceIds"` +} + +type SystemVolume struct { + StorageType StorageTypeV3 `json:"storageType,omitempty"` + VolumeSize int `json:"volumeSize,omitempty"` +} + +type DataVolume struct { + StorageType StorageTypeV3 `json:"storageType,omitempty"` + VolumeSize int `json:"volumeSize,omitempty"` + SnapshotId string `json:"snapshotId,omitempty"` + EncryptKey string `json:"encryptKey,omitempty"` +} + +type InstanceMarketOptions struct { + SpotOption string `json:"spotOption,omitempty"` + SpotPrice string `json:"spotPrice,omitempty"` +} + +type InternetAccessible struct { + InternetMaxBandwidthOut int `json:"internetMaxBandwidthOut,omitempty"` + InternetChargeType InternetChargeType `json:"internetChargeType,omitempty"` +} + +type InternetChargeType string + +const ( + BandwidthPrepaid InternetChargeType = "BANDWIDTH_PREPAID" + TrafficPostpaidByHour InternetChargeType = "TRAFFIC_POSTPAID_BY_HOUR" + BandwidthPostpaidByHour InternetChargeType = "BANDWIDTH_POSTPAID_BY_HOUR" +) + +type CreateInstanceBySpecResult struct { + InstanceIds []string `json:"instanceIds"` + OrderId string `json:"orderId,omitempty"` +} + +type ListInstanceArgs struct { + Marker string + MaxKeys int + InternalIp string + DedicatedHostId string + ZoneName string + KeypairId string + AutoRenew bool + InstanceIds string + InstanceNames string + CdsIds string + DeploySetIds string + SecurityGroupIds string + PaymentTiming string + Status string + Tags string + VpcId string + PrivateIps string +} + +type ListInstanceResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []InstanceModel `json:"instances"` +} + +type ListRecycleInstanceArgs struct { + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + InstanceId string `json:"instanceId,omitempty"` + Name string `json:"name,omitempty"` + PaymentTiming string `json:"paymentTiming,omitempty"` + RecycleBegin string `json:"recycleBegin,omitempty"` + RecycleEnd string `json:"recycleEnd,omitempty"` +} + +type ListServerRequestV3Args struct { + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + InstanceId string `json:"instanceId,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + PrivateIpAddress string `json:"privateIpAddress,omitempty"` + PublicIpAddress string `json:"publicIpAddress,omitempty"` + VpcName string `json:"vpcName,omitempty"` + SubnetName string `json:"subnetName,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + DedicatedHostId string `json:"dedicatedHostId,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + AutoRenew bool `json:"autoRenew,omitempty"` + KeypairId string `json:"keypairId,omitempty"` + KeypairName string `json:"keypairName,omitempty"` + DeploymentSetId string `json:"deploymentSetId,omitempty"` + DeploymentSetName string `json:"deploymentSetName,omitempty"` + ResGroupId string `json:"resGroupId,omitempty"` + Tag model.TagModel `json:"tag,omitempty"` +} + +type LogicMarkerResultResponseV3 struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []InstanceModelV3 `json:"instances"` +} + +type ListRecycleInstanceResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []RecycleInstanceModel `json:"instances"` +} + +type InstanceModelV3 struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + HostId string `json:"hostId"` + HostName string `json:"hostName"` + InstanceSpec string `json:"instanceSpec"` + Status InstanceStatus `json:"status"` + Description string `json:"description"` + PaymentTiming string `json:"paymentTiming"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + ReleaseTime string `json:"releaseTime"` + PrivateIpAddress string `json:"privateIpAddress"` + PublicIpAddress string `json:"publicIpAddress"` + Cpu int `json:"cpu"` + Memory int `json:"memory"` + GpuCard string `json:"gpuCard"` + FpgaCard string `json:"fpgaCard"` + CardCount int `json:"cardCount"` + DataVolumes []DataVolumeV3 `json:"dataVolumes"` + ImageId string `json:"imageId"` + NetworkCapacityInMbps InternetAccessible `json:"networkCapacityInMbps"` + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` + VpcId string `json:"vpcId"` + AutoRenew bool `json:"autoRenew"` + KeypairId string `json:"keypairId"` + KeypairName string `json:"keypairName"` + HypervisorDedicatedId string `json:"hypervisorDedicatedId"` + Ipv6 string `json:"ipv6"` + Tags []model.TagModel `json:"tags"` + DeployId []string `json:"deployId"` + SerialNumber string `json:"serialNumber"` + SwitchId string `json:"switchId"` + RackId string `json:"rackId"` + NicInfo NicInfoV3 `json:"nicInfo"` + OsName string `json:"osName"` + OsType string `json:"osType"` +} + +type NicInfoV3 struct { + MacAddress string `json:"macAddress"` + EniId string `json:"eniId"` + Type string `json:"type"` + Ips []IpModelV3 `json:"ips"` + SecurityGroups []string `json:"securityGroups"` +} + +type IpModelV3 struct { + Primary bool `json:"primary"` + PrivateIp string `json:"privateIp"` +} + +type DataVolumeV3 struct { + VolumeId string `json:"volumeId"` + VolumeType string `json:"volumeType"` + VolumeSizeInGb int `json:"volumeSizeInGb"` + StorageType string `json:"storageType"` + SnapshotId string `json:"snapshotId"` + EncryptKey string `json:"encryptKey"` +} + +type RecycleInstanceModel struct { + InstanceId string `json:"id"` + SerialNumber string `json:"serialNumber"` + InstanceName string `json:"name"` + RecycleTime string `json:"recycleTime"` + DeleteTime string `json:"deleteTime"` + PaymentTiming string `json:"paymentTiming"` + ServiceName string `json:"serviceName"` + ServiceType string `json:"serviceType"` + ConfigItems []string `json:"configItems"` + ConfigItem RecycleInstanceModelConfigItem `json:"configItem"` +} + +type RecycleInstanceModelConfigItem struct { + Cpu int `json:"cpu"` + Memory int `json:"memory"` + Type string `json:"type"` + SpecId string `json:"specId"` + Spec string `json:"spec"` + ZoneName string `json:"zoneName"` +} + +type ModifyInstanceHostnameArgs struct { + Hostname string `json:"hostname"` + IsOpenHostnameDomain bool `json:"isOpenHostnameDomain"` + Reboot bool `json:"reboot"` +} + +type GetInstanceDetailResult struct { + Instance InstanceModel `json:"instance"` +} + +type AutoReleaseArgs struct { + ReleaseTime string `json:"releaseTime"` +} + +type ResizeInstanceArgs struct { + CpuCount int `json:"cpuCount"` + GpuCardCount int `json:"gpuCardCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + Spec string `json:"spec"` + LiveResize bool `json:"liveResize"` + ClientToken string `json:"-"` +} + +type RebuildInstanceArgs struct { + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId"` + IsOpenHostEye bool `json:"isOpenHostEye"` + IsPreserveData bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type RebuildInstanceArgsV2 struct { + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId"` + IsOpenHostEye *bool `json:"isOpenHostEye"` + IsPreserveData *bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type StopInstanceArgs struct { + ForceStop bool `json:"forceStop"` + StopWithNoCharge bool `json:"stopWithNoCharge"` +} + +type ChangeInstancePassArgs struct { + AdminPass string `json:"adminPass"` +} + +type ModifyInstanceAttributeArgs struct { + Name string `json:"name"` + NetEthQueueCount string `json:"netEthQueueCount"` +} + +type ModifyInstanceDescArgs struct { + Description string `json:"desc"` +} + +type BindSecurityGroupArgs struct { + SecurityGroupId string `json:"securityGroupId"` +} + +type GetInstanceVNCResult struct { + VNCUrl string `json:"vncUrl"` +} + +type InstancePurchaseReservedResult struct { + OrderId string `json:"orderId"` +} + +type GetBidInstancePriceResult struct { + Money string `json:"money"` + Count string `json:"count"` + PerMoney string `json:"perMoney"` +} + +type ListBidFlavorResult struct { + ZoneResources []ZoneResource `json:"zoneResources"` +} + +type ZoneResource struct { + ZoneName string `json:"zoneName"` + BccResources []BccResource `json:"bccResources"` +} + +type BccResource struct { + InstanceType InstanceType `json:"instanceType"` + Flavors []Flavor `json:"flavors"` +} + +type Flavor struct { + SpecId string `json:"specId"` + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + ProductType string `json:"productType"` + Spec string `json:"spec"` +} + +type PurchaseReservedArgs struct { + RelatedRenewFlag string `json:"relatedRenewFlag"` + Billing Billing `json:"billing"` + ClientToken string `json:"-"` +} + +const ( + RelatedRenewFlagCDS string = "CDS" + RelatedRenewFlagEIP string = "EIP" + RelatedRenewFlagMKT string = "MKT" + RelatedRenewFlagCDSEIP string = "CDS_EIP" + RelatedRenewFlagCDSMKT string = "CDS_MKT" + RelatedRenewFlagEIPMKT string = "EIP_MKT" + RelatedRenewFlagCDSEIPMKT string = "CDS_EIP_MKT" +) + +type DeleteInstanceWithRelateResourceArgs struct { + RelatedReleaseFlag bool `json:"relatedReleaseFlag"` + DeleteCdsSnapshotFlag bool `json:"deleteCdsSnapshotFlag"` + BccRecycleFlag bool `json:"bccRecycleFlag"` + DeleteRelatedEnisFlag bool `json:"deleteRelatedEnisFlag"` + DeleteImmediate bool `json:"deleteImmediate"` +} + +type InstanceChangeVpcArgs struct { + InstanceId string `json:"instanceId"` + SubnetId string `json:"subnetId"` + InternalIp string `json:"internalIp"` + Reboot bool `json:"reboot"` + SecurityGroupIds []string `json:"securityGroupIds"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` +} + +type InstanceChangeSubnetArgs struct { + InstanceId string `json:"instanceId"` + SubnetId string `json:"subnetId"` + InternalIp string `json:"internalIp"` + Reboot bool `json:"reboot"` +} + +type BatchAddIpArgs struct { + InstanceId string `json:"instanceId"` + PrivateIps []string `json:"privateIps"` + SecondaryPrivateIpAddressCount int `json:"secondaryPrivateIpAddressCount"` + AllocateMultiIpv6Addr bool `json:"allocateMultiIpv6Addr"` + ClientToken string `json:"-"` +} + +type BatchAddIpResponse struct { + PrivateIps []string `json:"privateIps"` +} + +type BatchDelIpArgs struct { + InstanceId string `json:"instanceId"` + PrivateIps []string `json:"privateIps"` + ClientToken string `json:"-"` +} + +type VolumeStatus string + +const ( + VolumeStatusAVAILABLE VolumeStatus = "Available" + VolumeStatusINUSE VolumeStatus = "InUse" + VolumeStatusSNAPSHOTPROCESSING VolumeStatus = "SnapshotProcessing" + VolumeStatusRECHARGING VolumeStatus = "Recharging" + VolumeStatusDETACHING VolumeStatus = "Detaching" + VolumeStatusDELETING VolumeStatus = "Deleting" + VolumeStatusEXPIRED VolumeStatus = "Expired" + VolumeStatusNOTAVAILABLE VolumeStatus = "NotAvailable" + VolumeStatusDELETED VolumeStatus = "Deleted" + VolumeStatusSCALING VolumeStatus = "Scaling" + VolumeStatusIMAGEPROCESSING VolumeStatus = "ImageProcessing" + VolumeStatusCREATING VolumeStatus = "Creating" + VolumeStatusATTACHING VolumeStatus = "Attaching" + VolumeStatusERROR VolumeStatus = "Error" +) + +type VolumeStatusV3 string + +const ( + VolumeStatusV3AVAILABLE VolumeStatusV3 = "Available" + VolumeStatusV3INUSE VolumeStatusV3 = "InUse" + VolumeStatusV3SNAPSHOTPROCESSING VolumeStatusV3 = "SnapshotProcessing" + VolumeStatusV3RECHARGING VolumeStatusV3 = "Recharging" + VolumeStatusV3DETACHING VolumeStatusV3 = "Detaching" + VolumeStatusV3DELETING VolumeStatusV3 = "Deleting" + VolumeStatusV3EXPIRED VolumeStatusV3 = "Expired" + VolumeStatusV3NOTAVAILABLE VolumeStatusV3 = "NotAvailable" + VolumeStatusV3DELETED VolumeStatusV3 = "Deleted" + VolumeStatusV3SCALING VolumeStatusV3 = "Scaling" + VolumeStatusV3IMAGEPROCESSING VolumeStatusV3 = "ImageProcessing" + VolumeStatusV3CREATING VolumeStatusV3 = "Creating" + VolumeStatusV3ATTACHING VolumeStatusV3 = "Attaching" + VolumeStatusV3ERROR VolumeStatusV3 = "Error" + VolumeStatusV3Recycled VolumeStatusV3 = "Recycled" +) + +type VolumeType string + +const ( + VolumeTypeSYSTEM VolumeType = "System" + VolumeTypeEPHEMERAL VolumeType = "Ephemeral" + VolumeTypeCDS VolumeType = "Cds" +) + +type VolumeTypeV3 string + +const ( + VolumeTypeV3SYSTEM VolumeTypeV3 = "SYSTEM" + VolumeTypeV3DATA VolumeTypeV3 = "DATA" +) + +type RenameCSDVolumeArgs struct { + Name string `json:"name"` +} + +type ModifyCSDVolumeArgs struct { + CdsName string `json:"cdsName,omitempty"` + Desc string `json:"desc,omitempty"` +} + +type DetachVolumeArgs struct { + InstanceId string `json:"instanceId"` +} + +type PurchaseReservedCSDVolumeArgs struct { + Billing *Billing `json:"billing"` + ClientToken string `json:"-"` +} + +type DeleteCDSVolumeArgs struct { + ManualSnapshot string `json:"manualSnapshot,omitempty"` + AutoSnapshot string `json:"autoSnapshot,omitempty"` + Recycle string `json:"recycle,omitempty"` +} + +type ModifyChargeTypeCSDVolumeArgs struct { + Billing *Billing `json:"billing"` +} + +type ListCDSVolumeResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Volumes []VolumeModel `json:"volumes"` +} + +type ListCDSVolumeResultV3 struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Volumes []VolumeModelV3 `json:"volumes"` +} + +type VolumeModel struct { + Type VolumeType `json:"type"` + StorageType StorageType `json:"storageType"` + Id string `json:"id"` + Name string `json:"name"` + DiskSizeInGB int `json:"diskSizeInGB"` + PaymentTiming string `json:"paymentTiming"` + ExpireTime string `json:"expireTime"` + Status VolumeStatus `json:"status"` + Desc string `json:"desc"` + Attachments []VolumeAttachmentModel `json:"attachments"` + ZoneName string `json:"zoneName"` + AutoSnapshotPolicy *AutoSnapshotPolicyModel `json:"autoSnapshotPolicy"` + CreateTime string `json:"createTime"` + IsSystemVolume bool `json:"isSystemVolume"` + RegionId string `json:"regionId"` + SourceSnapshotId string `json:"sourceSnapshotId"` + SnapshotNum string `json:"snapshotNum"` + Tags []model.TagModel `json:"tags"` + EnableAutoRenew bool `json:"enableAutoRenew"` + AutoRenewTime int `json:"autoRenewTime"` + Encrypted bool `json:"encrypted"` + ClusterId string `json:"clusterId"` + RoleName string `json:"roleName"` + CreatedFrom string `json:"createdFrom"` + ReleaseTime string `json:"releaseTime"` +} + +type VolumeModelV3 struct { + Id string `json:"volumeId"` + Name string `json:"volumeName"` + VolumeSize int `json:"volumeSizeInGB"` + VolumeStatus VolumeStatusV3 `json:"volumeStatus"` + VolumeType VolumeTypeV3 `json:"volumeType"` + StorageType StorageTypeV3 `json:"storageType"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + Desc string `json:"description"` + PaymentTiming string `json:"paymentTiming"` + EnableAutoRenew bool `json:"enableAutoRenew"` + AutoRenewTime int `json:"autoRenewTime"` + ZoneName string `json:"zoneName"` + SourceSnapshotId string `json:"sourceSnapshotId"` + Region string `json:"region"` + SnapshotCount int `json:"snapshotCount"` + AutoSnapshotPolicyId string `json:"autoSnapshotPolicyId"` + Encrypted bool `json:"encrypted"` + Tags []model.TagModel `json:"tags"` + Attachments []VolumeAttachmentsModel `json:"volumeAttachments"` +} + +type VolumeAttachmentsModel struct { + InstanceId string `json:"instanceId"` + Device string `json:"device"` + AttachTime string `json:"attachTime"` +} + +type VolumeAttachmentModel struct { + VolumeId string `json:"volumeId"` + InstanceId string `json:"instanceId"` + Device string `json:"device"` + Serial string `json:"serial"` +} + +type AttachVolumeResult struct { + VolumeAttachment *VolumeAttachmentModel `json:"volumeAttachment"` +} + +type CreateCDSVolumeArgs struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + SnapshotId string `json:"snapshotId,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + CdsSizeInGB int `json:"cdsSizeInGB,omitempty"` + StorageType StorageType `json:"storageType,omitempty"` + Billing *Billing `json:"billing"` + EncryptKey string `json:"encryptKey"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` + InstanceId string `json:"instanceId"` + ClusterId string `json:"clusterId"` + Tags []model.TagModel `json:"tags"` + AutoSnapshotPolicy []AutoSnapshotPolicy `json:"autoSnapshotPolicy"` + ClientToken string `json:"-"` +} + +type AutoSnapshotPolicy struct { + AutoSnapshotPolicyId string `json:"autoSnapshotPolicyId"` +} + +type CreateCDSVolumeV3Args struct { + VolumeName string `json:"volumeName,omitempty"` + Description string `json:"description,omitempty"` + SnapshotId string `json:"snapshotId,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + VolumeSize int `json:"volumeSizeInGB,omitempty"` + StorageType StorageTypeV3 `json:"storageType,omitempty"` + Billing *Billing `json:"billing"` + EncryptKey string `json:"encryptKey"` + AutoSnapshotPolicyId string `json:"autoSnapshotPolicyId"` + InstanceId string `json:"instanceId"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` + ClientToken string `json:"-"` +} + +type CreateCDSVolumeResult struct { + VolumeIds []string `json:"volumeIds"` +} + +type GetVolumeDetailResult struct { + Volume *VolumeModel `json:"volume"` +} + +type GetVolumeDetailResultV3 struct { + Volume *VolumeModelV3 `json:"volume"` +} + +type GetAvailableDiskInfoResult struct { + CdsUsedCapacityGB string `json:"cdsUsedCapacityGB"` + CdsCreated string `json:"cdsCreated"` + CdsTotalCapacityGB string `json:"cdsTotalCapacityGB"` + CdsTotal string `json:"cdsTotal"` + CdsRatio string `json:"cdsRatio"` + DiskZoneResources []DiskZoneResource `json:"diskZoneResources"` +} + +type AttachVolumeArgs struct { + InstanceId string `json:"instanceId"` +} + +type ResizeCSDVolumeArgs struct { + NewCdsSizeInGB int `json:"newCdsSizeInGB,omitempty"` + NewVolumeType StorageType `json:"newVolumeType,omitempty"` + ClientToken string `json:"-"` +} + +type RollbackCSDVolumeArgs struct { + SnapshotId string `json:"snapshotId"` +} + +type ListCDSVolumeArgs struct { + MaxKeys int `json:"maxKeys"` + InstanceId string `json:"instanceId"` + ZoneName string `json:"zoneName"` + Marker string `json:"marker"` + ClusterId string `json:"clusterId"` + ChargeFilter string `json:"chargeFilter"` + UsageFilter string `json:"usageFilter"` + Name string `json:"name"` +} + +type AutoRenewCDSVolumeArgs struct { + VolumeId string `json:"volumeId"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` + ClientToken string `json:"-"` +} + +type CancelAutoRenewCDSVolumeArgs struct { + VolumeId string `json:"volumeId"` + ClientToken string `json:"-"` +} + +type AutoSnapshotPolicyModel struct { + CreatedTime string `json:"createdTime"` + Id string `json:"id"` + Status string `json:"status"` + RetentionDays int `json:"retentionDays"` + UpdatedTime string `json:"updatedTime"` + DeletedTime string `json:"deletedTime"` + LastExecuteTime string `json:"lastExecuteTime"` + VolumeCount int `json:"volumeCount"` + Name string `json:"name"` + TimePoints []int `json:"timePoints"` + RepeatWeekdays []int `json:"repeatWeekdays"` +} + +type SecurityGroupRuleModel struct { + SourceIp string `json:"sourceIp,omitempty"` + DestIp string `json:"destIp,omitempty"` + Protocol string `json:"protocol,omitempty"` + SourceGroupId string `json:"sourceGroupId,omitempty"` + Ethertype string `json:"ethertype,omitempty"` + PortRange string `json:"portRange,omitempty"` + DestGroupId string `json:"destGroupId,omitempty"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + Remark string `json:"remark,omitempty"` + Direction string `json:"direction"` +} + +type SecurityGroupModel struct { + Id string `json:"id"` + Name string `json:"name"` + Desc string `json:"desc"` + VpcId string `json:"vpcId"` + Rules []SecurityGroupRuleModel `json:"rules"` + Tags []model.TagModel `json:"tags"` +} + +type CreateSecurityGroupArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Desc string `json:"desc,omitempty"` + VpcId string `json:"vpcId,omitempty"` + Rules []SecurityGroupRuleModel `json:"rules"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +type ListSecurityGroupArgs struct { + Marker string + MaxKeys int + InstanceId string + VpcId string +} + +type CreateSecurityGroupResult struct { + SecurityGroupId string `json:"securityGroupId"` +} + +type ListSecurityGroupResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + SecurityGroups []SecurityGroupModel `json:"securityGroups"` +} + +type AuthorizeSecurityGroupArgs struct { + ClientToken string `json:"-"` + Rule *SecurityGroupRuleModel `json:"rule"` +} + +type RevokeSecurityGroupArgs struct { + Rule *SecurityGroupRuleModel `json:"rule"` +} + +type ImageType string + +const ( + ImageTypeIntegration ImageType = "Integration" + ImageTypeSystem ImageType = "System" + ImageTypeCustom ImageType = "Custom" + + // ImageTypeAll 所有镜像类型 + ImageTypeAll ImageType = "All" + + // ImageTypeSharing 共享镜像 + ImageTypeSharing ImageType = "Sharing" + + // ImageTypeGPUSystem gpu公有 + ImageTypeGPUSystem ImageType = "GpuBccSystem" + + // ImageTypeGPUCustom gpu 自定义 + ImageTypeGPUCustom ImageType = "GpuBccCustom" + + // ImageTypeBBCSystem BBC 公有 + ImageTypeBBCSystem ImageType = "BbcSystem" + + // ImageTypeBBCCustom BBC 自定义 + ImageTypeBBCCustom ImageType = "BbcCustom" +) + +type ImageStatus string + +const ( + ImageStatusCreating ImageStatus = "Creating" + ImageStatusCreateFailed ImageStatus = "CreateFailed" + ImageStatusAvailable ImageStatus = "Available" + ImageStatusNotAvailable ImageStatus = "NotAvailable" + ImageStatusError ImageStatus = "Error" +) + +type SharedUser struct { + AccountId string `json:"accountId,omitempty"` + Account string `json:"account,omitempty"` + UcAccount string `json:"ucAccount,omitempty"` +} + +type GetImageSharedUserResult struct { + Users []SharedUser `json:"users"` +} + +type GetImageOsResult struct { + OsInfo []OsModel `json:"osInfo"` +} + +type CreateImageResult struct { + ImageId string `json:"imageId"` +} + +type ListImageResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Images []ImageModel `json:"images"` +} + +type ImageModel struct { + OsVersion string `json:"osVersion"` + OsArch string `json:"osArch"` + OsLang string `json:"osLang"` + Status ImageStatus `json:"status"` + Desc string `json:"desc"` + Id string `json:"id"` + Name string `json:"name"` + OsName string `json:"osName"` + OsBuild string `json:"osBuild"` + CreateTime string `json:"createTime"` + Type ImageType `json:"type"` + OsType string `json:"osType"` + SpecialVersion string `json:"specialVersion"` + Package bool `json:"package"` + Encrypted bool `json:"encrypted"` + MinDiskGb int `json:"minDiskGb"` + DiskSize int `json:"diskSize"` + Snapshots []SnapshotModel `json:"snapshots"` +} + +type GetImageDetailResult struct { + Image *ImageModel `json:"image"` +} + +type RemoteCopyImageArgs struct { + Name string `json:"name,omitempty"` + DestRegion []string `json:"destRegion"` +} + +type RemoteCopyImageResult struct { + RemoteCopyImages []RemoteCopyImageModel `json:"result"` +} + +type RemoteCopyImageModel struct { + Region string `json:"region"` + ImageId string `json:"imageId"` + ErrMsg string `json:"errMsg"` + Code string `json:"code"` +} + +type CreateImageArgs struct { + InstanceId string `json:"instanceId,omitempty"` + SnapshotId string `json:"snapshotId,omitempty"` + ImageName string `json:"imageName"` + IsRelateCds bool `json:"relateCds"` + EncryptKey string `json:"encryptKey"` + ClientToken string `json:"-"` +} + +type ListImageArgs struct { + Marker string + MaxKeys int + ImageType string + ImageName string +} + +type OsModel struct { + OsVersion string `json:"osVersion"` + OsType string `json:"osType"` + InstanceId string `json:"instanceId"` + OsArch string `json:"osArch"` + OsName string `json:"osName"` + OsLang string `json:"osLang"` + SpecialVersion string `json:"specialVersion"` +} + +type GetImageOsArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type CreateSnapshotArgs struct { + ClientToken string `json:"-"` + VolumeId string `json:"volumeId"` + SnapshotName string `json:"snapshotName"` + Description string `json:"desc,omitempty"` + Tags []model.TagModel `json:"tags"` +} + +type CreateSnapshotResult struct { + SnapshotId string `json:"snapshotId"` +} + +type ListSnapshotArgs struct { + Marker string + MaxKeys int + VolumeId string +} + +type ListSnapshotChainArgs struct { + OrderBy string `json:"orderBy,omitempty"` + Order string `json:"order,omitempty"` + PageSize int `json:"pageSize,omitempty"` + PageNo int `json:"pageNo,omitempty"` + VolumeId string `json:"volumeId,omitempty"` +} + +type SnapshotStatus string + +const ( + SnapshotStatusCreating SnapshotStatus = "Creating" + SnapshotStatusCreatedFailed SnapshotStatus = "CreatedFailed" + SnapshotStatusAvailable SnapshotStatus = "Available" + SnapshotStatusNotAvailable SnapshotStatus = "NotAvailable" +) + +type SnapshotModel struct { + Id string `json:"id"` + Name string `json:"name"` + SizeInGB int `json:"sizeInGB"` + CreateTime string `json:"createTime"` + Status SnapshotStatus `json:"status"` + CreateMethod string `json:"createMethod"` + VolumeId string `json:"volumeId"` + Description string `json:"desc"` + ExpireTime string `json:"expireTime"` + Package bool `json:"package"` + TemplateId string `json:"templateId"` + InsnapId string `json:"insnapId"` + Encrypted bool `json:"encrypted"` +} + +type ListSnapshotResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Snapshots []SnapshotModel `json:"snapshots"` +} + +type ListSnapshotChainResult struct { + OrderBy string `json:"orderBy"` + TotalCount int `json:"totalCount"` + PageSize int `json:"pageSize"` + PageNo int `json:"pageNo"` + IsTruncated bool `json:"isTruncated"` + VolumeId string `json:"volumeId"` + Snapchains []SnapchainModel `json:"snapchains"` +} + +type SnapchainModel struct { + Status string `json:"status"` + ChainSize string `json:"chainSize"` + ChainId string `json:"chainId"` + InstanceId string `json:"instanceId"` + UserId string `json:"userId"` + VolumeId string `json:"volumeId"` + VolumeSize int `json:"volumeSize"` + ManualSnapCount int `json:"manualSnapCount"` + AutoSnapCount int `json:"autoSnapCount"` + CreateTime string `json:"createTime"` +} + +type GetSnapshotDetailResult struct { + Snapshot SnapshotModel `json:"snapshot"` +} + +type CreateASPArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + TimePoints []string `json:"timePoints"` + RepeatWeekdays []string `json:"repeatWeekdays"` + RetentionDays string `json:"retentionDays"` +} + +type CreateASPResult struct { + AspId string `json:"aspId"` +} + +type AttachASPArgs struct { + VolumeIds []string `json:"volumeIds"` +} + +type DetachASPArgs struct { + VolumeIds []string `json:"volumeIds"` +} + +type ListASPArgs struct { + Marker string + MaxKeys int + AspName string + VolumeName string +} + +type ListASPResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + AutoSnapshotPolicys []AutoSnapshotPolicyModel `json:"autoSnapshotPolicys"` +} + +type GetASPDetailResult struct { + AutoSnapshotPolicy AutoSnapshotPolicyModel `json:"autoSnapshotPolicy"` +} + +type UpdateASPArgs struct { + Name string `json:"name"` + TimePoints []string `json:"timePoints"` + RepeatWeekdays []string `json:"repeatWeekdays"` + RetentionDays string `json:"retentionDays"` + AspId string `json:"aspId"` +} + +type InstanceTypeModel struct { + Type string `json:"type"` + Name string `json:"name"` + CpuCount int `json:"cpuCount"` + MemorySizeInGB int `json:"memorySizeInGB"` + LocalDiskSizeInGB int `json:"localDiskSizeInGB"` +} + +type ListSpecResult struct { + InstanceTypes []InstanceTypeModel `json:"instanceTypes"` +} + +type ZoneModel struct { + ZoneName string `json:"zoneName"` +} + +type ListZoneResult struct { + Zones []ZoneModel `json:"zones"` +} + +type ListTypeZonesResult struct { + ZoneNames []string `json:"zoneNames"` +} + +type CreateDeploySetArgs struct { + Strategy string `json:"strategy"` + Name string `json:"name,omitempty"` + Desc string `json:"desc,omitempty"` + Concurrency int `json:"concurrency,omitempty"` + ClientToken string `json:"-"` +} + +type ModifyDeploySetArgs struct { + Name string `json:"name,omitempty"` + Desc string `json:"desc,omitempty"` + ClientToken string `json:"-"` +} + +type CreateDeploySetResp struct { + DeploySetIds []string `json:"deploySetIds"` +} + +type CreateDeploySetResult struct { + DeploySetId string `json:"deploySetIds"` +} + +type ListDeploySetsResult struct { + DeploySetList []DeploySetModel `json:"deploySets"` +} + +type DeploySetModel struct { + InstanceCount string `json:"instanceCount"` + Strategy string `json:"strategy"` + InstanceList []AzIntstanceStatis `json:"azIntstanceStatisList"` + Name string `json:"name"` + Desc string `json:"desc"` + DeploySetId string `json:"deploysetId"` + Concurrency int `json:"concurrency"` +} + +type DeploySetResult struct { + Strategy string `json:"strategy"` + Name string `json:"name"` + Desc string `json:"desc"` + DeploySetId string `json:"shortId"` + Concurrency int `json:"concurrency"` + InstanceList []AzIntstanceStatisDetail `json:"azIntstanceStatisList"` +} + +type UpdateInstanceDeployArgs struct { + ClientToken string `json:"-"` + InstanceId string `json:"instanceId,omitempty"` + DeploySetIds []string `json:"deploysetIdList,omitempty"` +} + +type DelInstanceDeployArgs struct { + ClientToken string `json:"-"` + InstanceIds []string `json:"instanceIdList,omitempty"` + DeploySetId string `json:"deployId,omitempty"` +} + +type AzIntstanceStatisDetail struct { + ZoneName string `json:"zoneName"` + Count int `json:"instanceCount"` + BccCount int `json:"bccInstanceCnt"` + BbcCount int `json:"bbcInstanceCnt"` + Total int `json:"instanceTotal"` + InstanceIds []string `json:"instanceIds"` + BccInstanceIds []string `json:"bccInstanceIds"` + BbcInstanceIds []string `json:"bbcInstanceIds"` +} + +type AzIntstanceStatis struct { + ZoneName string `json:"zoneName"` + Count int `json:"instanceCount"` + BbcCount int `json:"bbcInstanceCnt"` + BccCount int `json:"bccInstanceCnt"` + Total int `json:"instanceTotal"` +} + +type GetDeploySetResult struct { + DeploySetModel +} + +type RebuildBatchInstanceArgs struct { + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId"` + InstanceIds []string `json:"instanceIds"` + IsOpenHostEye bool `json:"isOpenHostEye"` + IsPreserveData bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type RebuildBatchInstanceArgsV2 struct { + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId"` + InstanceIds []string `json:"instanceIds"` + IsOpenHostEye *bool `json:"isOpenHostEye"` + IsPreserveData *bool `json:"isPreserveData"` + RaidId string `json:"raidId,omitempty"` + SysRootSize int `json:"sysRootSize,omitempty"` + RootPartitionType string `json:"rootPartitionType,omitempty"` + DataPartitionType string `json:"dataPartitionType,omitempty"` +} + +type ChangeToPrepaidRequest struct { + Duration int `json:"duration"` + RelationCds bool `json:"relationCds"` +} + +type ChangeToPrepaidResponse struct { + OrderId string `json:"orderId"` +} + +type BindTagsRequest struct { + ChangeTags []model.TagModel `json:"changeTags"` +} + +type UnBindTagsRequest struct { + ChangeTags []model.TagModel `json:"changeTags"` +} + +type CancelBidOrderRequest struct { + OrderId string `json:"orderId"` + ClientToken string `json:"-"` +} + +type CreateBidInstanceResult struct { + OrderId string `json:"orderId"` +} + +type ListFlavorSpecArgs struct { + ZoneName string `json:"zoneName,omitempty"` +} + +type ListFlavorSpecResult struct { + ZoneResources []ZoneResourceDetailSpec `json:"zoneResources"` +} + +type ZoneResourceDetailSpec struct { + ZoneName string `json:"zoneName"` + BccResources BccResources `json:"bccResources"` + EbcResources EbcResources `json:"ebcResources"` +} + +type BccResources struct { + FlavorGroups []FlavorGroup `json:"flavorGroups"` +} + +type FlavorGroup struct { + GroupId string `json:"groupId"` + Flavors []BccFlavor `json:"flavors"` +} + +type BccFlavor struct { + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + EphemeralDiskInGb int `json:"ephemeralDiskInGb"` + EphemeralDiskCount int `json:"ephemeralDiskCount"` + EphemeralDiskType string `json:"ephemeralDiskType"` + GpuCardType string `json:"gpuCardType"` + GpuCardCount int `json:"gpuCardCount"` + FpgaCardType string `json:"fpgaCardType"` + FpgaCardCount int `json:"fpgaCardCount"` + ProductType string `json:"productType"` + Spec string `json:"spec"` + SpecId string `json:"specId"` + CpuModel string `json:"cpuModel"` + CpuGHz string `json:"cpuGHz"` + NetworkBandwidth string `json:"networkBandwidth"` + NetworkPackage string `json:"networkPackage"` + NetEthQueueCount string `json:"netEthQueueCount"` + NetEthMaxQueueCount string `json:"netEthMaxQueueCount"` +} + +type EbcResources struct { + FlavorGroups []EbcFlavorGroup `json:"flavorGroups"` +} + +type EbcFlavorGroup struct { + GroupId string `json:"groupId"` + Flavors []EbcFlavor `json:"flavors"` +} + +type EbcFlavor struct { + CpuCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + EphemeralDiskInGb int `json:"ephemeralDiskInGb"` + EphemeralDiskCount string `json:"ephemeralDiskCount"` + EphemeralDiskType string `json:"ephemeralDiskType"` + GpuCardType string `json:"gpuCardType"` + GpuCardCount string `json:"gpuCardCount"` + FpgaCardType string `json:"fpgaCardType"` + FpgaCardCount string `json:"fpgaCardCount"` + ProductType string `json:"productType"` + Spec string `json:"spec"` + SpecId string `json:"specId"` + CpuModel string `json:"cpuModel"` + CpuGHz string `json:"cpuGHz"` + NetworkBandwidth string `json:"networkBandwidth"` + NetworkPackage string `json:"networkPackage"` +} + +type GetPriceBySpecArgs struct { + SpecId string `json:"specId"` + Spec string `json:"spec"` + PaymentTiming string `json:"paymentTiming"` + ZoneName string `json:"zoneName"` + PurchaseCount int `json:"purchaseCount,omitempty"` + PurchaseLength int `json:"purchaseLength"` +} + +type GetPriceBySpecResult struct { + Price []SpecIdPrices `json:"price"` +} + +type SpecIdPrices struct { + SpecId string `json:"specId"` + SpecPrices []SpecPrices `json:"specPrices"` +} + +type SpecPrices struct { + Spec string `json:"spec"` + Status string `json:"status"` + SpecPrice string `json:"specPrice"` +} + +type PrivateIP struct { + PublicIpAddress string `json:"publicIpAddress"` + Primary bool `json:"primary"` + PrivateIpAddress string `json:"privateIpAddress"` + Ipv6Address string `json:"ipv6Address"` +} + +type Eni struct { + EniId string `json:"eniId"` + Name string `json:"name"` + ZoneName string `json:"zoneName"` + Description string `json:"description"` + InstanceId string `json:"instanceId"` + MacAddress string `json:"macAddress"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Status string `json:"status"` + PrivateIpSet []PrivateIP `json:"privateIpSet"` +} + +type ListInstanceEniResult struct { + EniList []Eni `json:"enis"` +} + +type CreateKeypairArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description"` +} + +type ImportKeypairArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description"` + PublicKey string `json:"publicKey"` +} + +type KeypairModel struct { + KeypairId string `json:"keypairId"` + Name string `json:"name"` + Description string `json:"description"` + PublicKey string `json:"publicKey"` + RegionId string `json:"regionId"` + FingerPrint string `json:"fingerPrint"` + PrivateKey string `json:"privateKey"` + InstanceCount int `json:"instanceCount"` + CreatedTime string `json:"createdTime"` +} + +type KeypairResult struct { + Keypair KeypairModel `json:"keypair"` +} + +type AttackKeypairArgs struct { + KeypairId string `json:"keypairId"` + InstanceIds []string `json:"instanceIds"` +} + +type DetachKeypairArgs struct { + KeypairId string `json:"keypairId"` + InstanceIds []string `json:"instanceIds"` +} + +type DeleteKeypairArgs struct { + KeypairId string `json:"keypairId"` +} + +type ListKeypairArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + Name string `json:"name,omitempty"` +} + +type ListKeypairResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Keypairs []KeypairModel `json:"keypairs"` +} + +type RenameKeypairArgs struct { + Name string `json:"name"` + KeypairId string `json:"keypairId"` +} + +type KeypairUpdateDescArgs struct { + Description string `json:"description"` + KeypairId string `json:"keypairId"` +} + +type ListTypeZonesArgs struct { + InstanceType string `json:"instanceType"` + ProductType string `json:"productType"` + Spec string `json:"spec"` + SpecId string `json:"specId"` +} + +type BccCreateAutoRenewArgs struct { + InstanceId string `json:"instanceId"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` + RenewCds bool `json:"renewCds"` + RenewEip bool `json:"renewEip"` +} + +type BccDeleteAutoRenewArgs struct { + InstanceId string `json:"instanceId"` + RenewCds bool `json:"renewCds"` + RenewEip bool `json:"renewEip"` +} + +type DeleteInstanceIngorePaymentArgs struct { + InstanceId string `json:"instanceId"` + RelatedReleaseFlag bool `json:"relatedReleaseFlag"` + DeleteCdsSnapshotFlag bool `json:"deleteCdsSnapshotFlag"` + DeleteRelatedEnisFlag bool `json:"deleteRelatedEnisFlag"` + DeleteImmediate bool `json:"deleteImmediate"` +} + +type DeleteInstanceModel struct { + InstanceId string `json:"instanceId"` + Eip string `json:"eip"` + InsnapIds []string `json:"insnapIds"` + SnapshotIds []string `json:"snapshotIds"` + VolumeIds []string `json:"volumeIds"` +} + +type DeleteInstanceResult struct { + SuccessResources *DeleteInstanceModel `json:"successResources"` + FailResources *DeleteInstanceModel `json:"failResources"` +} + +type RecoveryInstanceArgs struct { + InstanceIds []RecoveryInstanceModel `json:"instanceIds"` +} + +type RecoveryInstanceModel struct { + InstanceId string `json:"instanceId"` +} + +type ListInstanceByInstanceIdArgs struct { + Marker string + MaxKeys int + InstanceIds []string `json:"instanceIds"` +} + +type ListInstancesResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []InstanceModel `json:"instances"` +} + +type VolumePrepayDeleteRequestArgs struct { + VolumeId string `json:"volumeId"` + RelatedReleaseFlag bool `json:"relatedReleaseFlag"` + DeleteImmediate bool `json:"deleteImmediate"` +} + +type VolumeDeleteResultResponse struct { + SuccessResources VolumeDeleteResultModel `json:"successResources"` + FailResources VolumeDeleteResultModel `json:"failResources"` +} + +type VolumeDeleteResultModel struct { + VolumeIds []string `json:"volumeIds"` +} + +type DeletionProtectionArgs struct { + DeletionProtection int `json:"deletionProtection"` +} + +type BatchDeleteInstanceWithRelateResourceArgs struct { + RelatedReleaseFlag bool `json:"relatedReleaseFlag"` + DeleteCdsSnapshotFlag bool `json:"deleteCdsSnapshotFlag"` + BccRecycleFlag bool `json:"bccRecycleFlag"` + DeleteRelatedEnisFlag bool `json:"deleteRelatedEnisFlag"` + InstanceIds []string `json:"instanceIds"` +} + +type BatchStartInstanceArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type BatchStopInstanceArgs struct { + ForceStop bool `json:"forceStop"` + StopWithNoCharge bool `json:"stopWithNoCharge"` + InstanceIds []string `json:"instanceIds"` +} + +type ListInstanceTypeArgs struct { + ZoneName string `json:"zoneName"` +} + +type ListInstanceTypeResults struct { + ZoneInstanceTypes []ZoneInstanceTypes `json:"zoneInstanceTypes"` +} + +type ZoneInstanceTypes struct { + ZoneName string `json:"zoneName"` + InstanceTypes []string `json:"instanceTypes"` +} + +type ListIdMappingArgs struct { + IdType string `json:"idType"` + ObjectType string `json:"objectType"` + InstanceIds []string `json:"instanceIds"` +} + +type ListIdMappingResults struct { + IdMapping []IdMapping `json:"mappings"` +} + +type IdMapping struct { + Uuid string `json:"uuid"` + Id string `json:"id"` +} + +type BatchResizeInstanceArgs struct { + Spec string `json:"spec"` + InstanceIdList []string `json:"instanceIdList"` +} + +type BatchResizeInstanceResults struct { + OrderUuidResults []string `json:"orderUuidResults"` +} + +// UpdateSecurityGroupRuleArgs defines the structure of input parameters for the UpdateSecurityGroupRule api +type UpdateSecurityGroupRuleArgs struct { + SgVersion int64 `json:"sgVersion,omitempty"` + SecurityGroupRuleId string `json:"securityGroupRuleId"` + Remark *string `json:"remark,omitempty"` + PortRange *string `json:"portRange,omitempty"` + SourceIp *string `json:"sourceIp,omitempty"` + SourceGroupId *string `json:"sourceGroupId,omitempty"` + DestIp *string `json:"destIp,omitempty"` + DestGroupId *string `json:"destGroupId,omitempty"` + Protocol *string `json:"protocol,omitempty"` +} + +// DeleteSecurityGroupRuleArgs defines the structure of input parameters for the DeleteSecurityGroupRule api +type DeleteSecurityGroupRuleArgs struct { + SgVersion int64 `json:"sgVersion,omitempty"` + SecurityGroupRuleId string `json:"securityGroupRuleId"` +} + +type GetInstanceDeleteProgressArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type Tag struct { + TagKey string `json:"tagKey"` + TagValue string `json:"tagValue"` +} + +type TagVolumeArgs struct { + ChangeTags []Tag `json:"changeTags"` + RelationTag bool `json:"relationTag"` +} + +type Volume struct { + VolumeId string `json:"volumeId"` + SizeInGB int `json:"sizeInGb"` +} + +type ListAvailableResizeSpecsArgs struct { + Spec string `json:"spec"` + SpecId string `json:"specId"` + Zone string `json:"zone"` + InstanceIdList []string `json:"instanceIdList"` +} + +type ListAvailableResizeSpecResults struct { + SpecList []string `json:"specList"` +} + +type BatchChangeInstanceToPrepayArgs struct { + Config []PrepayConfig `json:"config"` +} + +type PrepayConfig struct { + InstanceId string `json:"instanceId"` + Duration int `json:"duration"` + RelationCds bool `json:"relationCds"` + CdsList []string `json:"cdsList"` + AutoPay bool `json:"autoPay"` +} + +type BatchChangeInstanceToPostpayArgs struct { + Config []PostpayConfig `json:"config"` +} + +type PostpayConfig struct { + InstanceId string `json:"instanceId"` + RelationCds bool `json:"relationCds"` + CdsList []string `json:"cdsList"` +} + +type BatchChangeInstanceBillingMethodResult struct { + OrderId string `json:"orderId"` +} + +type Role struct { + RoleName string `json:"roleName"` +} + +type ListInstanceRolesResult struct { + Roles []Role `json:"roles"` +} + +type BindInstanceRoleResult struct { + FailInstances []FailInstances `json:"failInstances"` + InstanceRoleAssociations []InstanceRoleAssociations `json:"instanceRoleAssociations"` +} + +type FailInstances struct { + InstanceId string `json:"instanceId"` + FailMessage string `json:"failMessage"` +} + +type InstanceRoleAssociations struct { + InstanceID string `json:"instanceId"` +} + +type BindInstanceRoleArgs struct { + RoleName string `json:"roleName"` + Instances []Instances `json:"instances"` +} + +type Instances struct { + InstanceId string `json:"instanceId"` +} + +type UnBindInstanceRoleArgs struct { + RoleName string `json:"roleName"` + Instances []Instances `json:"instances"` +} + +type UnBindInstanceRoleResult struct { + FailInstances []FailInstances `json:"failInstances"` + InstanceRoleAssociations []InstanceRoleAssociations `json:"instanceRoleAssociations"` +} + +type DeleteIpv6Args struct { + InstanceId string `json:"instanceId"` + Reboot bool `json:"reboot"` +} + +type AddIpv6Args struct { + InstanceId string `json:"instanceId"` + Ipv6Address string `json:"ipv6Address"` + Reboot bool `json:"reboot"` +} + +type AddIpv6Result struct { + Ipv6Address string `json:"ipv6Address"` +} + +type RemoteCopySnapshotArgs struct { + ClientToken string `json:"-"` + DestRegionInfos []DestRegionInfo `json:"destRegionInfos"` +} + +type DestRegionInfo struct { + Name string `json:"name"` + DestRegion string `json:"destRegion"` +} + +type RemoteCopySnapshotResult struct { + Result []RemoteCopySnapshotResultItem `json:"result"` +} + +type RemoteCopySnapshotResultItem struct { + Region string `json:"region"` + SnapshotID string `json:"snapshotId"` +} + +type ImportCustomImageArgs struct { + OsName string `json:"osName"` + OsArch string `json:"osArch"` + OsType string `json:"osType"` + OsVersion string `json:"osVersion"` + Name string `json:"name"` + BosURL string `json:"bosUrl"` +} + +type ImportCustomImageResult struct { + Id string `json:"id"` +} + +type GetAvailableImagesBySpecArg struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + Spec string `json:"spec"` + OsName string `json:"osName"` +} + +type GetAvailableImagesBySpecResult struct { + IsTruncated bool `json:"isTruncated"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + Images ImageArg `json:"images"` +} + +type ImageArg []struct { + ImageID string `json:"imageId"` + ImageName string `json:"imageName"` + OsType string `json:"osType"` + OsVersion string `json:"osVersion"` + OsArch string `json:"osArch"` + OsName string `json:"osName"` + OsLang string `json:"osLang"` + MinSizeInGiB int `json:"minSizeInGiB"` +} diff --git a/bce-sdk-go/services/bcc/api/other.go b/bce-sdk-go/services/bcc/api/other.go new file mode 100644 index 0000000..da3498a --- /dev/null +++ b/bce-sdk-go/services/bcc/api/other.go @@ -0,0 +1,236 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// other.go - the other APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListSpec - get specification list information of the instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListSpecResult: result of the specifications +// - error: nil if success otherwise the specific error +func ListSpec(cli bce.Client) (*ListSpecResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSpecUri()) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListSpecResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListZone - get the available zone list in the current region +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListZoneResult: result of the available zones +// - error: nil if success otherwise the specific error +func ListZone(cli bce.Client) (*ListZoneResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getZoneUri()) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListZoneResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListFlavorSpec - get the specified flavor list +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list the specified flavor +// +// RETURNS: +// - *ListFlavorSpecResult: result of the specified flavor list +// - error: nil if success otherwise the specific error +func ListFlavorSpec(cli bce.Client, args *ListFlavorSpecArgs) (*ListFlavorSpecResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getFlavorSpecUri()) + req.SetMethod(http.GET) + + if args != nil { + if len(args.ZoneName) != 0 { + req.SetParam("zoneName", args.ZoneName) + } + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListFlavorSpecResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetPriceBySpec - get the price information of specified instance. +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get the price information of specified instance. +// +// RETURNS: +// - *GetPriceBySpecResult: result of the specified instance's price information +// - error: nil if success otherwise the specific error +func GetPriceBySpec(cli bce.Client, args *GetPriceBySpecArgs) (*GetPriceBySpecResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getPriceBySpecUri()) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetPriceBySpecResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListTypeZones - get the available zone list in the current region +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListZoneResult: result of the available zones +// - error: nil if success otherwise the specific error +func ListTypeZones(cli bce.Client, args *ListTypeZonesArgs) (*ListTypeZonesResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getInstanceTypeZoneUri()) + req.SetMethod(http.GET) + if args != nil { + if len(args.InstanceType) != 0 { + req.SetParam("instanceType", args.InstanceType) + } + if len(args.ProductType) != 0 { + req.SetParam("productType", args.ProductType) + } + if len(args.SpecId) != 0 { + req.SetParam("specId", args.SpecId) + } + if len(args.Spec) != 0 { + req.SetParam("spec", args.Spec) + } + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListTypeZonesResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListInstanceEni - get the eni list of the bcc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the bcc instance id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ListInstanceEnis(cli bce.Client, instanceId string) (*ListInstanceEniResult, error) { + req := &bce.BceRequest{} + req.SetUri(getInstanceEniUri(instanceId)) + req.SetMethod(http.GET) + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListInstanceEniResult{} + print(jsonBody) + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/bcc/api/securityGroup.go b/bce-sdk-go/services/bcc/api/securityGroup.go new file mode 100644 index 0000000..d142bba --- /dev/null +++ b/bce-sdk-go/services/bcc/api/securityGroup.go @@ -0,0 +1,270 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// securityGroup.go - the securityGroup APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateSecurityGroup - create a security group and related rules +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create security group +// - : +// +// RETURNS: +// - *CreateSecurityGroupResult: result of the security group id +// - error: nil if success otherwise the specific error +func CreateSecurityGroup(cli bce.Client, args *CreateSecurityGroupArgs) (*CreateSecurityGroupResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSecurityGroupUri()) + req.SetMethod(http.POST) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateSecurityGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListSecurityGroup - list all security groups with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: the arguments to list security groups +// +// RETURNS: +// - *ListSecurityGroupResult: result of the security group list +// - error: nil if success otherwise the specific error +func ListSecurityGroup(cli bce.Client, queryArgs *ListSecurityGroupArgs) (*ListSecurityGroupResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSecurityGroupUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.InstanceId) != 0 { + req.SetParam("instanceId", queryArgs.InstanceId) + } + if len(queryArgs.VpcId) != 0 { + req.SetParam("vpcId", queryArgs.VpcId) + } + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListSecurityGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// AuthorizeSecurityGroupRule - authorize a rule of security group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - securityGroupId: id of the security group +// - args: arguments to authorize security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func AuthorizeSecurityGroupRule(cli bce.Client, securityGroupId string, args *AuthorizeSecurityGroupArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSecurityGroupUriWithId(securityGroupId)) + req.SetMethod(http.PUT) + + if args.ClientToken != "" { + req.SetParam("clientToken", args.ClientToken) + } + req.SetParam("authorizeRule", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// RevokeSecurityGroupRule - revoke a rule of security group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - securityGroupId: id of the security group +// - args: arguments to revoke security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RevokeSecurityGroupRule(cli bce.Client, securityGroupId string, args *RevokeSecurityGroupArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSecurityGroupUriWithId(securityGroupId)) + req.SetMethod(http.PUT) + + req.SetParam("revokeRule", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteSecurityGroup - delete a security group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - securityGroupId: id of the security group to be deleted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteSecurityGroup(cli bce.Client, securityGroupId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSecurityGroupUriWithId(securityGroupId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteSecurityGroupRule - delete a security group rule +// +// PARAMS: +// - securityGroupRuleId: the id of the specific security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteSecurityGroupRule(cli bce.Client, args *DeleteSecurityGroupRuleArgs) error { + builder := bce.NewRequestBuilder(cli). + WithURL(getSecurityGroupRuleUri() + "/" + args.SecurityGroupRuleId). + WithMethod(http.DELETE) + if args.SgVersion != 0 { + builder.WithQueryParamFilter("sgVersion", strconv.FormatInt(args.SgVersion, 10)) + } + return builder.Do() +} + +// UpdateSecurityGroupRule - update security group rule with the specific parameters +// +// PARAMS: +// - args: the arguments to update the specific security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateSecurityGroupRule(cli bce.Client, args *UpdateSecurityGroupRuleArgs) error { + if args == nil { + return fmt.Errorf("the UpdateSecurityGroupRuleArgs cannot be nil") + } + builder := bce.NewRequestBuilder(cli). + WithURL(getSecurityGroupRuleUri() + "/update"). + WithMethod(http.PUT) + if args.SgVersion != 0 { + builder.WithQueryParamFilter("sgVersion", strconv.FormatInt(args.SgVersion, 10)) + } + return builder.WithBody(args).Do() +} diff --git a/bce-sdk-go/services/bcc/api/snapshot.go b/bce-sdk-go/services/bcc/api/snapshot.go new file mode 100644 index 0000000..e57ce08 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/snapshot.go @@ -0,0 +1,318 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// snapshot.go - the snapshot APIs definition supported by the BCC service + +// Package api defines all APIs supported by the BCC service of BCE. +package api + +import ( + "encoding/json" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateSnapshot - create a snapshot for specified volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create snapshot +// +// RETURNS: +// - *CreateSnapshotResult: result of the snapshot id newly created +// - error: nil if success otherwise the specific error +func CreateSnapshot(cli bce.Client, args *CreateSnapshotArgs) (*CreateSnapshotResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSnapshotUri()) + req.SetMethod(http.POST) + + if len(args.ClientToken) != 0 { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateSnapshotResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListSnapshot - list all snapshots with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: arguments to list snapshots +// +// RETURNS: +// - *ListSnapshotResult: result of the snapshot list +// - error: nil if success otherwise the specific error +func ListSnapshot(cli bce.Client, queryArgs *ListSnapshotArgs) (*ListSnapshotResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSnapshotUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListSnapshotResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListSnapshotChain - list all snapshot chains with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryArgs: arguments to list snapshot chains +// +// RETURNS: +// - *ListSnapshotChainResult: result of the snapshot chain list +// - error: nil if success otherwise the specific error +func ListSnapshotChain(cli bce.Client, queryArgs *ListSnapshotChainArgs) (*ListSnapshotChainResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSnapshotChainUri()) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.OrderBy) != 0 { + req.SetParam("orderBy", queryArgs.OrderBy) + } + if len(queryArgs.Order) != 0 { + req.SetParam("order", queryArgs.Order) + } + if queryArgs.PageSize != 0 { + req.SetParam("pageSize", strconv.Itoa(queryArgs.PageSize)) + } + if queryArgs.PageNo != 0 { + req.SetParam("pageNo", strconv.Itoa(queryArgs.PageNo)) + } + if len(queryArgs.VolumeId) != 0 { + req.SetParam("volumeId", queryArgs.VolumeId) + } + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListSnapshotChainResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetSnapshotDetail - get details of the specified snapshot +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - snapshotId: id of the snapshot +// +// RETURNS: +// - *GetSnapshotDetailResult: result of snapshot details +// - error: nil if success otherwise the specific error +func GetSnapshotDetail(cli bce.Client, snapshotId string) (*GetSnapshotDetailResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSnapshotUriWithId(snapshotId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &GetSnapshotDetailResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// DeleteSnapshot - delete a snapshot +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - snapshotId: id of the snapshot to be deleted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteSnapshot(cli bce.Client, snapshotId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getSnapshotUriWithId(snapshotId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + return nil +} + +func TagSnapshotChain(cli bce.Client, chainId string, args *TagVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getTagSnapshotChainUri(chainId)) + req.SetMethod(http.PUT) + req.SetParam("bind", "") + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func UntagSnapshotChain(cli bce.Client, chainId string, args *TagVolumeArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getUntagSnapshotChainUri(chainId)) + req.SetMethod(http.PUT) + req.SetParam("unbind", "") + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func CreateRemoteCopySnapshot(cli bce.Client, snapshotId string, args *RemoteCopySnapshotArgs) ( + *RemoteCopySnapshotResult, error) { + + // Build the request + req := &bce.BceRequest{} + req.SetUri(getRemoteCopySnapshotUri(snapshotId)) + req.SetMethod(http.PUT) + + if len(args.ClientToken) != 0 { + req.SetParam("clientToken", args.ClientToken) + } + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &RemoteCopySnapshotResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} diff --git a/bce-sdk-go/services/bcc/api/util.go b/bce-sdk-go/services/bcc/api/util.go new file mode 100644 index 0000000..a36a8c0 --- /dev/null +++ b/bce-sdk-go/services/bcc/api/util.go @@ -0,0 +1,437 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BCC service +package api + +import ( + "encoding/hex" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +const ( + URI_PREFIXV3 = bce.URI_PREFIX + "v3" + URI_PREFIXV2 = bce.URI_PREFIX + "v2" + URI_PREFIXV1 = bce.URI_PREFIX + "v1" + + REQUEST_ASP_URI = "/asp" + REQUEST_BATCHADDIP_URI = "/batchAddIp" + REQUEST_BATCHDELIP_URI = "/batchDelIp" + REQUEST_CREATE_URI = "/create" + REQUEST_UPDATE_URI = "/updateRelation" + REQUEST_DEL_URI = "/delRelation" + REQUEST_DEPLOYSET_URI = "/deployset" + REQUEST_IMAGE_URI = "/image" + REQUEST_IMAGE_SHAREDUSER_URI = "/sharedUsers" + REQUEST_IMAGE_OS_URI = "/os" + REQUEST_INSTANCE_URI = "/instance" + REQUEST_INSTANCE_LABEL_URI = "/instanceByLabel" + REQUEST_LIST_URI = "/list" + REQUEST_SECURITYGROUP_URI = "/securityGroup" + REQUEST_SNAPSHOT_URI = "/snapshot" + REQUEST_CHAIN_URI = "/chain" + REQUEST_SPEC_URI = "/instance/spec" + REQUEST_SUBNET_URI = "/subnet" + REQUEST_VPC_URI = "/vpc" + REQUEST_VNC_SUFFIX = "/vnc" + REQUEST_VOLUME_URI = "/volume" + REQUEST_ZONE_URI = "/zone" + REQUEST_RECYCLE = "/recycle" + REQUEST_DELETEPREPAY = "/volume/deletePrepay" + // + REQUEST_FLAVOR_SPEC_URI = "/instance/flavorSpec" + REQUEST_PRICE_URI = "/price" + REQUEST_AUTO_RENEW_URI = "/autoRenew" + REQUEST_CANCEL_AUTO_RENEW_URI = "/cancelAutoRenew" + REQUEST_BID_PRICE_URI = "/bidPrice" + REQUEST_BID_FLAVOR_URI = "/bidFlavor" + // + REQUEST_INSTANCE_PRICE_URI = "/instance/price" + REQUEST_INSTANCE_BY_SPEC_URI = "/instanceBySpec" + REQUEST_VOLUME_DISK_URI = "/volume/disk" + REQUEST_TYPE_ZONE_URI = "/instance/flavorZones" + REQUEST_ENI_URI = "/eni" + REQUEST_KEYPAIR_URI = "/keypair" + REQUEST_REBUILD_URI = "/rebuild" + REQUEST_TAG_URI = "/tag" + REQUEST_NOCHARGE_URI = "/noCharge" + REQUEST_BID_URI = "/bid" + REQUEST_RECOVERY_URI = "/recovery" + REQUEST_CANCEL_BIDORDER_URI = "/cancelBidOrder" + REQUEST_BATCH_CREATE_AUTORENEW_RULES_URI = "/batchCreateAutoRenewRules" + REQUEST_BATCH_Delete_AUTORENEW_RULES_URI = "/batchDeleteAutoRenewRules" + REQUEST_GET_ALL_STOCKS = "/getAllStocks" + REQUEST_GET_STOCK_WITH_DEPLOYSET = "/getStockWithDeploySet" + REQUEST_GET_STOCK_WITH_SPEC = "/getStockWithSpec" + REQUEST_DELETION_PROTECTION = "/deletionProtection" +) + +func getInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI +} + +func getInstanceByLabelUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_LABEL_URI +} + +func getInstanceUriV3() string { + return URI_PREFIXV3 + REQUEST_INSTANCE_URI +} + +func getRecycleInstanceListUri() string { + return URI_PREFIXV2 + REQUEST_RECYCLE + REQUEST_INSTANCE_URI +} + +func getServersByMarkerV3Uri() string { + return URI_PREFIXV3 + REQUEST_INSTANCE_URI + REQUEST_LIST_URI +} + +func getInstanceBySpecUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_BY_SPEC_URI +} + +func getInstanceUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/" + id +} + +func getRecoveryInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_RECOVERY_URI +} + +func getBatchAddIpUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BATCHADDIP_URI +} + +func getBatchDelIpUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BATCHDELIP_URI +} + +func getBidInstancePriceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BID_PRICE_URI +} + +func listBidFlavorUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BID_FLAVOR_URI +} + +func getInstanceVNCUri(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/" + id + REQUEST_VNC_SUFFIX +} + +func getInstanceDeletionProtectionUri(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/" + id + REQUEST_DELETION_PROTECTION +} + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} + +func getVolumeUri() string { + return URI_PREFIXV2 + REQUEST_VOLUME_URI +} + +func getVolumeV3Uri() string { + return URI_PREFIXV3 + REQUEST_VOLUME_URI +} + +func getVolumeUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_VOLUME_URI + "/" + id +} + +func getDeletePrepayVolumeUri() string { + return URI_PREFIXV2 + REQUEST_DELETEPREPAY +} + +func getVolumeV3UriWithId(id string) string { + return URI_PREFIXV3 + REQUEST_VOLUME_URI + "/" + id +} + +func getAutoRenewVolumeUri() string { + return URI_PREFIXV2 + REQUEST_VOLUME_URI + REQUEST_AUTO_RENEW_URI +} + +func getCancelAutoRenewVolumeUri() string { + return URI_PREFIXV2 + REQUEST_VOLUME_URI + REQUEST_CANCEL_AUTO_RENEW_URI +} +func getAvailableDiskInfo() string { + return URI_PREFIXV2 + REQUEST_VOLUME_DISK_URI +} + +func getSecurityGroupUri() string { + return URI_PREFIXV2 + REQUEST_SECURITYGROUP_URI +} + +func getSecurityGroupUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_SECURITYGROUP_URI + "/" + id +} + +func getSecurityGroupRuleUri() string { + return URI_PREFIXV2 + REQUEST_SECURITYGROUP_URI + "/rule" +} + +func getImageUri() string { + return URI_PREFIXV2 + REQUEST_IMAGE_URI +} + +func getImageUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_IMAGE_URI + "/" + id +} + +func getImageSharedUserUri(id string) string { + return URI_PREFIXV2 + REQUEST_IMAGE_URI + "/" + id + REQUEST_IMAGE_SHAREDUSER_URI +} + +func getImageOsUri() string { + return URI_PREFIXV2 + REQUEST_IMAGE_URI + REQUEST_IMAGE_OS_URI +} + +func getSnapshotUri() string { + return URI_PREFIXV2 + REQUEST_SNAPSHOT_URI +} + +func getSnapshotChainUri() string { + return URI_PREFIXV2 + REQUEST_SNAPSHOT_URI + REQUEST_CHAIN_URI +} + +func getSnapshotUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_SNAPSHOT_URI + "/" + id +} + +func getASPUri() string { + return URI_PREFIXV2 + REQUEST_ASP_URI +} + +func getASPUriWithId(id string) string { + return URI_PREFIXV2 + REQUEST_ASP_URI + "/" + id +} + +func getSpecUri() string { + return URI_PREFIXV2 + REQUEST_SPEC_URI +} + +func getZoneUri() string { + return URI_PREFIXV2 + REQUEST_ZONE_URI +} + +func getPriceBySpecUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_PRICE_URI +} + +func getInstanceTypeZoneUri() string { + return URI_PREFIXV1 + REQUEST_TYPE_ZONE_URI +} + +func getChangeSubnetUri() string { + return URI_PREFIXV2 + REQUEST_SUBNET_URI + "/changeSubnet" +} + +func getChangeVpcUri() string { + return URI_PREFIXV2 + REQUEST_VPC_URI + "/changeVpc" +} + +func getInstanceEniUri(instanceId string) string { + return URI_PREFIXV2 + REQUEST_ENI_URI + "/" + instanceId +} + +func getKeypairUri() string { + return URI_PREFIXV2 + REQUEST_KEYPAIR_URI +} + +func getKeypairWithId(id string) string { + return URI_PREFIXV2 + REQUEST_KEYPAIR_URI + "/" + id +} + +func getAllStocks() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_GET_ALL_STOCKS +} + +func getStockWithDeploySet() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_GET_STOCK_WITH_DEPLOYSET +} + +func getStockWithSpec() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_GET_STOCK_WITH_SPEC +} + +func getCreateInstanceStock() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/stock/createInstance" +} + +func getResizeInstanceStock() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/stock/resizeInstance" +} + +func getFlavorSpecUri() string { + return URI_PREFIXV2 + REQUEST_FLAVOR_SPEC_URI +} + +func getResizeInstanceBySpec(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_BY_SPEC_URI + "/" + id +} + +func getRebuildBatchInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_REBUILD_URI +} + +func getChangeToPrepaidUri(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/" + id +} + +func getbindInstanceToTagsUri(id string) string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/" + id + REQUEST_TAG_URI +} + +func GetInstanceNoChargeListUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_NOCHARGE_URI +} + +func GetCreateBidInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BID_URI +} + +func GetCancelBidOrderUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_CANCEL_BIDORDER_URI +} + +func getBatchCreateAutoRenewRulesUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BATCH_CREATE_AUTORENEW_RULES_URI +} + +func getBatchDeleteAutoRenewRulesUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + REQUEST_BATCH_Delete_AUTORENEW_RULES_URI +} + +func getDeleteInstanceDeleteIngorePaymentUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/delete" +} + +func getDeleteRecycledInstanceUri(id string) string { + return URI_PREFIXV2 + "/recycle" + REQUEST_INSTANCE_URI + "/" + id +} + +func getListInstancesByIdsUrl() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/listByInstanceId" +} + +func getBatchDeleteInstanceWithRelatedResourceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/batchDelete" +} + +func getBatchStartInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/batchAction" +} + +func getBatchStopInstanceUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/batchAction" +} + +func getListInstanceTypesUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/types" +} + +func getListIdMappingsUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/id/mapping" +} + +func getBatchResizeInstanceUri() string { + return URI_PREFIXV2 + "/instanceBatchBySpec" +} + +func getInstanceDeleteProgress() string { + return URI_PREFIXV2 + "/instance/deleteProgress" +} + +func getTagVolumeUri(id string) string { + return URI_PREFIXV2 + REQUEST_VOLUME_URI + "/" + id + REQUEST_TAG_URI +} + +func getUntagVolumeUri(id string) string { + return URI_PREFIXV2 + REQUEST_VOLUME_URI + "/" + id + REQUEST_TAG_URI +} + +func getTagSnapshotChainUri(id string) string { + return URI_PREFIXV2 + REQUEST_SNAPSHOT_URI + REQUEST_CHAIN_URI + "/" + id + REQUEST_TAG_URI +} + +func getUntagSnapshotChainUri(id string) string { + return URI_PREFIXV2 + REQUEST_SNAPSHOT_URI + REQUEST_CHAIN_URI + "/" + id + REQUEST_TAG_URI +} + +func getListInstancesByOrderIdUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/getServersByOrderId" +} + +func getCreateInstanceReturnOrderIdUri() string { + return URI_PREFIXV2 + "/instanceReturnOrderId" +} + +func getListAvailableResizeSpecsUri() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI +} + +func getBatchChangeInstanceToPrepay() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/batch/charging" +} + +func getBatchChangeInstanceToPostpay() string { + return URI_PREFIXV2 + REQUEST_INSTANCE_URI + "/batch/charging" +} + +func getResizeInstanceReturnOrderId(instanceId string) string { + return URI_PREFIXV2 + "/instanceReturnOrderId" + instanceId +} + +func listInstanceRoles() string { + return URI_PREFIXV2 + "/instance/role/list" +} + +func postInstanceRole() string { + return URI_PREFIXV2 + "/instance/role" +} + +func deleteIpv6() string { + return URI_PREFIXV2 + "/instance/delIpv6" +} + +func addIpv6() string { + return URI_PREFIXV2 + "/instance/addIpv6" +} + +func getImageToTagsUri(id string) string { + return URI_PREFIXV2 + REQUEST_IMAGE_URI + "/" + id + REQUEST_TAG_URI +} + +func getRemoteCopySnapshotUri(id string) string { + return URI_PREFIXV2 + REQUEST_SNAPSHOT_URI + "/remote_copy/" + id +} + +func getImportCustomImageUri() string { + return URI_PREFIXV2 + "/image/import" +} + +func getAvailableImagesBySpecUri() string { + return URI_PREFIXV2 + "/image/getAvailableImagesBySpec" +} diff --git a/bce-sdk-go/services/bcc/client.go b/bce-sdk-go/services/bcc/client.go new file mode 100644 index 0000000..21c095e --- /dev/null +++ b/bce-sdk-go/services/bcc/client.go @@ -0,0 +1,2270 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BOS service + +// Package bcc defines the BCC services of BCE. The supported APIs are all defined in sub-package + +package bcc + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +const DEFAULT_SERVICE_DOMAIN = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + +// Client of BCC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the BCC service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endPoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endPoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// CreateInstance - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstance(args *api.CreateInstanceArgs) (*api.CreateInstanceResult, error) { + if len(args.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + + args.AdminPass = cryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateInstance(c, args, body) +} + +// CreateInstanceV2 - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstanceV2(argsV2 *api.CreateInstanceArgsV2) (*api.CreateInstanceResult, error) { + if len(argsV2.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, argsV2.AdminPass) + if err != nil { + return nil, err + } + argsV2.AdminPass = cryptedPass + } + defaultTrue := true + defaultFalse := false + if argsV2.IsOpenHostnameDomain == nil { + argsV2.IsOpenHostnameDomain = &defaultFalse + } + if argsV2.AutoSeqSuffix == nil { + argsV2.AutoSeqSuffix = &defaultFalse + } + if argsV2.IsOpenHostEye == nil { + argsV2.IsOpenHostEye = &defaultTrue + } + if argsV2.RelationTag == nil { + argsV2.RelationTag = &defaultFalse + } + if argsV2.CdsAutoRenew == nil { + argsV2.CdsAutoRenew = &defaultFalse + } + if argsV2.IsOpenIpv6 == nil { + argsV2.IsOpenIpv6 = &defaultFalse + } + jsonBytes, err := json.Marshal(argsV2) + if err != nil { + return nil, err + } + args := &api.CreateInstanceArgs{} + err = json.Unmarshal(jsonBytes, args) + if err != nil { + return nil, err + } + args.ClientToken = argsV2.ClientToken + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateInstance(c, args, body) +} + +// CreateInstance - create an instance with the specific parameters and support the passing in of label +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstanceByLabel(args *api.CreateSpecialInstanceBySpecArgs) (*api.CreateInstanceResult, error) { + if len(args.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + + args.AdminPass = cryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateInstanceByLabel(c, args, body) +} + +// CreateInstanceBySpec - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceBySpecResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstanceBySpec(args *api.CreateInstanceBySpecArgs) (*api.CreateInstanceBySpecResult, error) { + if len(args.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + + args.AdminPass = cryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateInstanceBySpec(c, args, body) +} + +// CreateInstanceBySpecV2 - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceBySpecResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstanceBySpecV2(argsV2 *api.CreateInstanceBySpecArgsV2) (*api.CreateInstanceBySpecResult, error) { + if len(argsV2.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, argsV2.AdminPass) + if err != nil { + return nil, err + } + + argsV2.AdminPass = cryptedPass + } + defaultTrue := true + defaultFalse := false + if argsV2.IsOpenHostnameDomain == nil { + argsV2.IsOpenHostnameDomain = &defaultFalse + } + if argsV2.AutoSeqSuffix == nil { + argsV2.AutoSeqSuffix = &defaultFalse + } + if argsV2.IsOpenHostEye == nil { + argsV2.IsOpenHostEye = &defaultTrue + } + if argsV2.RelationTag == nil { + argsV2.RelationTag = &defaultFalse + } + if argsV2.CdsAutoRenew == nil { + argsV2.CdsAutoRenew = &defaultFalse + } + if argsV2.IsOpenIpv6 == nil { + argsV2.IsOpenIpv6 = &defaultFalse + } + + jsonBytes, jsonErr := json.Marshal(argsV2) + if jsonErr != nil { + return nil, jsonErr + } + + args := &api.CreateInstanceBySpecArgs{} + err := json.Unmarshal(jsonBytes, args) + if err != nil { + return nil, err + } + args.ClientToken = argsV2.ClientToken + + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateInstanceBySpec(c, args, body) +} + +// CreateInstanceV3 - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceV3Result: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstanceV3(args *api.CreateInstanceV3Args) (*api.CreateInstanceV3Result, error) { + if len(args.Password) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.Password) + if err != nil { + return nil, err + } + + args.Password = cryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateInstanceV3(c, args, body) +} + +// ListInstances - list all instance with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance +// +// RETURNS: +// - *api.ListInstanceResult: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) ListInstances(args *api.ListInstanceArgs) (*api.ListInstanceResult, error) { + return api.ListInstances(c, args) +} + +// ListRecycleInstances - list all instance in the recycle bin with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance in the recycle bin +// +// RETURNS: +// - *api.ListRecycleInstanceResult: the result of list Instance in the recycle bin +// - error: nil if success otherwise the specific error +func (c *Client) ListRecycleInstances(args *api.ListRecycleInstanceArgs) (*api.ListRecycleInstanceResult, error) { + return api.ListRecycleInstances(c, args) +} + +// ListServersByMarkerV3 - list all instance with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance +// +// RETURNS: +// - *api.LogicMarkerResultResponseV3: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) ListServersByMarkerV3(args *api.ListServerRequestV3Args) (*api.LogicMarkerResultResponseV3, error) { + return api.ListServersByMarkerV3(c, args) +} + +// GetInstanceDetail - get a specific instance detail info +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - *api.GetInstanceDetailResult: the result of get instance detail info +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceDetail(instanceId string) (*api.GetInstanceDetailResult, error) { + return api.GetInstanceDetail(c, instanceId) +} + +func (c *Client) GetInstanceDetailWithDeploySet(instanceId string, isDeploySet bool) (*api.GetInstanceDetailResult, + error) { + return api.GetInstanceDetailWithDeploySet(c, instanceId, isDeploySet) +} + +func (c *Client) GetInstanceDetailWithDeploySetAndFailed(instanceId string, + isDeploySet bool, containsFailed bool) (*api.GetInstanceDetailResult, + error) { + return api.GetInstanceDetailWithDeploySetAndFailed(c, instanceId, isDeploySet, containsFailed) +} + +// DeleteInstance - delete a specific instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstance(instanceId string) error { + return api.DeleteInstance(c, instanceId) +} + +// AutoReleaseInstance - set releaseTime of a postpay instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - releaseTime: an UTC string,eg:"2021-05-01T07:58:09Z" +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AutoReleaseInstance(instanceId string, releaseTime string) error { + args := &api.AutoReleaseArgs{ + ReleaseTime: releaseTime, + } + return api.AutoReleaseInstance(c, instanceId, args) +} + +// ResizeInstance - resize a specific instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to resize a specific instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeInstance(instanceId string, args *api.ResizeInstanceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.ResizeInstance(c, instanceId, args.ClientToken, body) +} + +// RebuildInstance - rebuild an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to rebuild an instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebuildInstance(instanceId string, args *api.RebuildInstanceArgs) error { + if len(args.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return err + } + args.AdminPass = cryptedPass + } + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.RebuildInstance(c, instanceId, body) +} + +func (c *Client) RebuildInstanceV2(instanceId string, argsV2 *api.RebuildInstanceArgsV2) error { + if len(argsV2.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, argsV2.AdminPass) + if err != nil { + return err + } + argsV2.AdminPass = cryptedPass + } + + defaultTrue := true + if argsV2.IsPreserveData == nil { + argsV2.IsPreserveData = &defaultTrue + } + if argsV2.IsOpenHostEye == nil { + argsV2.IsOpenHostEye = &defaultTrue + } + + argsV2JsonBytes, err := json.Marshal(argsV2) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(argsV2JsonBytes) + if err != nil { + return err + } + + return api.RebuildInstance(c, instanceId, body) +} + +// StartInstance - start an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StartInstance(instanceId string) error { + return api.StartInstance(c, instanceId) +} + +// StopInstance - stop an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - forceStop: choose to force stop an instance or not +// - stopWithNoCharge: choose to stop with nocharge an instance or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StopInstanceWithNoCharge(instanceId string, forceStop bool, stopWithNoCharge bool) error { + args := &api.StopInstanceArgs{ + ForceStop: forceStop, + StopWithNoCharge: stopWithNoCharge, + } + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.StopInstance(c, instanceId, body) +} + +// StopInstance - stop an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - forceStop: choose to force stop an instance or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StopInstance(instanceId string, forceStop bool) error { + args := &api.StopInstanceArgs{ + ForceStop: forceStop, + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.StopInstance(c, instanceId, body) +} + +// RebootInstance - restart an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - forceStop: choose to force stop an instance or not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstance(instanceId string, forceStop bool) error { + args := &api.StopInstanceArgs{ + ForceStop: forceStop, + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.RebootInstance(c, instanceId, body) +} + +func (c *Client) RecoveryInstance(args *api.RecoveryInstanceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.RecoveryInstance(c, body) +} + +// ChangeInstancePass - change an instance's password +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to change password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ChangeInstancePass(instanceId string, args *api.ChangeInstancePassArgs) error { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return err + } + args.AdminPass = cryptedPass + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.ChangeInstancePass(c, instanceId, body) +} + +// ModifyDeletionProtection - Modify deletion protection of specified instance +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to modify deletion protection, default 0 for deletable and 1 for deletion protection +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyDeletionProtection(instanceId string, args *api.DeletionProtectionArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.ModifyDeletionProtection(c, instanceId, body) +} + +// ModifyInstanceAttribute - modify an instance's attribute +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments of now instance's attribute +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyInstanceAttribute(instanceId string, args *api.ModifyInstanceAttributeArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.ModifyInstanceAttribute(c, instanceId, body) +} + +// ModifyInstanceDesc - modify an instance's description +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments of now instance's description +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyInstanceDesc(instanceId string, args *api.ModifyInstanceDescArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.ModifyInstanceDesc(c, instanceId, body) +} + +// ModifyInstanceHostname - modify an instance's hostname +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments of now instance's hostname +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyInstanceHostname(instanceId string, args *api.ModifyInstanceHostnameArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.ModifyInstanceHostname(c, instanceId, body) +} + +// BindSecurityGroup - bind a security group to an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - securityGroupId: the security group ID which need to bind +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindSecurityGroup(instanceId string, securityGroupId string) error { + args := &api.BindSecurityGroupArgs{ + SecurityGroupId: securityGroupId, + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BindSecurityGroup(c, instanceId, body) +} + +// UnBindSecurityGroup - unbind a security group ID from instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - securityGroupId: the security group ID which need to unbind +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindSecurityGroup(instanceId string, securityGroupId string) error { + args := &api.BindSecurityGroupArgs{ + SecurityGroupId: securityGroupId, + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.UnBindSecurityGroup(c, instanceId, body) +} + +// GetInstanceVNC - get an instance's VNC url +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - *api.GetInstanceVNCResult: the result of get instance's VNC url +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceVNC(instanceId string) (*api.GetInstanceVNCResult, error) { + return api.GetInstanceVNC(c, instanceId) +} + +// InstancePurchaseReserved - purchase reserve an instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to purchase reserved an instance +// +// RETURNS: +// - *api.InstancePurchaseReservedResult: the result of purchase reserve an instance +// - error: nil if success otherwise the specific error +func (c *Client) InstancePurchaseReserved(instanceId string, args *api.PurchaseReservedArgs) (*api.InstancePurchaseReservedResult, error) { + // this api only support Prepaid instance + args.Billing.PaymentTiming = api.PaymentTimingPrePaid + relatedRenewFlag := args.RelatedRenewFlag + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.InstancePurchaseReserved(c, instanceId, relatedRenewFlag, args.ClientToken, body) +} + +// GetBidInstancePrice - get the market price of the specified bidding instance +// +// PARAMS: +// - args: the arguments to get the bidding instance market price +// +// RETURNS: +// - *GetBidInstancePriceResult: result of the market price of the specified bidding instance +// - error: nil if success otherwise the specific error +func (c *Client) GetBidInstancePrice(args *api.GetBidInstancePriceArgs) (*api.GetBidInstancePriceResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.GetBidInstancePrice(c, args.ClientToken, body) +} + +// ListBidFlavor - list all flavors of the bidding instance +// +// RETURNS: +// - *ListBidFlavorResult: result of the flavor list +// - error: nil if success otherwise the specific error +func (c *Client) ListBidFlavor() (*api.ListBidFlavorResult, error) { + return api.ListBidFlavor(c) +} + +// DeleteInstanceWithRelateResource - delete an instance and all eip/cds relate it +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to delete instance and its relate resource +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstanceWithRelateResource(instanceId string, args *api.DeleteInstanceWithRelateResourceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.DeleteInstanceWithRelatedResource(c, instanceId, body) +} + +// InstanceChangeSubnet - change an instance's subnet +// +// PARAMS: +// - args: the arguments to change an instance's subnet +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceChangeSubnet(args *api.InstanceChangeSubnetArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.InstanceChangeSubnet(c, body) +} + +// InstanceChangeVpc - change an instance's vpc +// +// PARAMS: +// - args: the arguments to change an instance's vpc +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceChangeVpc(args *api.InstanceChangeVpcArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.InstanceChangeVpc(c, body) +} + +// BatchAddIP - Add ips to instance +// +// PARAMS: +// - args: the arguments to add ips to bbc instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchAddIP(args *api.BatchAddIpArgs) (*api.BatchAddIpResponse, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.BatchAddIp(c, args, body) +} + +// BatchDelIP - Delete ips of instance +// +// PARAMS: +// - args: the arguments to add ips to bbc instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDelIP(args *api.BatchDelIpArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.BatchDelIp(c, args, body) +} + +// cds sdk +// CreateCDSVolume - create a CDS volume +// +// PARAMS: +// - args: the arguments to create CDS +// +// RETURNS: +// - *api.CreateCDSVolumeResult: the result of create CDS volume, contains new volume ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateCDSVolume(args *api.CreateCDSVolumeArgs) (*api.CreateCDSVolumeResult, error) { + return api.CreateCDSVolume(c, args) +} + +// cds sdk +// CreateCDSVolumeV3 - create a CDS volume +// +// PARAMS: +// - args: the arguments to create CDS +// +// RETURNS: +// - *api.CreateCDSVolumeResult: the result of create CDS volume, contains new volume ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateCDSVolumeV3(args *api.CreateCDSVolumeV3Args) (*api.CreateCDSVolumeResult, error) { + return api.CreateCDSVolumeV3(c, args) +} + +// ListCDSVolume - list all cds volume with the specific parameters +// +// PARAMS: +// - args: the arguments to list all cds +// +// RETURNS: +// - *api.ListCDSVolumeResult: the result of list all CDS volume +// - error: nil if success otherwise the specific error +func (c *Client) ListCDSVolume(queryArgs *api.ListCDSVolumeArgs) (*api.ListCDSVolumeResult, error) { + return api.ListCDSVolume(c, queryArgs) +} + +// ListCDSVolumeV3 - list all cds volume with the specific parameters +// +// PARAMS: +// - args: the arguments to list all cds +// +// RETURNS: +// - *api.ListCDSVolumeResultV3: the result of list all CDS volume +// - error: nil if success otherwise the specific error +func (c *Client) ListCDSVolumeV3(queryArgs *api.ListCDSVolumeArgs) (*api.ListCDSVolumeResultV3, error) { + return api.ListCDSVolumeV3(c, queryArgs) +} + +// GetCDSVolumeDetail - get a CDS volume's detail info +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// +// RETURNS: +// - *api.GetVolumeDetailResult: the result of get a specific CDS volume's info +// - error: nil if success otherwise the specific error +func (c *Client) GetCDSVolumeDetail(volumeId string) (*api.GetVolumeDetailResult, error) { + return api.GetCDSVolumeDetail(c, volumeId) +} + +// GetCDSVolumeDetailV3 - get a CDS volume's detail info +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// +// RETURNS: +// - *api.GetVolumeDetailResultV3: the result of get a specific CDS volume's info +// - error: nil if success otherwise the specific error +func (c *Client) GetCDSVolumeDetailV3(volumeId string) (*api.GetVolumeDetailResultV3, error) { + return api.GetCDSVolumeDetailV3(c, volumeId) +} + +// AttachCDSVolume - attach a CDS volume to an instance +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to attach a CDS volume +// +// RETURNS: +// - *api.AttachVolumeResult: the result of attach a CDS volume +// - error: nil if success otherwise the specific error +func (c *Client) AttachCDSVolume(volumeId string, args *api.AttachVolumeArgs) (*api.AttachVolumeResult, error) { + return api.AttachCDSVolume(c, volumeId, args) +} + +// DetachCDSVolume - detach a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to detach a CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DetachCDSVolume(volumeId string, args *api.DetachVolumeArgs) error { + return api.DetachCDSVolume(c, volumeId, args) +} + +// DeleteCDSVolume - delete a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteCDSVolume(volumeId string) error { + return api.DeleteCDSVolume(c, volumeId) +} + +// DeleteCDSVolumeNew - delete a CDS volume and snapshot +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to delete a CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteCDSVolumeNew(volumeId string, args *api.DeleteCDSVolumeArgs) error { + return api.DeleteCDSVolumeNew(c, volumeId, args) +} + +// ResizeCDSVolume - resize a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to resize CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeCDSVolume(volumeId string, args *api.ResizeCSDVolumeArgs) error { + return api.ResizeCDSVolume(c, volumeId, args) +} + +// RollbackCDSVolume - rollback a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to rollback a CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RollbackCDSVolume(volumeId string, args *api.RollbackCSDVolumeArgs) error { + return api.RollbackCDSVolume(c, volumeId, args) +} + +// PurchaseReservedCDSVolume - purchase reserve a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to purchase reserve a CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PurchaseReservedCDSVolume(volumeId string, args *api.PurchaseReservedCSDVolumeArgs) error { + return api.PurchaseReservedCDSVolume(c, volumeId, args) +} + +// RenameCDSVolume - rename a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to rename a CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenameCDSVolume(volumeId string, args *api.RenameCSDVolumeArgs) error { + return api.RenameCDSVolume(c, volumeId, args) +} + +// ModifyCDSVolume - modify a CDS volume +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to modify a CDS volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyCDSVolume(volumeId string, args *api.ModifyCSDVolumeArgs) error { + return api.ModifyCDSVolume(c, volumeId, args) +} + +// ModifyChargeTypeCDSVolume - modify a CDS volume's charge type +// +// PARAMS: +// - volumeId: the specific CDS volume ID +// - args: the arguments to create instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyChargeTypeCDSVolume(volumeId string, args *api.ModifyChargeTypeCSDVolumeArgs) error { + return api.ModifyChargeTypeCDSVolume(c, volumeId, args) +} + +// AutoRenewCDSVolume - auto renew the specified cds volume +// +// PARAMS: +// - args: the arguments to auto renew the cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AutoRenewCDSVolume(args *api.AutoRenewCDSVolumeArgs) error { + return api.AutoRenewCDSVolume(c, args) +} + +// CancelAutoRenewCDSVolume - cancel auto renew the specified cds volume +// +// PARAMS: +// - args: the arguments to cancel auto renew the cds volume +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CancelAutoRenewCDSVolume(args *api.CancelAutoRenewCDSVolumeArgs) error { + return api.CancelAutoRenewCDSVolume(c, args) +} + +// securityGroup sdk +// CreateSecurityGroup - create a security group +// +// PARAMS: +// - args: the arguments to create security group +// +// RETURNS: +// - *api.CreateSecurityGroupResult: the result of create security group +// - error: nil if success otherwise the specific error +func (c *Client) CreateSecurityGroup(args *api.CreateSecurityGroupArgs) (*api.CreateSecurityGroupResult, error) { + return api.CreateSecurityGroup(c, args) +} + +// ListSecurityGroup - list all security group +// +// PARAMS: +// - args: the arguments to list all security group +// +// RETURNS: +// - *api.ListSecurityGroupResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroup(queryArgs *api.ListSecurityGroupArgs) (*api.ListSecurityGroupResult, error) { + return api.ListSecurityGroup(c, queryArgs) +} + +// AuthorizeSecurityGroupRule - authorize a security group rule +// +// PARAMS: +// - securityGroupId: the specific securityGroup ID +// - args: the arguments to authorize a security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AuthorizeSecurityGroupRule(securityGroupId string, args *api.AuthorizeSecurityGroupArgs) error { + return api.AuthorizeSecurityGroupRule(c, securityGroupId, args) +} + +// RevokeSecurityGroupRule - revoke a security group rule +// +// PARAMS: +// - securityGroupId: the specific securityGroup ID +// - args: the arguments to revoke security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RevokeSecurityGroupRule(securityGroupId string, args *api.RevokeSecurityGroupArgs) error { + return api.RevokeSecurityGroupRule(c, securityGroupId, args) +} + +// DeleteSecurityGroup - delete a security group +// +// PARAMS: +// - securityGroupId: the specific securityGroup ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSecurityGroup(securityGroupId string) error { + return api.DeleteSecurityGroup(c, securityGroupId) +} + +// image sdk +// CreateImage - create an image +// +// PARAMS: +// - args: the arguments to create image +// +// RETURNS: +// - *api.CreateImageResult: the result of create Image +// - error: nil if success otherwise the specific error +func (c *Client) CreateImage(args *api.CreateImageArgs) (*api.CreateImageResult, error) { + return api.CreateImage(c, args) +} + +// ListImage - list all images +// +// PARAMS: +// - args: the arguments to list all images +// +// RETURNS: +// - *api.ListImageResult: the result of list all images +// - error: nil if success otherwise the specific error +func (c *Client) ListImage(queryArgs *api.ListImageArgs) (*api.ListImageResult, error) { + return api.ListImage(c, queryArgs) +} + +// GetImageDetail - get an image's detail info +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - *api.GetImageDetailResult: the result of get image's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetImageDetail(imageId string) (*api.GetImageDetailResult, error) { + return api.GetImageDetail(c, imageId) +} + +// DeleteImage - delete an image +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteImage(imageId string) error { + return api.DeleteImage(c, imageId) +} + +// RemoteCopyImage - copy an image from other region +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to remote copy an image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RemoteCopyImage(imageId string, args *api.RemoteCopyImageArgs) error { + return api.RemoteCopyImage(c, imageId, args) +} + +// RemoteCopyImageReturnImageIds - copy an image from other region +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to remote copy an image +// +// RETURNS: +// - imageIds of destination region if success otherwise the specific error +func (c *Client) RemoteCopyImageReturnImageIds(imageId string, args *api.RemoteCopyImageArgs) (*api.RemoteCopyImageResult, error) { + return api.RemoteCopyImageReturnImageIds(c, imageId, args) +} + +// CancelRemoteCopyImage - cancel a copy image from other region operation +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CancelRemoteCopyImage(imageId string) error { + return api.CancelRemoteCopyImage(c, imageId) +} + +// ShareImage - share an image +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to share an image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ShareImage(imageId string, args *api.SharedUser) error { + return api.ShareImage(c, imageId, args) +} + +// UnShareImage - cancel share an image +// +// PARAMS: +// - imageId: the specific image ID +// - args: the arguments to cancel share an image +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnShareImage(imageId string, args *api.SharedUser) error { + return api.UnShareImage(c, imageId, args) +} + +// GetImageSharedUser - get user list use this image +// +// PARAMS: +// - imageId: the specific image ID +// +// RETURNS: +// - *api.GetImageSharedUserResult: the result of user list +// - error: nil if success otherwise the specific error +func (c *Client) GetImageSharedUser(imageId string) (*api.GetImageSharedUserResult, error) { + return api.GetImageSharedUser(c, imageId) +} + +// GetImageOS - get image OS +// +// PARAMS: +// - args: the arguments to get OS info +// +// RETURNS: +// - *api.GetImageOsResult: the result of get image OS info +// - error: nil if success otherwise the specific error +func (c *Client) GetImageOS(args *api.GetImageOsArgs) (*api.GetImageOsResult, error) { + return api.GetImageOS(c, args) +} + +// CreateSnapshot - create a snapshot +// +// PARAMS: +// - args: the arguments to create a snapshot +// +// RETURNS: +// - *api.CreateSnapshotResult: the result of create snapshot +// - error: nil if success otherwise the specific error +func (c *Client) CreateSnapshot(args *api.CreateSnapshotArgs) (*api.CreateSnapshotResult, error) { + return api.CreateSnapshot(c, args) +} + +// ListSnapshot - list all snapshots +// +// PARAMS: +// - args: the arguments to list all snapshots +// +// RETURNS: +// - *api.ListSnapshotResult: the result of list all snapshots +// - error: nil if success otherwise the specific error +func (c *Client) ListSnapshot(args *api.ListSnapshotArgs) (*api.ListSnapshotResult, error) { + return api.ListSnapshot(c, args) +} + +// ListSnapshotChain - list all snapshot chains +// +// PARAMS: +// - args: the arguments to list all snapshot chains +// +// RETURNS: +// - *api.ListSnapshotChainResult: the result of list all snapshot chains +// - error: nil if success otherwise the specific error +func (c *Client) ListSnapshotChain(args *api.ListSnapshotChainArgs) (*api.ListSnapshotChainResult, error) { + return api.ListSnapshotChain(c, args) +} + +// GetSnapshotDetail - get a snapshot's detail info +// +// PARAMS: +// - snapshotId: the specific snapshot ID +// +// RETURNS: +// - *api.GetSnapshotDetailResult: the result of get snapshot's detail info +// - error: nil if success otherwise the specific error +func (c *Client) GetSnapshotDetail(snapshotId string) (*api.GetSnapshotDetailResult, error) { + return api.GetSnapshotDetail(c, snapshotId) +} + +// DeleteSnapshot - delete a snapshot +// +// PARAMS: +// - snapshotId: the specific snapshot ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSnapshot(snapshotId string) error { + return api.DeleteSnapshot(c, snapshotId) +} + +// CreateAutoSnapshotPolicy - create an auto snapshot policy +// +// PARAMS: +// - args: the arguments to create an auto snapshot policy +// +// RETURNS: +// - *api.CreateASPResult: the result of create an auto snapshot policy +// - error: nil if success otherwise the specific error +func (c *Client) CreateAutoSnapshotPolicy(args *api.CreateASPArgs) (*api.CreateASPResult, error) { + return api.CreateAutoSnapshotPolicy(c, args) +} + +// AttachAutoSnapshotPolicy - attach an ASP to volumes +// +// PARAMS: +// - aspId: the specific auto snapshot policy ID +// - args: the arguments to attach an ASP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AttachAutoSnapshotPolicy(aspId string, args *api.AttachASPArgs) error { + return api.AttachAutoSnapshotPolicy(c, aspId, args) +} + +// DetachAutoSnapshotPolicy - detach an ASP +// +// PARAMS: +// - aspId: the specific auto snapshot policy ID +// - args: the arguments to detach an ASP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DetachAutoSnapshotPolicy(aspId string, args *api.DetachASPArgs) error { + return api.DetachAutoSnapshotPolicy(c, aspId, args) +} + +// DeleteAutoSnapshotPolicy - delete an auto snapshot policy +// +// PARAMS: +// - aspId: the specific auto snapshot policy ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAutoSnapshotPolicy(aspId string) error { + return api.DeleteAutoSnapshotPolicy(c, aspId) +} + +// ListAutoSnapshotPolicy - list all auto snapshot policies +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.ListASPResult: the result of list all auto snapshot policies +// - error: nil if success otherwise the specific error +func (c *Client) ListAutoSnapshotPolicy(args *api.ListASPArgs) (*api.ListASPResult, error) { + return api.ListAutoSnapshotPolicy(c, args) +} + +// GetAutoSnapshotPolicy - get an auto snapshot policy's meta +// +// PARAMS: +// - aspId: the specific auto snapshot policy ID +// +// RETURNS: +// - *api.GetASPDetailResult: the result of get an auto snapshot policy's meta +// - error: nil if success otherwise the specific error +func (c *Client) GetAutoSnapshotPolicy(aspId string) (*api.GetASPDetailResult, error) { + return api.GetAutoSnapshotPolicyDetail(c, aspId) +} + +// UpdateAutoSnapshotPolicy - update an auto snapshot policy +// +// PARAMS: +// - args: the arguments to update an auto snapshot policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAutoSnapshotPolicy(args *api.UpdateASPArgs) error { + return api.UpdateAutoSnapshotPolicy(c, args) +} + +// ListSpec - list all spec +// +// RETURNS: +// - *api.ListSpecResult: the result of all spec +// - error: nil if success otherwise the specific error +func (c *Client) ListSpec() (*api.ListSpecResult, error) { + return api.ListSpec(c) +} + +// ListZone - list all zones +// +// RETURNS: +// - *api.ListZoneResult: the result of list all zones +// - error: nil if success otherwise the specific error +func (c *Client) ListZone() (*api.ListZoneResult, error) { + return api.ListZone(c) +} + +// ListFlavorSpec - get the specified flavor list +// +// PARAMS: +// - args: the arguments to list the specified flavor +// +// RETURNS: +// - *api.ListFlavorSpecResult: result of the specified flavor list +// - error: nil if success otherwise the specific error +func (c *Client) ListFlavorSpec(args *api.ListFlavorSpecArgs) (*api.ListFlavorSpecResult, error) { + return api.ListFlavorSpec(c, args) +} + +// GetPriceBySpec - get the price information of specified instance. +// +// PARAMS: +// - args: the arguments to get the price information of specified instance. +// +// RETURNS: +// - *api.GetPriceBySpecResult: result of the specified instance's price information +// - error: nil if success otherwise the specific error +func (c *Client) GetPriceBySpec(args *api.GetPriceBySpecArgs) (*api.GetPriceBySpecResult, error) { + return api.GetPriceBySpec(c, args) +} + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - args: the arguments to create a deploy set +// +// RETURNS: +// - *CreateDeploySetResult: results of creating a deploy set +// - error: nil if success otherwise the specific error +func (c *Client) CreateDeploySet(args *api.CreateDeploySetArgs) (*api.CreateDeploySetResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.CreateDeploySet(c, args.ClientToken, body) +} + +// ListDeploySets - list all deploy sets +// +// RETURNS: +// - *ListDeploySetsResult: the result of list all deploy sets +// - error: nil if success otherwise the specific error +func (c *Client) ListDeploySets() (*api.ListDeploySetsResult, error) { + return api.ListDeploySets(c) +} + +// ModifyDeploySet - modify the deploy set +// +// PARAMS: +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *ModifyDeploySetArgs: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *Client) ModifyDeploySet(deploySetId string, args *api.ModifyDeploySetArgs) (error, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, nil + } + return api.ModifyDeploySet(c, deploySetId, args.ClientToken, body), nil +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDeploySet(deploySetId string) error { + return api.DeleteDeploySet(c, deploySetId) +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *GetDeploySetResult: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *Client) GetDeploySet(deploySetId string) (*api.DeploySetResult, error) { + return api.GetDeploySet(c, deploySetId) +} + +// UpdateInstanceDeploySet - update deployset and instance relation +// +// PARAMS: +// - args: the arguments to update deployset and instance relation +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceDeploySet(args *api.UpdateInstanceDeployArgs) (error, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.UpdateInstanceDeploy(c, args.ClientToken, body), nil +} + +// DelInstanceDeploySet - delete deployset and instance relation +// +// PARAMS: +// - args: the arguments to delete deployset and instance relation +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DelInstanceDeploySet(args *api.DelInstanceDeployArgs) (error, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.DelInstanceDeploy(c, args.ClientToken, body), nil +} + +// ResizeInstanceBySpec - resize a specific instance +// +// PARAMS: +// - instanceId: the specific instance ID +// - args: the arguments to resize a specific instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeInstanceBySpec(instanceId string, args *api.ResizeInstanceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.ResizeInstanceBySpec(c, instanceId, args.ClientToken, body) +} + +// RebuildBatchInstance - batch rebuild instances +// +// PARAMS: +// - args: the arguments to batch rebuild instances +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchRebuildInstances(args *api.RebuildBatchInstanceArgs) error { + if len(args.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return err + } + args.AdminPass = cryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BatchRebuildInstances(c, body) +} + +// RebuildBatchInstancesV2 - batch rebuild instances +// +// PARAMS: +// - args: the arguments to batch rebuild instances +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchRebuildInstancesV2(argsV2 *api.RebuildBatchInstanceArgsV2) error { + if len(argsV2.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, argsV2.AdminPass) + if err != nil { + return err + } + argsV2.AdminPass = cryptedPass + } + + defaultTrue := true + if argsV2.IsOpenHostEye == nil { + argsV2.IsOpenHostEye = &defaultTrue + } + if argsV2.IsPreserveData == nil { + argsV2.IsPreserveData = &defaultTrue + } + + jsonBytes, jsonErr := json.Marshal(argsV2) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BatchRebuildInstances(c, body) +} + +// ChangeToPrepaid - to prepaid +// +// PARAMS: +// - instanceId: instanceId +// - args: the arguments to ChangeToPrepaid +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ChangeToPrepaid(instanceId string, args *api.ChangeToPrepaidRequest) (*api.ChangeToPrepaidResponse, + error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.ChangeToPrepaid(c, instanceId, body) +} + +// BindInstanceToTags - bind instance to tags +// +// PARAMS: +// - instanceId: instanceId +// - args: the arguments to BindInstanceToTags +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindInstanceToTags(instanceId string, args *api.BindTagsRequest) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BindInstanceToTags(c, instanceId, body) +} + +// UnBindInstanceToTags - unbind instance to tags +// +// PARAMS: +// - instanceId: instanceId +// - args: the arguments to unBindInstanceToTags +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindInstanceToTags(instanceId string, args *api.UnBindTagsRequest) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.UnBindInstanceToTags(c, instanceId, body) +} + +// GetInstanceNoChargeList - get instance with nocharge list +// +// PARAMS: +// - args: the arguments to list all nocharge instance +// +// RETURNS: +// - *api.ListInstanceResult: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceNoChargeList(args *api.ListInstanceArgs) (*api.ListInstanceResult, error) { + return api.GetInstanceNoChargeList(c, args) +} + +// CreateBidInstance - create an instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create instance +// +// RETURNS: +// - *api.CreateInstanceResult: the result of create Instance, contains new Instance ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateBidInstance(args *api.CreateInstanceArgs) (*api.CreateInstanceResult, error) { + if len(args.AdminPass) > 0 { + cryptedPass, err := api.Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.AdminPass) + if err != nil { + return nil, err + } + + args.AdminPass = cryptedPass + } + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CreateBidInstance(c, args.ClientToken, body) +} + +// CancelBidOrder - Cancel the bidding instance order. +// +// PARAMS: +// - args: the arguments to cancel bid order +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CancelBidOrder(args *api.CancelBidOrderRequest) (*api.CreateBidInstanceResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.CancelBidOrder(c, args.ClientToken, body) +} + +// GetAvailableDiskInfo - get available diskInfos of the specified zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: the zone name eg:cn-bj-a +// +// RETURNS: +// - *GetAvailableDiskInfoResult: the result of the specified zone diskInfos +// - error: nil if success otherwise the specific error +func (c *Client) GetAvailableDiskInfo(zoneName string) (*api.GetAvailableDiskInfoResult, error) { + return api.GetAvailableDiskInfo(c, zoneName) +} + +// DeletePrepayVolume - delete the volumes for prepay +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments of method +// +// RETURNS: +// - *VolumeDeleteResultResponse: the result of deleting volumes +// - error: nil if success otherwise the specific error +func (c *Client) DeletePrepayVolume(args *api.VolumePrepayDeleteRequestArgs) (*api.VolumeDeleteResultResponse, error) { + return api.DeletePrepayVolume(c, args) +} + +// ListTypeZones - list instanceType zones +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceType: the instanceType like "N1" +// +// RETURNS: +// - *api.ListTypeZonesResult: the result of list instanceType zones +// - error: nil if success otherwise the specific error +func (c *Client) ListTypeZones(args *api.ListTypeZonesArgs) (*api.ListTypeZonesResult, error) { + return api.ListTypeZones(c, args) +} + +// ListInstanceEni - get the eni list of the bcc instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: the bcc instance id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ListInstanceEnis(instanceId string) (*api.ListInstanceEniResult, error) { + return api.ListInstanceEnis(c, instanceId) +} + +func (c *Client) CreateKeypair(args *api.CreateKeypairArgs) (*api.KeypairResult, error) { + return api.CreateKeypair(c, args) +} + +func (c *Client) ImportKeypair(args *api.ImportKeypairArgs) (*api.KeypairResult, error) { + return api.ImportKeypair(c, args) +} + +func (c *Client) AttachKeypair(args *api.AttackKeypairArgs) error { + return api.AttachKeypair(c, args) +} + +func (c *Client) DetachKeypair(args *api.DetachKeypairArgs) error { + return api.DetachKeypair(c, args) +} + +func (c *Client) DeleteKeypair(args *api.DeleteKeypairArgs) error { + return api.DeleteKeypair(c, args) +} + +func (c *Client) GetKeypairDetail(keypairId string) (*api.KeypairResult, error) { + return api.GetKeypairDetail(c, keypairId) +} + +func (c *Client) ListKeypairs(args *api.ListKeypairArgs) (*api.ListKeypairResult, error) { + return api.ListKeypairs(c, args) +} + +func (c *Client) RenameKeypair(args *api.RenameKeypairArgs) error { + return api.RenameKeypair(c, args) +} + +func (c *Client) UpdateKeypairDescription(args *api.KeypairUpdateDescArgs) error { + return api.UpdateKeypairDescription(c, args) +} + +// GetAllStocks - get the bcc and bbc's stock +// +// RETURNS: +// - *GetAllStocksResult: the result of the bcc and bbc's stock +// - error: nil if success otherwise the specific error +func (c *Client) GetAllStocks() (*api.GetAllStocksResult, error) { + return api.GetAllStocks(c) +} + +// GetStockWithDeploySet - get the bcc's stock with deploySet +// +// RETURNS: +// - *GetStockWithDeploySetResults: the result of the bcc's stock +// - error: nil if success otherwise the specific error +func (c *Client) GetStockWithDeploySet(args *api.GetStockWithDeploySetArgs) (*api.GetStockWithDeploySetResults, error) { + return api.GetStockWithDeploySet(c, args) +} + +// GetStockWithSpec - get the bcc's stock with spec +// +// RETURNS: +// - *GetStockWithSpecResults: the result of the bcc's stock +// - error: nil if success otherwise the specific error +func (c *Client) GetStockWithSpec(args *api.GetStockWithSpecArgs) (*api.GetStockWithSpecResults, error) { + return api.GetStockWithSpec(c, args) +} + +func (c *Client) GetInstanceCreateStock(args *api.CreateInstanceStockArgs) (*api.InstanceStockResult, error) { + return api.GetInstanceCreateStock(c, args) +} + +func (c *Client) GetInstanceResizeStock(args *api.ResizeInstanceStockArgs) (*api.InstanceStockResult, error) { + return api.GetInstanceResizeStock(c, args) +} + +// BatchCreateAutoRenewRules - Batch Create AutoRenew Rules +// +// PARAMS: +// - args: the arguments to batch create autorenew rules +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchCreateAutoRenewRules(args *api.BccCreateAutoRenewArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.BatchCreateAutoRenewRules(c, body) +} + +// BatchDeleteAutoRenewRules - Batch Delete AutoRenew Rules +// +// PARAMS: +// - args: the arguments to batch delete autorenew rules +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDeleteAutoRenewRules(args *api.BccDeleteAutoRenewArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.BatchDeleteAutoRenewRules(c, body) +} + +func (c *Client) DeleteInstanceIngorePayment(args *api.DeleteInstanceIngorePaymentArgs) (*api.DeleteInstanceResult, error) { + return api.DeleteInstanceIngorePayment(c, args) +} + +// DeleteRecycledInstance - delete a recycled instance +// +// PARAMS: +// - instanceId: the specific instance ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecycledInstance(instanceId string) error { + return api.DeleteRecycledInstance(c, instanceId) +} + +func (c *Client) ListInstanceByInstanceIds(args *api.ListInstanceByInstanceIdArgs) (*api.ListInstancesResult, error) { + return api.ListInstanceByInstanceIds(c, args) +} + +// BatchDeleteInstanceWithRelateResource - batch delete instance and all eip/cds relate it +// +// PARAMS: +// - args: the arguments to batch delete instance and its relate resource +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDeleteInstanceWithRelateResource(args *api.BatchDeleteInstanceWithRelateResourceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BatchDeleteInstanceWithRelatedResource(c, body) +} + +// BatchStartInstance - batch start instance +// +// PARAMS: +// - args: the arguments to batch start instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchStartInstance(args *api.BatchStartInstanceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BatchStartInstance(c, body) +} + +// BatchStopInstance - batch stop instance +// +// PARAMS: +// - args: the arguments to batch stop instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchStopInstance(args *api.BatchStopInstanceArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.BatchStopInstance(c, body) +} + +// ListInstanceTypes - list all instance type with the specific parameters +// +// PARAMS: +// - args: the arguments to list all instance type +// +// RETURNS: +// - *api.ListInstanceTypeResults: the result of list Instance type +// - error: nil if success otherwise the specific error +func (c *Client) ListInstanceTypes(args *api.ListInstanceTypeArgs) (*api.ListInstanceTypeResults, error) { + return api.ListInstanceTypes(c, args) +} + +// ListIdMappings - Long and short ID conversion parameters +// +// PARAMS: +// - args: the arguments to Long and short ID conversion +// +// RETURNS: +// - *api.ListIdMappingResults: result of the Long short mapping +// - error: nil if success otherwise the specific error +func (c *Client) ListIdMappings(args *api.ListIdMappingArgs) (*api.ListIdMappingResults, error) { + return api.ListIdMappings(c, args) +} + +// BatchResizeInstance - batch resize a specific instance +// +// PARAMS: +// - args: the arguments to resize a specific instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchResizeInstance(args *api.BatchResizeInstanceArgs) (*api.BatchResizeInstanceResults, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.BatchResizeInstance(c, body) +} + +// DeleteSecurityGroupRule - delete a security group rule +// +// PARAMS: +// - securityGroupRuleId: the id of the specific security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSecurityGroupRule(args *api.DeleteSecurityGroupRuleArgs) error { + return api.DeleteSecurityGroupRule(c, args) +} + +// UpdateSecurityGroupRule - update security group rule with the specific parameters +// +// PARAMS: +// - args: the arguments to update the specific security group rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSecurityGroupRule(args *api.UpdateSecurityGroupRuleArgs) error { + return api.UpdateSecurityGroupRule(c, args) +} + +func (c *Client) GetInstanceDeleteProgress(args *api.GetInstanceDeleteProgressArgs) (map[string]interface{}, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.GetInstanceDeleteProgress(c, body) +} +func (c *Client) TagVolume(volumeId string, args *api.TagVolumeArgs) error { + return api.TagVolume(c, volumeId, args) +} + +func (c *Client) UntagVolume(volumeId string, args *api.TagVolumeArgs) error { + return api.UntagVolume(c, volumeId, args) +} + +func (c *Client) TagSnapshotChain(chainId string, args *api.TagVolumeArgs) error { + return api.TagSnapshotChain(c, chainId, args) +} + +func (c *Client) UntagSnapshotChain(chainId string, args *api.TagVolumeArgs) error { + return api.UntagSnapshotChain(c, chainId, args) +} + +func (c *Client) ListAvailableResizeSpecs(args *api.ListAvailableResizeSpecsArgs) ( + *api.ListAvailableResizeSpecResults, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.ListAvailableResizeSpecs(c, body) +} + +func (c *Client) BatchChangeInstanceToPrepay(args *api.BatchChangeInstanceToPrepayArgs) ( + *api.BatchChangeInstanceBillingMethodResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.BatchChangeInstanceToPrepay(c, body) + +} + +func (c *Client) BatchChangeInstanceToPostpay(args *api.BatchChangeInstanceToPostpayArgs) ( + *api.BatchChangeInstanceBillingMethodResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.BatchChangeInstanceToPostpay(c, body) +} + +func (c *Client) ListInstanceRoles() (*api.ListInstanceRolesResult, error) { + + return api.ListInstanceRoles(c) +} + +func (c *Client) BindInstanceRole(args *api.BindInstanceRoleArgs) (*api.BindInstanceRoleResult, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.BindInstanceRole(c, body) +} + +func (c *Client) UnBindInstanceRole(args *api.UnBindInstanceRoleArgs) (*api.UnBindInstanceRoleResult, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.UnBindInstanceRole(c, body) +} + +func (c *Client) DeleteIpv6(args *api.DeleteIpv6Args) error { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.DeleteIpv6(c, body) +} + +func (c *Client) AddIpv6(args *api.AddIpv6Args) (*api.AddIpv6Result, error) { + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + return api.AddIpv6(c, body) +} + +func (c *Client) BindImageToTags(imageId string, args *api.BindTagsRequest) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.BindImageToTags(c, imageId, body) +} + +func (c *Client) UnBindImageToTags(imageId string, args *api.UnBindTagsRequest) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + return api.UnBindImageToTags(c, imageId, body) +} + +func (c *Client) CreateRemoteCopySnapshot(snapshotId string, args *api.RemoteCopySnapshotArgs) (*api.RemoteCopySnapshotResult, + error) { + + return api.CreateRemoteCopySnapshot(c, snapshotId, args) +} + +func (c *Client) ImportCustomImage(args *api.ImportCustomImageArgs) (*api.ImportCustomImageResult, + error) { + + return api.ImportCustomImage(c, args) +} + +func (c *Client) GetAvailableImagesBySpec(args *api.GetAvailableImagesBySpecArg) (*api.GetAvailableImagesBySpecResult, error) { + + return api.GetAvailableImagesBySpec(c, args) +} diff --git a/bce-sdk-go/services/bcc/client_test.go b/bce-sdk-go/services/bcc/client_test.go new file mode 100644 index 0000000..1add200 --- /dev/null +++ b/bce-sdk-go/services/bcc/client_test.go @@ -0,0 +1,1760 @@ +package bcc + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/bcc/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BCC_CLIENT *Client + BCC_TestCdsId string + BCC_TestBccId string + BCC_TestSecurityGroupId string + BCC_TestImageId string + BCC_TestSnapshotId string + BCC_TestAspId string + BCC_TestDeploySetId string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + BCC_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) + // log.SetLogLevel(log.DEBUG) + BCC_TestBccId = "i-7pxLG046" + BCC_TestCdsId = "cds_id" + BCC_TestImageId = "m-Q0ezqMIa" +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestCreateInstance(t *testing.T) { + InternalIps := []string{"ip"} + DeploySetIds := []string{"DeploySetId1", "DeploySetId2"} + createInstanceArgs := &api.CreateInstanceArgs{ + ImageId: "m-aCVG7Jxt", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + InstanceType: api.InstanceTypeN5, + CpuCount: 1, + MemoryCapacityInGB: 1, + RootDiskSizeInGb: 40, + RootDiskStorageType: api.StorageTypeEnhancedPl1, + ZoneName: "ZoneName", + SubnetId: "SubnetId", + SecurityGroupId: "SecurityGroupId", + RelationTag: true, + PurchaseCount: 1, + Name: "sdkTest", + KeypairId: "KeypairId", + InternalIps: InternalIps, + DeployIdList: DeploySetIds, + } + createResult, err := BCC_CLIENT.CreateInstance(createInstanceArgs) + ExpectEqual(t.Errorf, err, nil) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCreateInstanceV2(t *testing.T) { + InternalIps := []string{"ip"} + DeploySetIds := []string{"DeploySetId1", "DeploySetId2"} + RelationTag := true + IsOpenHostEye := true + argsV2 := &api.CreateInstanceArgsV2{ + ClientToken: "clientToken", + RequestToken: "requestToken", + ImageId: "m-aCVG7Jxt", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + InstanceType: api.InstanceTypeN5, + CpuCount: 1, + MemoryCapacityInGB: 1, + RootDiskSizeInGb: 40, + RootDiskStorageType: api.StorageTypeEnhancedPl1, + ZoneName: "ZoneName", + SubnetId: "SubnetId", + SecurityGroupId: "SecurityGroupId", + RelationTag: &RelationTag, + PurchaseCount: 1, + Name: "sdkTest", + KeypairId: "KeypairId", + InternalIps: InternalIps, + DeployIdList: DeploySetIds, + IsOpenHostEye: &IsOpenHostEye, + } + + createResult, err := BCC_CLIENT.CreateInstanceV2(argsV2) + ExpectEqual(t.Errorf, err, nil) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCreateSpecialInstanceBySpec(t *testing.T) { + createInstanceBySpecArgs := &api.CreateSpecialInstanceBySpecArgs{ + ImageId: "ImageId", + Spec: "bcc.g5.c1m4", + ZoneName: "cn-bj-a", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + + LabelConstraints: []api.LabelConstraint{{ + Key: "feaA", + Operator: api.LabelOperatorExist, + }, { + Key: "feaB", + Value: "typeB", + Operator: api.LabelOperatorNotEqual, + }}, + } + // 将使用『有 feaA 这个 label』且『feaB 这个 label 的值不是 typeB』的测试机创建实例 + createResult, err := BCC_CLIENT.CreateInstanceByLabel(createInstanceBySpecArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(createResult) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCreateInstanceBySpec(t *testing.T) { + DeploySetIds := []string{"DeploySetId"} + createInstanceBySpecArgs := &api.CreateInstanceBySpecArgs{ + ImageId: "ImageId", + Spec: "bcc.l3.c16m64", + Name: "sdkTest2", + AdminPass: "123qaz!@#", + ZoneName: "cn-bj-a", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + DeployIdList: DeploySetIds, + } + createResult, err := BCC_CLIENT.CreateInstanceBySpec(createInstanceBySpecArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(createResult) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCreateInstanceBySpecV2(t *testing.T) { + DeploySetIds := []string{"DeploySetId"} + EnableHt := true + createInstanceBySpecArgs := &api.CreateInstanceBySpecArgsV2{ + ImageId: "ImageId", + Spec: "bcc.l3.c16m64", + Name: "sdkTest2", + AdminPass: "123qaz!@#", + ZoneName: "cn-bj-a", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + DeployIdList: DeploySetIds, + EnableHt: &EnableHt, + } + createResult, err := BCC_CLIENT.CreateInstanceBySpecV2(createInstanceBySpecArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(createResult) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCreateInstanceV3(t *testing.T) { + createInstanceV3Args := &api.CreateInstanceV3Args{ + InstanceSpec: "bcc.l1.c1m1", + SystemVolume: api.SystemVolume{ + StorageType: api.StorageTypeV3CloudSSDGeneral, + VolumeSize: 20, + }, + DataVolumes: []api.DataVolume{ + { + StorageType: api.StorageTypeV3LocalSSD, + VolumeSize: 460, + }, + }, + PurchaseCount: 1, + InstanceName: "sdkTest8", + Password: "123qaz!@#", + ZoneName: "cn-bj-b", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + }, + }, + AssociatedResourceTag: true, + Tags: []model.TagModel{ + { + TagKey: "v3", + TagValue: "1", + }, + }, + AutoRenewTime: 12, + CdsAutoRenew: true, + // 私有网络子网 IP 数组,当前仅支持批量创建多台实例时支持传入相同子网的多个 IP。 + PrivateIpAddresses: []string{ + "ip", + }, + DeployIdList: []string{ + // "dset-PAAeNoJt", + "DeployId", + }, + ImageId: "ImageId", + InternetAccessible: api.InternetAccessible{ + InternetMaxBandwidthOut: 5, + InternetChargeType: api.TrafficPostpaidByHour, + }, + InstanceMarketOptions: api.InstanceMarketOptions{ + SpotOption: "custom", + SpotPrice: "10", + }, + } + createResult, err := BCC_CLIENT.CreateInstanceV3(createInstanceV3Args) + ExpectEqual(t.Errorf, err, nil) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCreateSecurityGroup(t *testing.T) { + args := &api.CreateSecurityGroupArgs{ + Name: "testSecurityGroup", + VpcId: "vpc-uiudcexceb7y", + Desc: "vpc1 sdk test create security group", + Rules: []api.SecurityGroupRuleModel{ + { + Remark: "备注", + Protocol: "tcp", + PortRange: "1-65535", + Direction: "ingress", + SourceIp: "", + SourceGroupId: "", + }, + }, + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + }, + } + result, err := BCC_CLIENT.CreateSecurityGroup(args) + ExpectEqual(t.Errorf, err, nil) + BCC_TestSecurityGroupId = result.SecurityGroupId +} + +func TestCreateImage(t *testing.T) { + args := &api.CreateImageArgs{ + ImageName: "testImageName", + InstanceId: BCC_TestBccId, + } + result, err := BCC_CLIENT.CreateImage(args) + ExpectEqual(t.Errorf, err, nil) + BCC_TestImageId = result.ImageId +} + +func TestListInstances(t *testing.T) { + listArgs := &api.ListInstanceArgs{ + ZoneName: "cn-bj-a", + } + res, err := BCC_CLIENT.ListInstances(listArgs) + ExpectEqual(t.Errorf, err, nil) + // fmt.Println(res.Instances[0].NetEthQueueCount) + fmt.Println(res) +} + +func TestListRecycleInstances(t *testing.T) { + listArgs := &api.ListRecycleInstanceArgs{} + res, err := BCC_CLIENT.ListRecycleInstances(listArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestGetInstanceDetail(t *testing.T) { + res, err := BCC_CLIENT.GetInstanceDetail("i-aFW4mJkZ") + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res.Instance.NetEthQueueCount) + fmt.Println(res) +} + +func TestGetInstanceDetailWithDeploySetAndFailed(t *testing.T) { + res, err := BCC_CLIENT.GetInstanceDetailWithDeploySetAndFailed("InstanceId", false, true) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestResizeInstance(t *testing.T) { + resizeArgs := &api.ResizeInstanceArgs{ + CpuCount: 2, + MemoryCapacityInGB: 4, + } + err := BCC_CLIENT.ResizeInstance(BCC_TestBccId, resizeArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestLiveResizeInstance(t *testing.T) { + resizeArgs := &api.ResizeInstanceArgs{ + CpuCount: 2, + MemoryCapacityInGB: 4, + LiveResize: true, + } + err := BCC_CLIENT.ResizeInstance(BCC_TestBccId, resizeArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestStopInstanceWithNoCharge(t *testing.T) { + err := BCC_CLIENT.StopInstanceWithNoCharge(BCC_TestBccId, true, true) + ExpectEqual(t.Errorf, err, nil) +} + +func TestStopInstance(t *testing.T) { + err := BCC_CLIENT.StopInstance(BCC_TestBccId, true) + ExpectEqual(t.Errorf, err, nil) +} + +func TestStartInstance(t *testing.T) { + err := BCC_CLIENT.StartInstance(BCC_TestBccId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRebootInstance(t *testing.T) { + err := BCC_CLIENT.RebootInstance(BCC_TestBccId, true) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRebuildInstance(t *testing.T) { + rebuildArgs := &api.RebuildInstanceArgs{ + ImageId: "ImageId", + AdminPass: "123qaz!@#", + } + err := BCC_CLIENT.RebuildInstance(BCC_TestBccId, rebuildArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRebuildInstanceV2(t *testing.T) { + rebuildArgs := &api.RebuildInstanceArgsV2{ + ImageId: "ImageId", + AdminPass: "123qaz!@#", + } + err := BCC_CLIENT.RebuildInstanceV2(BCC_TestBccId, rebuildArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestChangeInstancePass(t *testing.T) { + changeArgs := &api.ChangeInstancePassArgs{ + AdminPass: "321zaq#@!", + } + err := BCC_CLIENT.ChangeInstancePass(BCC_TestBccId, changeArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyInstanceAttribute(t *testing.T) { + modifyArgs := &api.ModifyInstanceAttributeArgs{ + Name: "test-modify", + NetEthQueueCount: "3", + } + err := BCC_CLIENT.ModifyInstanceAttribute(BCC_TestBccId, modifyArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyInstanceDesc(t *testing.T) { + modifyArgs := &api.ModifyInstanceDescArgs{ + Description: "test modify", + } + err := BCC_CLIENT.ModifyInstanceDesc(BCC_TestBccId, modifyArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyInstanceHostname(t *testing.T) { + modifyArgs := &api.ModifyInstanceHostnameArgs{ + Hostname: "test-modify-domain", + IsOpenHostnameDomain: false, + Reboot: true, + } + err := BCC_CLIENT.ModifyInstanceHostname(BCC_TestBccId, modifyArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetInstanceVNC(t *testing.T) { + _, err := BCC_CLIENT.GetInstanceVNC(BCC_TestBccId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchAddIp(t *testing.T) { + privateIps := []string{"privateIp"} + batchAddIpArgs := &api.BatchAddIpArgs{ + InstanceId: BCC_TestBccId, + PrivateIps: privateIps, + SecondaryPrivateIpAddressCount: 1, + } + result, err := BCC_CLIENT.BatchAddIP(batchAddIpArgs) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchDelIp(t *testing.T) { + privateIps := []string{"privateIp"} + batchDelIpArgs := &api.BatchDelIpArgs{ + InstanceId: BCC_TestBccId, + PrivateIps: privateIps, + } + err := BCC_CLIENT.BatchDelIP(batchDelIpArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBindSecurityGroup(t *testing.T) { + err := BCC_CLIENT.BindSecurityGroup(BCC_TestBccId, BCC_TestSecurityGroupId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnBindSecurityGroup(t *testing.T) { + err := BCC_CLIENT.UnBindSecurityGroup(BCC_TestBccId, BCC_TestSecurityGroupId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateCDSVolume(t *testing.T) { + args := &api.CreateCDSVolumeArgs{ + PurchaseCount: 1, + CdsSizeInGB: 40, + Billing: &api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "MONTH", + }, + }, + AutoSnapshotPolicy: []api.AutoSnapshotPolicy{ + { + AutoSnapshotPolicyId: "Test_AutoSnapshotPolicyId", + }, + }, + RenewTimeUnit: "month", + RenewTime: 2, + } + + result, _ := BCC_CLIENT.CreateCDSVolume(args) + BCC_TestCdsId = result.VolumeIds[0] + fmt.Print(BCC_TestCdsId) +} + +func TestCreateCDSVolumeV3(t *testing.T) { + args := &api.CreateCDSVolumeV3Args{ + ZoneName: "cn-bj-a", + VolumeName: "volumeV3Test", + Description: "v3 test", + PurchaseCount: 1, + VolumeSize: 50, + StorageType: api.StorageTypeV3CloudSSDGeneral, + Billing: &api.Billing{ + PaymentTiming: api.PaymentTimingPostPaid, + }, + } + + result, err := BCC_CLIENT.CreateCDSVolumeV3(args) + fmt.Println(result) + ExpectEqual(t.Errorf, err, nil) + BCC_TestCdsId = result.VolumeIds[0] +} + +func TestGetBidInstancePrice(t *testing.T) { + args := &api.GetBidInstancePriceArgs{ + InstanceType: api.InstanceTypeN1, + CpuCount: 1, + MemoryCapacityInGB: 2, + RootDiskSizeInGb: 45, + RootDiskStorageType: api.StorageTypeCloudHP1, + PurchaseCount: 1, + } + result, err := BCC_CLIENT.GetBidInstancePrice(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestListBidFlavor(t *testing.T) { + result, err := BCC_CLIENT.ListBidFlavor() + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestCreateSnapshot(t *testing.T) { + args := &api.CreateSnapshotArgs{ + VolumeId: BCC_TestCdsId, + SnapshotName: "testSnapshotName", + Tags: []model.TagModel{ + { + TagKey: "test", + TagValue: "val", + }, + }, + } + result, err := BCC_CLIENT.CreateSnapshot(args) + ExpectEqual(t.Errorf, err, nil) + + BCC_TestSnapshotId = result.SnapshotId +} + +func TestListSnapshot(t *testing.T) { + args := &api.ListSnapshotArgs{} + _, err := BCC_CLIENT.ListSnapshot(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListSnapshotChain(t *testing.T) { + args := &api.ListSnapshotChainArgs{ + OrderBy: "chainId", + Order: "asc", + PageSize: 2, + PageNo: 2, + } + res, err := BCC_CLIENT.ListSnapshotChain(args) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetSnapshotDetail(t *testing.T) { + _, err := BCC_CLIENT.GetSnapshotDetail(BCC_TestSnapshotId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteSnapshot(t *testing.T) { + err := BCC_CLIENT.DeleteSnapshot(BCC_TestSnapshotId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateAutoSnapshotPolicy(t *testing.T) { + args := &api.CreateASPArgs{ + Name: "testAspName", + TimePoints: []string{"20"}, + RepeatWeekdays: []string{"1", "5"}, + RetentionDays: "7", + } + result, err := BCC_CLIENT.CreateAutoSnapshotPolicy(args) + ExpectEqual(t.Errorf, err, nil) + BCC_TestAspId = result.AspId +} + +func TestAttachAutoSnapshotPolicy(t *testing.T) { + args := &api.AttachASPArgs{ + VolumeIds: []string{BCC_TestCdsId}, + } + err := BCC_CLIENT.AttachAutoSnapshotPolicy(BCC_TestAspId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDetachAutoSnapshotPolicy(t *testing.T) { + args := &api.DetachASPArgs{ + VolumeIds: []string{BCC_TestCdsId}, + } + err := BCC_CLIENT.DetachAutoSnapshotPolicy(BCC_TestAspId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUpdateAutoSnapshotPolicy(t *testing.T) { + args := &api.UpdateASPArgs{ + AspId: "AspId", + Name: "Name", + TimePoints: []string{"21"}, + RepeatWeekdays: []string{"2"}, + } + err := BCC_CLIENT.UpdateAutoSnapshotPolicy(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListAutoSnapshotPolicy(t *testing.T) { + args := &api.ListASPArgs{} + _, err := BCC_CLIENT.ListAutoSnapshotPolicy(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetAutoSnapshotPolicy(t *testing.T) { + _, err := BCC_CLIENT.GetAutoSnapshotPolicy(BCC_TestAspId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteAutoSnapshotPolicy(t *testing.T) { + err := BCC_CLIENT.DeleteAutoSnapshotPolicy(BCC_TestAspId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListCDSVolume(t *testing.T) { + queryArgs := &api.ListCDSVolumeArgs{ + InstanceId: BCC_TestBccId, + } + res, err := BCC_CLIENT.ListCDSVolume(queryArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestListCDSVolumeV3(t *testing.T) { + queryArgs := &api.ListCDSVolumeArgs{ + InstanceId: BCC_TestBccId, + } + res, err := BCC_CLIENT.ListCDSVolumeV3(queryArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetCDSVolumeDetail(t *testing.T) { + res, err := BCC_CLIENT.GetCDSVolumeDetail(BCC_TestCdsId) + fmt.Println(res.Volume) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetCDSVolumeDetailV3(t *testing.T) { + res, err := BCC_CLIENT.GetCDSVolumeDetailV3(BCC_TestCdsId) + fmt.Println(res.Volume) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAttachCDSVolume(t *testing.T) { + args := &api.AttachVolumeArgs{ + InstanceId: BCC_TestBccId, + } + + _, err := BCC_CLIENT.AttachCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDetachCDSVolume(t *testing.T) { + args := &api.DetachVolumeArgs{ + InstanceId: BCC_TestBccId, + } + + err := BCC_CLIENT.DetachCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestResizeCDSVolume(t *testing.T) { + args := &api.ResizeCSDVolumeArgs{ + NewCdsSizeInGB: 100, + } + + err := BCC_CLIENT.ResizeCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRollbackCDSVolume(t *testing.T) { + args := &api.RollbackCSDVolumeArgs{ + SnapshotId: "SnapshotId", + } + + err := BCC_CLIENT.RollbackCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestPurchaseReservedCDSVolume(t *testing.T) { + args := &api.PurchaseReservedCSDVolumeArgs{ + Billing: &api.Billing{ + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "Month", + }, + }, + } + + err := BCC_CLIENT.PurchaseReservedCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRenameCDSVolume(t *testing.T) { + args := &api.RenameCSDVolumeArgs{ + Name: "testRenamedName", + } + + err := BCC_CLIENT.RenameCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyCDSVolume(t *testing.T) { + args := &api.ModifyCSDVolumeArgs{ + CdsName: "modifiedName", + Desc: "modifiedDesc", + } + + err := BCC_CLIENT.ModifyCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyChargeTypeCDSVolume(t *testing.T) { + args := &api.ModifyChargeTypeCSDVolumeArgs{ + Billing: &api.Billing{ + Reservation: &api.Reservation{ + ReservationLength: 1, + }, + }, + } + + err := BCC_CLIENT.ModifyChargeTypeCDSVolume(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteCDSVolumeNew(t *testing.T) { + args := &api.DeleteCDSVolumeArgs{ + AutoSnapshot: "on", + Recycle: "on", + } + + err := BCC_CLIENT.DeleteCDSVolumeNew(BCC_TestCdsId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteCDSVolume(t *testing.T) { + err := BCC_CLIENT.DeleteCDSVolume(BCC_TestCdsId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAutoRenewCDSVolume(t *testing.T) { + args := &api.AutoRenewCDSVolumeArgs{ + VolumeId: "VolumeId", + RenewTimeUnit: "month", + RenewTime: 2, + } + + err := BCC_CLIENT.AutoRenewCDSVolume(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCancelAutoRenewCDSVolume(t *testing.T) { + args := &api.CancelAutoRenewCDSVolumeArgs{ + VolumeId: "VolumeId", + } + + err := BCC_CLIENT.CancelAutoRenewCDSVolume(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListSecurityGroup(t *testing.T) { + queryArgs := &api.ListSecurityGroupArgs{ + VpcId: "vpc-uiudcexceb7y", + } + result, err := BCC_CLIENT.ListSecurityGroup(queryArgs) + r, _ := json.Marshal(result) + fmt.Println(string(r)) + ExpectEqual(t.Errorf, err, nil) +} + +func TestInstanceChangeVpc(t *testing.T) { + args := &api.InstanceChangeVpcArgs{ + InstanceId: "InstanceId", + SubnetId: "SubnetId", + Reboot: false, + SecurityGroupIds: []string{"SecurityGroupId"}, + EnterpriseSecurityGroupIds: []string{"EnterpriseSecurityGroupIds"}, + } + + err := BCC_CLIENT.InstanceChangeVpc(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestInstanceChangeSubnet(t *testing.T) { + args := &api.InstanceChangeSubnetArgs{ + InstanceId: "i-YRMFRB6Z", + SubnetId: "sbn-z1y9tcedqnh6", + InternalIp: "192.168.5.12", + Reboot: false, + } + + err := BCC_CLIENT.InstanceChangeSubnet(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAuthorizeSecurityGroupRule(t *testing.T) { + args := &api.AuthorizeSecurityGroupArgs{ + Rule: &api.SecurityGroupRuleModel{ + Remark: "备注", + Protocol: "udp", + PortRange: "1-65535", + Direction: "ingress", + SourceIp: "", + SourceGroupId: "", + }, + } + err := BCC_CLIENT.AuthorizeSecurityGroupRule(BCC_TestSecurityGroupId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRevokeSecurityGroupRule(t *testing.T) { + args := &api.RevokeSecurityGroupArgs{ + Rule: &api.SecurityGroupRuleModel{ + Remark: "备注", + Protocol: "udp", + PortRange: "1-65535", + Direction: "ingress", + SourceIp: "", + SourceGroupId: "", + }, + } + err := BCC_CLIENT.RevokeSecurityGroupRule(BCC_TestSecurityGroupId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteSecurityGroupRule(t *testing.T) { + err := BCC_CLIENT.DeleteSecurityGroup(BCC_TestSecurityGroupId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListImage(t *testing.T) { + queryArgs := &api.ListImageArgs{} + _, err := BCC_CLIENT.ListImage(queryArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetImageDetail(t *testing.T) { + _, err := BCC_CLIENT.GetImageDetail(BCC_TestImageId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRemoteCopyImage(t *testing.T) { + args := &api.RemoteCopyImageArgs{ + Name: "testRemoteCopy", + DestRegion: []string{"hkg"}, + } + err := BCC_CLIENT.RemoteCopyImage(BCC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRemoteCopyImageReturnImageIds(t *testing.T) { + args := &api.RemoteCopyImageArgs{ + Name: "Copy", + DestRegion: []string{"hkg"}, + } + result, err := BCC_CLIENT.RemoteCopyImageReturnImageIds(BCC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestCancelRemoteCopyImage(t *testing.T) { + err := BCC_CLIENT.CancelRemoteCopyImage(BCC_TestImageId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestShareImage(t *testing.T) { + args := &api.SharedUser{ + AccountId: "id", + } + err := BCC_CLIENT.ShareImage(BCC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnShareImage(t *testing.T) { + args := &api.SharedUser{ + AccountId: "id", + } + err := BCC_CLIENT.UnShareImage(BCC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetImageSharedUser(t *testing.T) { + _, err := BCC_CLIENT.GetImageSharedUser(BCC_TestImageId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetImageOS(t *testing.T) { + args := &api.GetImageOsArgs{} + _, err := BCC_CLIENT.GetImageOS(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteImage(t *testing.T) { + err := BCC_CLIENT.DeleteImage(BCC_TestImageId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteInstance(t *testing.T) { + err := BCC_CLIENT.DeleteInstance(BCC_TestBccId) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteInstanceWithRelateResource(t *testing.T) { + args := &api.DeleteInstanceWithRelateResourceArgs{ + BccRecycleFlag: true, + DeleteImmediate: true, + } + + err := BCC_CLIENT.DeleteInstanceWithRelateResource(BCC_TestBccId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListSpec(t *testing.T) { + _, err := BCC_CLIENT.ListSpec() + ExpectEqual(t.Errorf, err, nil) +} + +func TestListZone(t *testing.T) { + _, err := BCC_CLIENT.ListZone() + ExpectEqual(t.Errorf, err, nil) +} + +func TestListFlavorSpec(t *testing.T) { + args := &api.ListFlavorSpecArgs{} + res, err := BCC_CLIENT.ListFlavorSpec(args) + ExpectEqual(t.Errorf, err, nil) + //fmt.Println(res.ZoneResources[0].BccResources.FlavorGroups[0].Flavors[0].NetEthQueueCount) + //fmt.Println(res.ZoneResources[0].BccResources.FlavorGroups[0].Flavors[0].NetEthMaxQueueCount) + fmt.Println(res) +} + +func TestGetPriceBySpec(t *testing.T) { + args := &api.GetPriceBySpecArgs{ + SpecId: "g1", + Spec: "", + PaymentTiming: "Postpaid", + ZoneName: "cn-gz-b", + PurchaseCount: 1, + PurchaseLength: 1, + } + res, err := BCC_CLIENT.GetPriceBySpec(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestCreateDeploySet(t *testing.T) { + testDeploySetName := "testName" + testDeployDesc := "testDesc" + testStrategy := "HOST_HA" + queryArgs := &api.CreateDeploySetArgs{ + Strategy: testStrategy, + Name: testDeploySetName, + Desc: testDeployDesc, + Concurrency: 5, + } + rep, err := BCC_CLIENT.CreateDeploySet(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListDeploySets(t *testing.T) { + rep, err := BCC_CLIENT.ListDeploySets() + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyDeploySet(t *testing.T) { + testDeploySetName := "testName" + testDeployDesc := "goDesc" + queryArgs := &api.ModifyDeploySetArgs{ + Name: testDeploySetName, + Desc: testDeployDesc, + } + BCC_TestDeploySetId = "DeploySetId" + rep, err := BCC_CLIENT.ModifyDeploySet(BCC_TestDeploySetId, queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteDeploySet(t *testing.T) { + testDeleteDeploySetId := "DeploySetId" + err := BCC_CLIENT.DeleteDeploySet(testDeleteDeploySetId) + fmt.Println(err) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetDeploySet(t *testing.T) { + testDeploySetID := "DeploySetId" + rep, err := BCC_CLIENT.GetDeploySet(testDeploySetID) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUpdateInstanceDeploySet(t *testing.T) { + queryArgs := &api.UpdateInstanceDeployArgs{ + InstanceId: "InstanceId", + DeploySetIds: []string{"DeploySetId"}, + } + rep, err := BCC_CLIENT.UpdateInstanceDeploySet(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDelInstanceDeploySet(t *testing.T) { + queryArgs := &api.DelInstanceDeployArgs{ + DeploySetId: "DeploySetId", + InstanceIds: []string{"InstanceId"}, + } + rep, err := BCC_CLIENT.DelInstanceDeploySet(queryArgs) + fmt.Println(rep) + ExpectEqual(t.Errorf, err, nil) +} + +func TestResizeInstanceBySpec(t *testing.T) { + resizeArgs := &api.ResizeInstanceArgs{ + Spec: "Spec", + } + err := BCC_CLIENT.ResizeInstanceBySpec(BCC_TestBccId, resizeArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchRebuildInstances(t *testing.T) { + rebuildArgs := &api.RebuildBatchInstanceArgs{ + ImageId: "ImageId", + AdminPass: "123qaz!@#", + InstanceIds: []string{BCC_TestBccId}, + } + err := BCC_CLIENT.BatchRebuildInstances(rebuildArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchRebuildInstancesV2(t *testing.T) { + rebuildArgs := &api.RebuildBatchInstanceArgsV2{ + ImageId: "ImageId", + AdminPass: "123qaz!@#", + InstanceIds: []string{BCC_TestBccId}, + } + err := BCC_CLIENT.BatchRebuildInstancesV2(rebuildArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestChangeToPrepaid(t *testing.T) { + args := &api.ChangeToPrepaidRequest{ + Duration: 1, + RelationCds: true, + } + _, err := BCC_CLIENT.ChangeToPrepaid(BCC_TestBccId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBindInstanceToTags(t *testing.T) { + args := &api.BindTagsRequest{ + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, + } + err := BCC_CLIENT.BindInstanceToTags(BCC_TestBccId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnBindInstanceToTags(t *testing.T) { + args := &api.UnBindTagsRequest{ + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, + } + err := BCC_CLIENT.UnBindInstanceToTags(BCC_TestBccId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetInstanceNoChargeList(t *testing.T) { + listArgs := &api.ListInstanceArgs{} + _, err := BCC_CLIENT.GetInstanceNoChargeList(listArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateBidInstance(t *testing.T) { + createInstanceArgs := &api.CreateInstanceArgs{ + ImageId: "ImageId", + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingBidding, + }, + InstanceType: api.InstanceTypeN3, + CpuCount: 1, + MemoryCapacityInGB: 4, + RootDiskSizeInGb: 40, + RootDiskStorageType: api.StorageTypeHP1, + ZoneName: "zoneName", + SubnetId: "SubnetId", + SecurityGroupId: "SecurityGroupId", + RelationTag: true, + PurchaseCount: 1, + Name: "sdkTest", + BidModel: "BidModel", + BidPrice: "BidPrice", + } + createResult, err := BCC_CLIENT.CreateBidInstance(createInstanceArgs) + ExpectEqual(t.Errorf, err, nil) + BCC_TestBccId = createResult.InstanceIds[0] +} + +func TestCancelBidOrder(t *testing.T) { + createInstanceArgs := &api.CancelBidOrderRequest{ + OrderId: "OrderId", + } + _, err := BCC_CLIENT.CancelBidOrder(createInstanceArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestInstancePurchaseReserved(t *testing.T) { + purchaseReservedArgs := &api.PurchaseReservedArgs{ + Billing: api.Billing{ + PaymentTiming: api.PaymentTimingPrePaid, + Reservation: &api.Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "MONTH", + }, + }, + RelatedRenewFlag: "", + } + _, err := BCC_CLIENT.InstancePurchaseReserved(BCC_TestBccId, purchaseReservedArgs) + // fmt.Print(err) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetAvailableDiskInfo(t *testing.T) { + zoneName := "cn-bj-a" + if res, err := BCC_CLIENT.GetAvailableDiskInfo(zoneName); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) + } else { + fmt.Println("Get the specific zone flavor success, result: ", res) + } +} + +func TestListTypeZones(t *testing.T) { + args := &api.ListTypeZonesArgs{ + InstanceType: "", + ProductType: "", + Spec: "bcc.g3.c2m12", + SpecId: "", + } + if res, err := BCC_CLIENT.ListTypeZones(args); err != nil { + fmt.Println("Get the specific zone flavor failed: ", err) + } else { + fmt.Println("Get the specific zone flavor success, result: ", res) + } +} + +func TestListInstanceEnis(t *testing.T) { + instanceId := "InstanceId" + if res, err := BCC_CLIENT.ListInstanceEnis(instanceId); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success, result: ", res) + } +} + +func TestCreateKeypair(t *testing.T) { + args := &api.CreateKeypairArgs{ + Name: "gosdk", + Description: "go sdk test", + } + if res, err := BCC_CLIENT.CreateKeypair(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success, result: ", res) + } +} + +func TestImportKeypair(t *testing.T) { + args := &api.ImportKeypairArgs{ + ClientToken: "", + Name: "goImport", + Description: "go sdk test", + PublicKey: "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCNItVsPPOYbMH4W5fyFqoYZwfL2A1G9IWgofhrrNYVmUr22qx42FPcyR6Fj1frHGNUIZ0NN3CzS8wXg/aKWJkYMiZGjlwmppdrNGWUjmPZD9GbHw/w8sVGCBEyyCEVlTZHQe+AgfzOr/yzqpUmCareBIlQDlR1PzX39wDf7ohpzmJy2e+B+amNy2pgsxG9OI9a4RacGLAeD/OTE/nvj027pEwbWbxM1BsJjrMeH51gWGqv8zANJFL2MGqdBaUGH0r4iXTWGZ+TkA1L7np8qWNCwquve2iy8dlHw7OnzA+hsFVZJROjJimzMY+yNNiy3CqzdO+WaBXG9MWUxtLf3ZjF", + } + if res, err := BCC_CLIENT.ImportKeypair(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success, result: ", res) + } +} + +func TestListKeypairs(t *testing.T) { + args := &api.ListKeypairArgs{ + Marker: "", + MaxKeys: 0, + Name: "ac", + } + if res, err := BCC_CLIENT.ListKeypairs(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success, result: ", res) + } +} + +func TestRenameKeypair(t *testing.T) { + args := &api.RenameKeypairArgs{ + Name: "renameKeypair", + KeypairId: "KeypairId", + } + if err := BCC_CLIENT.RenameKeypair(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success") + } +} + +func TestUpdateKeypairDescription(t *testing.T) { + args := &api.KeypairUpdateDescArgs{ + KeypairId: "KeypairId", + Description: "UpdateKeypairDescription test", + } + if err := BCC_CLIENT.UpdateKeypairDescription(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success") + } +} + +func TestGetKeypairDetail(t *testing.T) { + keypairId := "KeypairId" + if resp, err := BCC_CLIENT.GetKeypairDetail(keypairId); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success resp:", resp.Keypair.InstanceCount) + } +} + +func TestAttachKeypair(t *testing.T) { + args := &api.AttackKeypairArgs{ + KeypairId: "KeypairId", + InstanceIds: []string{"InstanceId"}, + } + if err := BCC_CLIENT.AttachKeypair(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success") + } +} + +func TestDetachKeypair(t *testing.T) { + args := &api.DetachKeypairArgs{ + KeypairId: "KeypairId", + InstanceIds: []string{"InstanceId"}, + } + if err := BCC_CLIENT.DetachKeypair(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success") + } +} + +func TestDeleteKeypair(t *testing.T) { + args := &api.DeleteKeypairArgs{ + KeypairId: "KeypairId", + } + if err := BCC_CLIENT.DeleteKeypair(args); err != nil { + fmt.Println("Get specific instance eni failed: ", err) + } else { + fmt.Println("Get specific instance eni success") + } +} + +func TestBatchCreateAutoRenewRules(t *testing.T) { + bccAutoRenewArgs := &api.BccCreateAutoRenewArgs{ + InstanceId: BCC_TestBccId, + RenewTimeUnit: "month", + RenewTime: 1, + } + err := BCC_CLIENT.BatchCreateAutoRenewRules(bccAutoRenewArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchDeleteAutoRenewRules(t *testing.T) { + bccAutoRenewArgs := &api.BccDeleteAutoRenewArgs{ + InstanceId: BCC_TestBccId, + } + err := BCC_CLIENT.BatchDeleteAutoRenewRules(bccAutoRenewArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteInstanceIngorePayment(t *testing.T) { + args := &api.DeleteInstanceIngorePaymentArgs{ + InstanceId: "InstanceId", + RelatedReleaseFlag: true, + DeleteRelatedEnisFlag: true, + DeleteCdsSnapshotFlag: true, + } + if res, err := BCC_CLIENT.DeleteInstanceIngorePayment(args); err != nil { + fmt.Println("delete instance failed: ", err) + } else { + fmt.Println("delete instance success, result: ", res) + } +} + +func TestRecoveryInstance(t *testing.T) { + args := &api.RecoveryInstanceArgs{ + InstanceIds: []api.RecoveryInstanceModel{ + { + InstanceId: BCC_TestBccId, + }, + }, + } + if err := BCC_CLIENT.RecoveryInstance(args); err != nil { + fmt.Println("recovery instance failed: ", err) + } else { + fmt.Println("recovery instance success") + } +} + +func TestGetAllStocks(t *testing.T) { + if res, err := BCC_CLIENT.GetAllStocks(); err != nil { + fmt.Println("get all stocks failed: ", err) + } else { + fmt.Println("get all stocks success, result: ", res) + } +} + +func TestGetStockWithDeploySet(t *testing.T) { + args := &api.GetStockWithDeploySetArgs{ + Spec: "bcc.g3.c2m8", + DeploySetIds: []string{"DeploySetId"}, + } + if res, err := BCC_CLIENT.GetStockWithDeploySet(args); err != nil { + fmt.Println("get stock with deploySet failed: ", err) + } else { + fmt.Println("get stock with deploySet, result: ", res) + } +} + +func TestGetStockWithSpec(t *testing.T) { + args := &api.GetStockWithSpecArgs{ + Spec: "bcc.g3.c2m8", + DeploySetIds: []string{"dset-RekVqK7V"}, + } + if res, err := BCC_CLIENT.GetStockWithSpec(args); err != nil { + fmt.Println("get stock with spec failed: ", err) + } else { + fmt.Println("get stock with spec, result: ", res) + } +} + +func TestListInstanceByInstanceIds(t *testing.T) { + args := &api.ListInstanceByInstanceIdArgs{ + InstanceIds: []string{"i-gRYyYyjr", "i-GGc7Buqs"}, + Marker: "", + MaxKeys: 3, + } + result, err := BCC_CLIENT.ListInstanceByInstanceIds(args) + if err != nil { + fmt.Println("list instance failed: ", err) + } else { + fmt.Println("list instance success") + data, e := json.Marshal(result) + if e != nil { + fmt.Println("json marshal failed!") + return + } + fmt.Printf("list instance : %s", data) + } +} + +func TestListServersByMarkerV3(t *testing.T) { + args := &api.ListServerRequestV3Args{ + Marker: "", + MaxKeys: 3, + } + result, err := BCC_CLIENT.ListServersByMarkerV3(args) + if err != nil { + fmt.Println("list instance failed: ", err) + } else { + fmt.Println("list instance success") + data, e := json.Marshal(result) + if e != nil { + fmt.Println("json marshal failed!") + return + } + fmt.Printf("list instance : %s", data) + } +} + +func TestDeletePrepayVolume(t *testing.T) { + args := &api.VolumePrepayDeleteRequestArgs{ + VolumeId: "v-tVDW1NkK", + RelatedReleaseFlag: false, + } + result, err := BCC_CLIENT.DeletePrepayVolume(args) + if err != nil { + fmt.Println("delete volume failed: ", err) + } else { + fmt.Println("delete volume success") + data, e := json.Marshal(result) + if e != nil { + fmt.Println("json marshal failed!") + return + } + fmt.Printf("delete volume : %s", data) + } +} + +func TestBatchDeleteInstanceWithRelateResource(t *testing.T) { + args := &api.BatchDeleteInstanceWithRelateResourceArgs{ + RelatedReleaseFlag: true, + BccRecycleFlag: true, + InstanceIds: []string{"i-gRYyYyjx", "i-GGc7Buqd"}, + } + + err := BCC_CLIENT.BatchDeleteInstanceWithRelateResource(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchStartInstance(t *testing.T) { + args := &api.BatchStartInstanceArgs{ + InstanceIds: []string{"i-gRYyYyjx", "i-GGc7Buqd"}, + } + err := BCC_CLIENT.BatchStartInstance(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestBatchStopInstance(t *testing.T) { + args := &api.BatchStopInstanceArgs{ + ForceStop: true, + StopWithNoCharge: false, + InstanceIds: []string{"i-gRYyYyjx", "i-GGc7Buqd"}, + } + err := BCC_CLIENT.BatchStopInstance(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListInstanceTypes(t *testing.T) { + listArgs := &api.ListInstanceTypeArgs{ + ZoneName: "cn-bj-a", + } + res, err := BCC_CLIENT.ListInstanceTypes(listArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestListIdMappings(t *testing.T) { + listArgs := &api.ListIdMappingArgs{ + IdType: "shot", + ObjectType: "vm", + InstanceIds: []string{ + "i-wQzV1qYZ", + "i-b1jcrdt5", + }, + } + res, err := BCC_CLIENT.ListIdMappings(listArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestBatchResizeInstance(t *testing.T) { + listArgs := &api.BatchResizeInstanceArgs{ + Spec: "spec", + InstanceIdList: []string{ + "i-wQzV1qYZ", + "i-b1jcrdt5", + }, + } + res, err := BCC_CLIENT.BatchResizeInstance(listArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestClient_DeleteSecurityGroupRule(t *testing.T) { + args := &api.DeleteSecurityGroupRuleArgs{ + SecurityGroupRuleId: "r-zkcrsnesy13b", + } + err := BCC_CLIENT.DeleteSecurityGroupRule(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateSecurityGroupRule(t *testing.T) { + remark := "" + args := &api.UpdateSecurityGroupRuleArgs{ + SecurityGroupRuleId: "r-sdxzpzxe2igh", + Remark: &remark, + } + err := BCC_CLIENT.UpdateSecurityGroupRule(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetInstanceDeleteProgress(t *testing.T) { + args := &api.GetInstanceDeleteProgressArgs{ + InstanceIds: []string{ + BCC_TestBccId, + }, + } + + res, err := BCC_CLIENT.GetInstanceDeleteProgress(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(res) +} + +func TestTagVolume(t *testing.T) { + tagArgs := &api.TagVolumeArgs{ + ChangeTags: []api.Tag{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, + } + err := BCC_CLIENT.TagVolume(BCC_TestCdsId, tagArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUntagVolume(t *testing.T) { + tagArgs := &api.TagVolumeArgs{ + ChangeTags: []api.Tag{ + { + TagKey: "go-SDK-Tag-Key3", + TagValue: "go_SDK-Tag-Value2", + }, + }, + } + err := BCC_CLIENT.UntagVolume(BCC_TestCdsId, tagArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestTagSnapshotChain(t *testing.T) { + tagArgs := &api.TagVolumeArgs{ + ChangeTags: []api.Tag{ + { + TagKey: "go-k", + TagValue: "go-v", + }, + }, + } + err := BCC_CLIENT.TagSnapshotChain("sl-PdPu6Oel", tagArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUntagSnapshotChain(t *testing.T) { + tagArgs := &api.TagVolumeArgs{ + ChangeTags: []api.Tag{ + { + TagKey: "go-k", + TagValue: "go-v", + }, + }, + } + err := BCC_CLIENT.UntagSnapshotChain("sl-PdPu6Oel", tagArgs) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListAvailableResizeSpecs(t *testing.T) { + listAvailableResizeSpecsArgs := &api.ListAvailableResizeSpecsArgs{ + Spec: "bcc.ic5.c1m1", + Zone: "cn-bj-a", + } + createResult, err := BCC_CLIENT.ListAvailableResizeSpecs(listAvailableResizeSpecsArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(createResult) +} + +func TestBatchChangeInstanceToPrepay(t *testing.T) { + batchChangeInstanceToPrepayArgs := &api.BatchChangeInstanceToPrepayArgs{ + Config: []api.PrepayConfig{ + { + InstanceId: BCC_TestBccId, + Duration: 1, + CdsList: []string{ + BCC_TestCdsId, + }, + }, + }, + } + result, err := BCC_CLIENT.BatchChangeInstanceToPrepay(batchChangeInstanceToPrepayArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestBatchChangeInstanceToPostpay(t *testing.T) { + batchChangeInstanceToPostArgs := &api.BatchChangeInstanceToPostpayArgs{ + Config: []api.PostpayConfig{ + { + InstanceId: BCC_TestBccId, + CdsList: []string{ + BCC_TestCdsId, + }, + }, + }, + } + result, err := BCC_CLIENT.BatchChangeInstanceToPostpay(batchChangeInstanceToPostArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestListInstanceRoles(t *testing.T) { + result, err := BCC_CLIENT.ListInstanceRoles() + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestBindInstanceRole(t *testing.T) { + bindInstanceRoleArgs := &api.BindInstanceRoleArgs{ + RoleName: "Test_BCC", + Instances: []api.Instances{ + { + InstanceId: BCC_TestBccId, + }, + }, + } + + result, err := BCC_CLIENT.BindInstanceRole(bindInstanceRoleArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestUnBindInstanceRole(t *testing.T) { + unbindInstanceRoleArgs := &api.UnBindInstanceRoleArgs{ + RoleName: "Test_BCC", + Instances: []api.Instances{ + { + InstanceId: BCC_TestBccId, + }, + }, + } + + result, err := BCC_CLIENT.UnBindInstanceRole(unbindInstanceRoleArgs) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestDeleteIpv6(t *testing.T) { + deleteIpv6Args := &api.DeleteIpv6Args{ + InstanceId: BCC_TestBccId, + Reboot: true, + } + + err := BCC_CLIENT.DeleteIpv6(deleteIpv6Args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAddIpv6(t *testing.T) { + addIpv6Args := &api.AddIpv6Args{ + InstanceId: BCC_TestBccId, + Reboot: true, + Ipv6Address: "2400:da00:e003:0:41c:4100:0:2", + } + + result, err := BCC_CLIENT.AddIpv6(addIpv6Args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestBindImageToTags(t *testing.T) { + args := &api.BindTagsRequest{ + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, + } + err := BCC_CLIENT.BindImageToTags(BCC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUnBindImageToTags(t *testing.T) { + args := &api.UnBindTagsRequest{ + ChangeTags: []model.TagModel{ + { + TagKey: "TagKey", + TagValue: "TagValue", + }, + }, + } + err := BCC_CLIENT.UnBindImageToTags(BCC_TestImageId, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateRemoteCopySnapshot(t *testing.T) { + args := &api.RemoteCopySnapshotArgs{ + ClientToken: "ClientTokenForTest", + DestRegionInfos: []api.DestRegionInfo{ + { + Name: "Test", + DestRegion: "bj", + }, + }, + } + result, err := BCC_CLIENT.CreateRemoteCopySnapshot("s-S9HdTie0", args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestImportCustomImage(t *testing.T) { + args := &api.ImportCustomImageArgs{ + OsName: "Centos", + OsArch: "32", + OsType: "linux", + OsVersion: "6.5", + Name: "import_image_test", + BosURL: "http://cloud.baidu.com/testurl", + } + + result, err := BCC_CLIENT.ImportCustomImage(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestGetAvailableImagesBySpec(t *testing.T) { + + args := &api.GetAvailableImagesBySpecArg{ + OsName: "Centos", + Spec: "bcc.ic4.c1m1", + MaxKeys: 1, + Marker: "m-21bmeYvH", + } + + result, err := BCC_CLIENT.GetAvailableImagesBySpec(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestListCDSVolumeV3New(t *testing.T) { + + args := &api.ListCDSVolumeArgs{ + ChargeFilter: "postpay", + Name: "cdsTest", + UsageFilter: "data", + } + + result, err := BCC_CLIENT.ListCDSVolumeV3(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} + +func TestListCDSVolumeNew(t *testing.T) { + + args := &api.ListCDSVolumeArgs{ + ChargeFilter: "postpay", + Name: "test-ebcc-api-gc_datadiskvCSM", + UsageFilter: "data", + } + + result, err := BCC_CLIENT.ListCDSVolume(args) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(result) +} diff --git a/bce-sdk-go/services/bcc/config.json b/bce-sdk-go/services/bcc/config.json new file mode 100644 index 0000000..61e7c8e --- /dev/null +++ b/bce-sdk-go/services/bcc/config.json @@ -0,0 +1,5 @@ +{ + "AK":"", + "SK":"", + "Endpoint":"" +} \ No newline at end of file diff --git a/bce-sdk-go/services/bci/bci.go b/bce-sdk-go/services/bci/bci.go new file mode 100644 index 0000000..35a58ef --- /dev/null +++ b/bce-sdk-go/services/bci/bci.go @@ -0,0 +1,139 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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 bci + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateInstance - create a bci with the specific parameters +// +// PARAMS: +// - args: the arguments to create a bci +// +// RETURNS: +// - *CreateInstanceResult: the result of create bci +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstance(args *CreateInstanceArgs) (*CreateInstanceResult, error) { + if args == nil { + return nil, fmt.Errorf("The CreateInstanceArgs cannot be nil.") + } + + result := &CreateInstanceResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForBci()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListInstance - list all bcis with the specific parameters +// +// PARAMS: +// - args: the arguments to list all bcis +// +// RETURNS: +// - *ListInstanceResult: the result of list all bcis +// - error: nil if success otherwise the specific error +func (c *Client) ListInstances(args *ListInstanceArgs) (*ListInstanceResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListInstanceArgs cannot be nil.") + } + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListInstanceResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForBci()). + WithMethod(http.GET). + WithQueryParam("keywordType", args.KeywordType). + WithQueryParamFilter("keyword", args.Keyword). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetInstance - query bci detail with the specific parameters +// +// PARAMS: +// - args: the arguments to list all bci +// +// RETURNS: +// - *GetInstanceResult: the result of query bci detail +// - error: nil if success otherwise the specific error +func (c *Client) GetInstance(args *GetInstanceArgs) (*GetInstanceResult, error) { + if args == nil { + return nil, fmt.Errorf("The GetInstanceArgs cannot be nil.") + } + + result := &GetInstanceResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForBciId(args.InstanceId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// DeleteInstance - delete a bci +// +// PARAMS: +// - args: the arguments to delete a bci +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstance(args *DeleteInstanceArgs) error { + if args == nil { + return fmt.Errorf("The DeleteInstanceArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForBciId(args.InstanceId)). + WithMethod(http.DELETE). + WithQueryParamFilter("relatedReleaseFlag", strconv.FormatBool(args.RelatedReleaseFlag)). + Do() +} + +// BatchDeleteInstance - batch delete bcis +// +// PARAMS: +// - args: the arguments to batch delete bcis +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDeleteInstance(args *BatchDeleteInstanceArgs) error { + if args == nil { + return fmt.Errorf("The BatchDeleteInstanceArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForBci() + "/batchDel"). + WithMethod(http.POST). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/bci/client.go b/bce-sdk-go/services/bci/client.go new file mode 100644 index 0000000..65acdf2 --- /dev/null +++ b/bce-sdk-go/services/bci/client.go @@ -0,0 +1,52 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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 bci + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX_v2 = bce.URI_PREFIX + "v2" + DEFAULT_PREFIX = URI_PREFIX_v2 + + DEFAULT_BCI_ENDPOINT = "bci." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_BCI_URL = "/instance" +) + +// Client of BCI service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_BCI_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForBci() string { + return DEFAULT_PREFIX + REQUEST_BCI_URL +} + +func getURLForBciId(bciId string) string { + return getURLForBci() + "/" + bciId +} diff --git a/bce-sdk-go/services/bci/client_test.go b/bce-sdk-go/services/bci/client_test.go new file mode 100644 index 0000000..95e8c56 --- /dev/null +++ b/bce-sdk-go/services/bci/client_test.go @@ -0,0 +1,207 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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 bci + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BCI_CLIENT *Client + BciInstanceId string +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + BCI_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateInstance(t *testing.T) { + args := &CreateInstanceArgs{ + Name: "cym-bci-test", + ZoneName: "zoneC", + SubnetIds: []string{"sbn-g463qx0aqu7q"}, + SecurityGroupIds: []string{"g-59gf44p4jmwe"}, + RestartPolicy: "Always", + AutoCreateEip: false, + EipRouteType: "BGP", + EipBandwidthInMbps: 150, + EipBillingMethod: "ByTraffic", + Tags: []Tag{ + { + TagKey: "mytag", + TagValue: "serverglen", + }, + }, + ImageRegistryCredentials: []ImageRegistryCredential{ + { + Server: "docker.io/wywcoder", + UserName: "wywcoder", + Password: "Qaz123456", + }, + }, + Containers: []Container{ + { + Name: "container01", + Image: "registry.baidubce.com/bci-zjm-public/ubuntu:18.04", + Memory: 1, + CPU: 0.5, + WorkingDir: "", + ImagePullPolicy: "IfNotPresent", + Commands: []string{ + "/bin/sh", + "-c", + "sleep 30000 && exit 0", + }, + VolumeMounts: []VolumeMount{ + { + MountPath: "/usr/local/share", + ReadOnly: false, + Name: "emptydir", + Type: "EmptyDir", + }, + { + MountPath: "/config", + ReadOnly: false, + Name: "configfile", + Type: "ConfigFile", + }, + }, + Ports: []Port{ + { + Port: 8099, + Protocol: "TCP", + }, + }, + EnvironmentVars: []Environment{ + { + Key: "java", + Value: "/usr/local/jre", + }, + }, + }}, + Volume: &Volume{ + Nfs: []NfsVolume{}, + EmptyDir: []EmptyDirVolume{ + { + Name: "emptydir", + }, + }, + ConfigFile: []ConfigFileVolume{ + { + Name: "configfile", + ConfigFiles: []ConfigFileDetail{ + { + Path: "podconfig", + File: "filenxx", + }, + }, + }}, + }, + } + // res, _ := json.Marshal(args) + // fmt.Println(string(res)) + result, err := BCI_CLIENT.CreateInstance(args) + fmt.Printf("CreateInstance result: %+v, err: %+v \n", result, err) + ExpectEqual(t.Errorf, nil, err) + BciInstanceId = result.InstanceId +} + +func TestClient_ListInstance(t *testing.T) { + args := &ListInstanceArgs{ + MaxKeys: 5, + } + result, err := BCI_CLIENT.ListInstances(args) + fmt.Printf("ListInstances result: %+v, err: %+v \n", result, err) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetInstance(t *testing.T) { + args := &GetInstanceArgs{ + InstanceId: BciInstanceId, + } + result, err := BCI_CLIENT.GetInstance(args) + fmt.Printf("GetInstance err: %+v, result: %+v \n", err, *result.Instance) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteInstance(t *testing.T) { + args := &DeleteInstanceArgs{ + InstanceId: BciInstanceId, + RelatedReleaseFlag: true, + } + err := BCI_CLIENT.DeleteInstance(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BatchDeleteInstance(t *testing.T) { + args := &BatchDeleteInstanceArgs{ + InstanceIds: []string{BciInstanceId}, + RelatedReleaseFlag: true, + } + err := BCI_CLIENT.BatchDeleteInstance(args) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/bci/model.go b/bce-sdk-go/services/bci/model.go new file mode 100644 index 0000000..26cf080 --- /dev/null +++ b/bce-sdk-go/services/bci/model.go @@ -0,0 +1,294 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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 bci + +type CreateInstanceArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + ZoneName string `json:"zoneName,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + SubnetIds []string `json:"subnetIds,omitempty"` + RestartPolicy string `json:"restartPolicy,omitempty"` + EipIp string `json:"eipIp,omitempty"` + AutoCreateEip bool `json:"autoCreateEip,omitempty"` + EipName string `json:"eipName,omitempty"` + EipRouteType string `json:"eipRouteType,omitempty"` + EipBandwidthInMbps int `json:"eipBandwidthInMbps,omitempty"` + EipBillingMethod string `json:"eipBillingMethod,omitempty"` + GPUType string `json:"gpuType,omitempty"` + TerminationGracePeriodSeconds int64 `json:"terminationGracePeriodSeconds,omitempty"` + HostName string `json:"hostName,omitempty"` + Tags []Tag `json:"tags,omitempty"` + ImageRegistryCredentials []ImageRegistryCredential `json:"imageRegistryCredentials,omitempty"` + Containers []Container `json:"containers,omitempty"` + InitContainers []Container `json:"initContainers,omitempty"` + Volume *Volume `json:"volume,omitempty"` +} + +type CreateInstanceResult struct { + InstanceId string `json:"instanceId,omitempty"` +} + +type ListInstanceArgs struct { + KeywordType string `json:"keywordType,omitempty"` + Keyword string `json:"keyword,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListInstanceResult struct { + Marker string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated,omitempty"` + NextMarker string `json:"nextMarker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + Result []InstanceModel `json:"result,omitempty"` +} + +type GetInstanceArgs struct { + InstanceId string `json:"instanceId"` +} + +type GetInstanceResult struct { + Instance *InstanceDetailModel `json:"instance,omitempty"` +} + +type DeleteInstanceArgs struct { + InstanceId string `json:"instanceId"` + RelatedReleaseFlag bool `json:"relatedReleaseFlag,omitempty"` +} + +type BatchDeleteInstanceArgs struct { + InstanceIds []string `json:"instanceIds,omitempty"` + RelatedReleaseFlag bool `json:"relatedReleaseFlag,omitempty"` +} + +type InstanceDetailModel struct { + InstanceModel + Volume *Volume `json:"volume,omitempty"` + Containers []ContainerDetailModel `json:"containers,omitempty"` + InitContainers []ContainerDetailModel `json:"initContainers,omitempty"` + SecurityGroups []SecurityGroupModel `json:"securityGroups,omitempty"` + Vpc *VpcModel `json:"vpc,omitempty"` + Subnet *SubnetModel `json:"subnet,omitempty"` +} + +type ContainerDetailModel struct { + Name string `json:"name,omitempty"` + Image string `json:"image,omitempty"` + CPU float64 `json:"cpu,omitempty"` + GPU float64 `json:"gpu,omitempty"` + Memory float64 `json:"memory,omitempty"` + WorkingDir string `json:"workingDir"` + ImagePullPolicy string `json:"imagePullPolicy,omitempty"` + Commands []string `json:"commands,omitempty"` + Args []string `json:"args,omitempty"` + Ports []Port `json:"ports,omitempty"` + VolumeMounts []VolumeMount `json:"volumeMounts,omitempty"` + Envs []Environment `json:"envs,omitempty"` + CreateTime string `json:"createTime,omitempty"` + UpdateTime string `json:"updateTime,omitempty"` + DeleteTime string `json:"deleteTime,omitempty"` + PreviousState *ContainerStatus `json:"previousState,omitempty"` + CurrentState *ContainerStatus `json:"currentState,omitempty"` + Ready bool `json:"ready,omitempty"` + RestartCount int `json:"restartCount,omitempty"` +} + +type ContainerStatus struct { + State string `json:"state,omitempty"` + Reason string `json:"reason,omitempty"` + Message string `json:"message,omitempty"` + StartTime string `json:"startTime,omitempty"` + FinishTime string `json:"finishTime,omitempty"` + DetailStatus string `json:"detailStatus,omitempty"` + ExitCode int `json:"exitCode,omitempty"` +} + +type SecurityGroupModel struct { + SecurityGroupId string `json:"securityGroupId,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + VpcId string `json:"vpcId,omitempty"` +} + +type VpcModel struct { + VpcId string `json:"vpcId,omitempty"` + Name string `json:"name,omitempty"` + Cidr string `json:"cidr,omitempty"` + CreateTime string `json:"createTime,omitempty"` + Description string `json:"description,omitempty"` + IsDefault bool `json:"isDefault,omitempty"` +} + +type SubnetModel struct { + SubnetId string `json:"subnetId,omitempty"` + Name string `json:"name,omitempty"` + Cidr string `json:"cidr,omitempty"` + VpcId string `json:"vpcId,omitempty"` + SubnetType string `json:"subnetType,omitempty"` + Description string `json:"description,omitempty"` + CreateTime string `json:"createTime,omitempty"` +} + +type InstanceModel struct { + InstanceId string `json:"instanceId,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + Status string `json:"status,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + CPUType string `json:"cpuType,omitempty"` + GPUType string `json:"gpuType,omitempty"` + BandwidthInMbps int `json:"bandwidthInMbps,omitempty"` + InternalIp string `json:"internalIp,omitempty"` + PublicIp string `json:"publicIp,omitempty"` + CreateTime string `json:"createTime,omitempty"` + UpdateTime string `json:"updateTime,omitempty"` + DeleteTime string `json:"deleteTime,omitempty"` + RestartPolicy string `json:"restartPolicy,omitempty"` + Tags []Tag `json:"tags,omitempty"` +} + +type Tag struct { + TagKey string `json:"tagKey,omitempty"` + TagValue string `json:"tagValue,omitempty"` +} + +type ImageRegistryCredential struct { + Server string `json:"server,omitempty"` + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +type Container struct { + Name string `json:"name"` + Image string `json:"image"` + Memory float64 `json:"memory,omitempty"` + CPU float64 `json:"cpu,omitempty"` + GPU float64 `json:"gpu,omitempty"` + WorkingDir string `json:"workingDir"` + ImagePullPolicy string `json:"imagePullPolicy,omitempty"` + Commands []string `json:"commands,omitempty"` + Args []string `json:"args,omitempty"` + VolumeMounts []VolumeMount `json:"volumeMounts,omitempty"` + Ports []Port `json:"ports,omitempty"` + EnvironmentVars []Environment `json:"environmentVars,omitempty"` + LivenessProbe *Probe `json:"livenessProbe,omitempty"` + ReadinessProbe *Probe `json:"readinessProbe,omitempty"` + StartupProbe *Probe `json:"startupProbe,omitempty"` + Stdin bool `json:"stdin,omitempty"` + StdinOnce bool `json:"stdinOnce,omitempty"` + Tty bool `json:"tty,omitempty"` + SecurityContext *ContainerSecurityContext `json:"securityContext,omitempty"` +} + +type VolumeMount struct { + Name string `json:"name,omitempty"` + Type string `json:"type,omitempty"` + MountPath string `json:"mountPath,omitempty"` + ReadOnly bool `json:"readOnly,omitiempty"` +} + +type Port struct { + Name string `json:"name,omitempty"` + Port int `json:"port,omitempty"` + Protocol string `json:"protocol,omitempty"` +} + +type Environment struct { + Key string `json:"key,omitempty"` + Value string `json:"value,omitempty"` +} + +type Probe struct { + InitialDelaySeconds int `json:"initialDelaySeconds,omitempty"` + TimeoutSeconds int `json:"timeoutSeconds,omitempty"` + PeriodSeconds int `json:"periodSeconds,omitempty"` + SuccessThreshold int `json:"successThreshold,omitempty"` + FailureThreshold int `json:"failureThreshold,omitempty"` + TerminationGracePeriodSeconds int64 `json:"terminationGracePeriodSeconds,omitempty"` + HTTPGet *HTTPGetAction `json:"httpGet,omitempty"` + TCPSocket *TCPSocketAction `json:"tcpSocket,omitempty"` + Exec *ExecAction `json:"exec,omitempty"` + GRPC *GRPCAction `json:"grpc,omitempty"` +} + +type HTTPGetAction struct { + Path string `json:"path,omitempty"` + Port int `json:"port,omitempty"` + Scheme string `json:"scheme,omitempty"` + Host string `json:"host,omitempty"` + HTTPHeaders *HTTPHeader `json:"httpHeaders,omitempty"` +} + +type HTTPHeader struct { + Name string `json:"name,omitempty"` + Value string `json:"value,omitempty"` +} + +type TCPSocketAction struct { + Port int `json:"port,omitempty"` + Host string `json:"host,omitempty"` +} + +type ExecAction struct { + Command []string `json:"command,omitempty"` +} + +type GRPCAction struct { + Port int `json:"port,omitempty"` + Service string `josn:"service,omitempty"` +} + +type ContainerSecurityContext struct { + Capabilities *Capabilities `json:"capabilities,omitempty"` + RunAsUser int64 `json:"runAsUser,omitempty"` + RunAsGroup int64 `json:"runAsGroup,omitempty"` + RunAsNonRoot bool `json:"runAsNonRoot,omitempty"` + ReadOnlyRootFilesystem bool `json:"readOnlyRootFilesystem,omitempty"` +} + +type Capabilities struct { + Add []string `json:"add,omitempty"` + Drop []string `json:"drop,omitempty"` +} + +type Volume struct { + Nfs []NfsVolume `json:"nfs,omitempty"` + EmptyDir []EmptyDirVolume `json:"emptyDir,omitempty"` + ConfigFile []ConfigFileVolume `json:"configFile,omitempty"` +} + +type NfsVolume struct { + Name string `json:"name,omitempty"` + Server string `json:"server,omitempty"` + Path string `json:"path,omitempty"` + ReadOnly bool `json:"readOnly,omitempty"` +} + +type EmptyDirVolume struct { + Name string `json:"name,omitempty"` + Medium string `json:"medium,omitempty"` + SizeLimit float64 `json:"sizeLimit,omitempty"` +} + +type ConfigFileVolume struct { + Name string `json:"name,omitempty"` + DefaultMode int `json:"defaultMode,omitempty"` + ConfigFiles []ConfigFileDetail `json:"configFiles,omitempty"` +} + +type ConfigFileDetail struct { + Path string `json:"path,omitempty"` + File string `json:"file,omitempty"` +} diff --git a/bce-sdk-go/services/bcm/bcm.go b/bce-sdk-go/services/bcm/bcm.go new file mode 100644 index 0000000..70c7bd5 --- /dev/null +++ b/bce-sdk-go/services/bcm/bcm.go @@ -0,0 +1,119 @@ +package bcm + +import ( + "errors" + "fmt" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + // GetMetricDataPath userId - scope - metricName + GetMetricDataPath = "/json-api/v1/metricdata/%s/%s/%s" + // BatchMetricDataPath userId - scope + BatchMetricDataPath = "/json-api/v1/metricdata/metricName/%s/%s" + + Average = "average" + Maximum = "maximum" + Minimum = "minimum" + Sum = "sum" + SampleCount = "sampleCount" +) + +// GetMetricData get metric data +func (c *Client) GetMetricData(req *GetMetricDataRequest) (*GetMetricDataResponse, error) { + if len(req.UserId) <= 0 { + return nil, errors.New("userId should not be empty") + } + if len(req.Scope) <= 0 { + return nil, errors.New("scope should not be empty") + } + if len(req.MetricName) <= 0 { + return nil, errors.New("metricName should not be empty") + } + if len(req.Statistics) <= 0 { + return nil, errors.New("statistics should not be empty") + } + if req.PeriodInSecond < 10 { + return nil, errors.New("periodInSecond should not be greater 10") + } + if len(req.StartTime) <= 0 { + return nil, errors.New("startTime should not be empty") + } + if len(req.EndTime) <= 0 { + return nil, errors.New("endTime should not be empty") + } + if len(req.Dimensions) <= 0 { + return nil, errors.New("dimension should not be empty") + } + dimensionStr := "" + for key, value := range req.Dimensions { + dimensionStr = dimensionStr + key + ":" + value + ";" + } + dimensionStr = strings.TrimRight(dimensionStr, ";") + + result := &GetMetricDataResponse{} + url := fmt.Sprintf(GetMetricDataPath, req.UserId, req.Scope, req.MetricName) + err := bce.NewRequestBuilder(c). + WithURL(url). + WithQueryParam("dimensions", dimensionStr). + WithQueryParam("statistics[]", strings.Join(req.Statistics, ",")). + WithQueryParam("periodInSecond", strconv.Itoa(req.PeriodInSecond)). + WithQueryParam("startTime", req.StartTime). + WithQueryParam("endTime", req.EndTime). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} + +// BatchGetMetricData batch get metric data +func (c *Client) BatchGetMetricData(req *BatchGetMetricDataRequest) (*BatchGetMetricDataResponse, error) { + if len(req.UserId) <= 0 { + return nil, errors.New("userId should not be empty") + } + if len(req.Scope) <= 0 { + return nil, errors.New("scope should not be empty") + } + if len(req.MetricNames) <= 0 { + return nil, errors.New("metricName should not be empty") + } + if len(req.Statistics) <= 0 { + return nil, errors.New("statistics should not be empty") + } + if req.PeriodInSecond < 10 { + return nil, errors.New("periodInSecond should not be greater 10") + } + if len(req.StartTime) <= 0 { + return nil, errors.New("startTime should not be empty") + } + if len(req.EndTime) <= 0 { + return nil, errors.New("endTime should not be empty") + } + if len(req.Dimensions) <= 0 { + return nil, errors.New("dimension should not be empty") + } + dimensionStr := "" + for key, value := range req.Dimensions { + dimensionStr = dimensionStr + key + ":" + value + ";" + } + dimensionStr = strings.TrimRight(dimensionStr, ";") + + result := &BatchGetMetricDataResponse{} + url := fmt.Sprintf(BatchMetricDataPath, req.UserId, req.Scope) + err := bce.NewRequestBuilder(c). + WithURL(url). + WithQueryParam("metricName[]", strings.Join(req.MetricNames, ",")). + WithQueryParam("dimensions", dimensionStr). + WithQueryParam("statistics[]", strings.Join(req.Statistics, ",")). + WithQueryParam("periodInSecond", strconv.Itoa(req.PeriodInSecond)). + WithQueryParam("startTime", req.StartTime). + WithQueryParam("endTime", req.EndTime). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} diff --git a/bce-sdk-go/services/bcm/client.go b/bce-sdk-go/services/bcm/client.go new file mode 100644 index 0000000..f0af011 --- /dev/null +++ b/bce-sdk-go/services/bcm/client.go @@ -0,0 +1,49 @@ +package bcm + +import ( + "strings" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + ProductName = "bcm" + DefaultBcmEndpoint = ProductName + "." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN +) + +// Client of BCM service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the bcm service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + + if len(endpoint) == 0 { + endpoint = DefaultBcmEndpoint + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: map[string]struct{}{ + strings.ToLower(http.HOST): {}, + strings.ToLower(http.BCE_DATE): {}, + }, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} diff --git a/bce-sdk-go/services/bcm/client_test.go b/bce-sdk-go/services/bcm/client_test.go new file mode 100644 index 0000000..a51fbbb --- /dev/null +++ b/bce-sdk-go/services/bcm/client_test.go @@ -0,0 +1,133 @@ +package bcm + +import ( + "encoding/json" + "os" + "path/filepath" + "runtime" + "strings" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + bcmClient *Client + bcmConf *Conf +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` + InstanceId string `json:"InstanceId"` + UserId string `json:"UserId"` +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + bcmConf = &Conf{} + _ = decoder.Decode(bcmConf) + + bcmClient, _ = NewClient(bcmConf.AK, bcmConf.SK, bcmConf.Endpoint) + log.SetLogLevel(log.WARN) +} + +func TestClient_GetMetricData(t *testing.T) { + dimensions := map[string]string{ + "InstanceId": bcmConf.InstanceId, + } + req := &GetMetricDataRequest{ + UserId: bcmConf.UserId, + Scope: "BCE_BCC", + MetricName: "vCPUUsagePercent", + Dimensions: dimensions, + Statistics: strings.Split(Average+","+SampleCount+","+Sum+","+Minimum+","+Maximum, ","), + PeriodInSecond: 60, + StartTime: time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02T15:04:05Z"), + EndTime: time.Now().UTC().Add(-1 * time.Hour).Format("2006-01-02T15:04:05Z"), + } + resp, err := bcmClient.GetMetricData(req) + if err != nil { + t.Errorf("bcm get metric data error with %v\n", err) + } + if resp.Code != "OK" { + t.Errorf("bcm get metric data response code error with %v\n", resp.Code) + } + if len(resp.DataPoints) < 1 { + t.Error("bcm get metric data response dataPoints size not be greater 0\n") + } else { + if resp.DataPoints[0].Sum <= 0 { + t.Error("bcm get metric data response dataPoints[0] sum not be greater 0\n") + } + if resp.DataPoints[0].Average <= 0 { + t.Error("bcm get metric data response dataPoints[0] average not be greater 0\n") + } + if resp.DataPoints[0].SampleCount <= 0 { + t.Error("bcm get metric data response dataPoints[0] sampleCount not be greater 0\n") + } + if resp.DataPoints[0].Minimum <= 0 { + t.Error("bcm get metric data response dataPoints[0] minimum not be greater 0\n") + } + if resp.DataPoints[0].Maximum <= 0 { + t.Error("bcm get metric data response dataPoints[0] maximum not be greater 0\n") + } + } +} + +func TestClient_BatchGetMetricData(t *testing.T) { + dimensions := map[string]string{ + "InstanceId": bcmConf.InstanceId, + } + req := &BatchGetMetricDataRequest{ + UserId: bcmConf.UserId, + Scope: "BCE_BCC", + MetricNames: []string{"vCPUUsagePercent", "CpuIdlePercent"}, + Dimensions: dimensions, + Statistics: strings.Split(Average+","+SampleCount+","+Sum+","+Minimum+","+Maximum, ","), + PeriodInSecond: 60, + StartTime: time.Now().UTC().Add(-2 * time.Hour).Format("2006-01-02T15:04:05Z"), + EndTime: time.Now().UTC().Add(-1 * time.Hour).Format("2006-01-02T15:04:05Z"), + } + resp, err := bcmClient.BatchGetMetricData(req) + if err != nil { + t.Errorf("bcm batch get metric data error with %v\n", err) + } + if resp.Code != "OK" { + t.Errorf("bcm batch get metric data response code error with %v\n", resp.Code) + } + if len(resp.ErrorList) > 0 { + t.Error("bcm batch get metric data response errorList size not be lower 1\n") + } + if len(resp.SuccessList) < 2 { + t.Error("bcm batch get metric data response successList size not be greater 1\n") + } else { + if len(resp.SuccessList[0].DataPoints) <= 0 { + t.Error("bcm batch get metric data response successList dataPoints size not be greater 0\n") + } + if resp.SuccessList[0].DataPoints[0].Sum <= 0 { + t.Error("bcm batch get metric data response successList dataPoints[0] sum not be greater 0\n") + } + if resp.SuccessList[0].DataPoints[0].Average <= 0 { + t.Error("bcm batch get metric data response successList dataPoints[0] average not be greater 0\n") + } + if resp.SuccessList[0].DataPoints[0].SampleCount <= 0 { + t.Error("bcm batch get metric data response successList dataPoints[0] sampleCount not be greater 0\n") + } + if resp.SuccessList[0].DataPoints[0].Minimum <= 0 { + t.Error("bcm batch get metric data response successList dataPoints[0] minimum not be greater 0\n") + } + if resp.SuccessList[0].DataPoints[0].Maximum <= 0 { + t.Error("bcm batch get metric data response successList dataPoints[0] maximum not be greater 0\n") + } + } + +} diff --git a/bce-sdk-go/services/bcm/model.go b/bce-sdk-go/services/bcm/model.go new file mode 100644 index 0000000..b5bfac5 --- /dev/null +++ b/bce-sdk-go/services/bcm/model.go @@ -0,0 +1,64 @@ +package bcm + +type GetMetricDataRequest struct { + UserId string `json:"userId,omitempty"` + Scope string `json:"scope,omitempty"` + MetricName string `json:"metricName,omitempty"` + Dimensions map[string]string `json:"dimensions,omitempty"` + Statistics []string `json:"statistics,omitempty"` + StartTime string `json:"startTime,omitempty"` + EndTime string `json:"endTime,omitempty"` + PeriodInSecond int `json:"periodInSecond,omitempty"` +} + +type GetMetricDataResponse struct { + RequestId string `json:"requestId,omitempty"` + Code string `json:"code,omitempty"` + Message string `json:"message,omitempty"` + DataPoints []*DataPoints `json:"dataPoints,omitempty"` +} + +type DataPoints struct { + Average float64 `json:"average,omitempty"` + Sum float64 `json:"sum,omitempty"` + Minimum float64 `json:"minimum,omitempty"` + Maximum float64 `json:"maximum,omitempty"` + SampleCount int64 `json:"sampleCount,omitempty"` + Timestamp string `json:"timestamp,omitempty"` +} + +type BatchGetMetricDataRequest struct { + UserId string `json:"userId,omitempty"` + Scope string `json:"scope,omitempty"` + MetricNames []string `json:"metricNames,omitempty"` + Dimensions map[string]string `json:"dimensions,omitempty"` + Statistics []string `json:"statistics,omitempty"` + StartTime string `json:"startTime,omitempty"` + EndTime string `json:"endTime,omitempty"` + PeriodInSecond int `json:"periodInSecond,omitempty"` +} + +type BatchGetMetricDataResponse struct { + RequestId string `json:"requestId,omitempty"` + Code string `json:"code,omitempty"` + Message string `json:"message,omitempty"` + SuccessList []*SuccessBatchGetMetricData `json:"successList,omitempty"` + ErrorList []*ErrorBatchGetMetricData `json:"errorList,omitempty"` +} + +type SuccessBatchGetMetricData struct { + MetricName string `json:"metricName,omitempty"` + Dimensions []*Dimension `json:"dimensions,omitempty"` + DataPoints []*DataPoints `json:"dataPoints,omitempty"` +} + +type ErrorBatchGetMetricData struct { + MetricName string `json:"metricName,omitempty"` + Dimensions []*Dimension `json:"dimensions,omitempty"` + Message string `json:"message,omitempty"` +} + +type Dimension struct { + Name string `json:"name,omitempty"` + Value string `json:"value,omitempty"` +} diff --git a/bce-sdk-go/services/bec/api/common.go b/bce-sdk-go/services/bec/api/common.go new file mode 100644 index 0000000..88f85dc --- /dev/null +++ b/bce-sdk-go/services/bec/api/common.go @@ -0,0 +1,120 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// commond.go - commmon and shared logic + +// Package api defines all APIs supported by the BEC service of BCE. +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +type PostHttpReq struct { + Url string + Body interface{} + Result interface{} + Params map[string]string +} + +type GetHttpReq struct { + Url string + Result interface{} + Params map[string]string +} + +func Post(cli bce.Client, phr *PostHttpReq) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + + return PostOrPut(cli, phr, req) +} + +func Put(cli bce.Client, phr *PostHttpReq) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + + return PostOrPut(cli, phr, req) +} + +func PostOrPut(cli bce.Client, phr *PostHttpReq, req *bce.BceRequest) error { + req.SetUri(phr.Url) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + if phr.Body != nil { + jsonBytes, jsonErr := json.Marshal(phr.Body) + if jsonErr != nil { + return jsonErr + } + // fmt.Println(string(jsonBytes)) + bodyObj, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + req.SetBody(bodyObj) + } + + if phr.Params != nil { + req.SetParams(phr.Params) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + if phr.Result != nil { + if err := resp.ParseJsonBody(phr.Result); err != nil { + return err + } + } + return nil +} + +func Get(cli bce.Client, ghr *GetHttpReq) error { + req := &bce.BceRequest{} + req.SetUri(ghr.Url) + req.SetMethod(http.GET) + + if ghr.Params != nil { + req.SetParams(ghr.Params) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + if err := resp.ParseJsonBody(ghr.Result); err != nil { + return err + } + return nil +} + +func Delete(cli bce.Client, dhr *PostHttpReq) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + + return PostOrPut(cli, dhr, req) +} diff --git a/bce-sdk-go/services/bec/api/model.go b/bce-sdk-go/services/bec/api/model.go new file mode 100644 index 0000000..0b1524b --- /dev/null +++ b/bce-sdk-go/services/bec/api/model.go @@ -0,0 +1,1736 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +type V1VolumeMount struct { + Name string `json:"name,omitempty"` + MountPath string `json:"mountPath,omitempty"` + ReadOnly bool `json:"readOnly,omitempty"` + MountPropagation string `json:"mountPropagation,omitempty"` + SubPath string `json:"subPath,omitempty"` +} + +type V1ContainerPort struct { + Protocol string `json:"protocol,omitempty"` + ContainerPort int `json:"containerPort,omitempty"` + HostIP string `json:"hostIP,omitempty"` + HostPort int `json:"hostPort,omitempty"` + Name string `json:"name,omitempty"` +} + +type V1ConfigMapKeySelector struct { + Key string `json:"key,omitempty"` + Name string `json:"name,omitempty"` + Optional bool `json:"optional,omitempty"` +} + +type V1ObjectFieldSelector struct { + ApiVersion string `json:"apiVersion,omitempty"` + FieldPath string `json:"fieldPath,omitempty"` +} + +type V1ResourceFieldSelector struct { + ContainerName string `json:"containerName,omitempty"` + Divisor string `json:"divisor,omitempty"` + Resource string `json:"resource,omitempty"` +} + +type V1SecretKeySelector struct { + Key string `json:"key,omitempty"` + Name string `json:"name,omitempty"` + Optional string `json:"optional,omitempty"` +} + +type V1EnvVarSource struct { + ConfigMapKeyRef *V1ConfigMapKeySelector `json:"configMapKeyRef,omitempty"` + FieldRef *V1ObjectFieldSelector `json:"fieldRef,omitempty"` + ResourceFieldRef *V1ResourceFieldSelector `json:"resourceFieldRef,omitempty"` + SecretKeyRef *V1SecretKeySelector `json:"secretKeyRef,omitempty"` +} + +type V1EnvVar struct { + Name string `json:"name,omitempty"` + Value string `json:"value,omitempty"` + ValueFrom *V1EnvVarSource `json:"valueFrom,omitempty"` +} + +type ImageRegistrySecret struct { + Name string `json:"name,omitempty"` +} + +type EmptyDir struct { + Name string `json:"name,omitempty"` +} + +type ConfigFile EmptyDir + +type Secret EmptyDir + +type VolumeClaimTemplates struct { + Name string `json:"name,omitempty"` + StorageSize int `json:"storageSize,omitempty"` + DiskType string `json:"diskType,omitempty"` +} + +type Volume struct { + EmptyDir *[]EmptyDir `json:"emptyDir,omitempty"` + ConfigMap *[]ConfigFile `json:"configMap,omitempty"` + Secret *[]Secret `json:"secret,omitempty"` + VolumeClaimTemplates *[]VolumeClaimTemplates `json:"volumeClaimTemplates,omitempty"` +} + +type Tag struct { + TagKey string `json:"tagKey,omitempty"` + TagValue string `json:"tagValue,omitempty"` +} + +type Region string + +const ( + RegionCentralChina Region = "CENTRAL_CHINA" + RegionEastChina Region = "EAST_CHINA" + RegionNorthChina Region = "NORTH_CHINA" + RegionSouthChina Region = "SOUTH_CHINA" + RegionNorthEast Region = "NORTH_EAST" + RegionNorthWest Region = "NORTH_WEST" + RegionSouthWest Region = "SOUTH_WEST" +) + +type ServiceProvider string + +const ( + ServiceChinaMobile ServiceProvider = "CHINA_MOBILE" + ServiceChinaUnicom ServiceProvider = "CHINA_UNICOM" + ServiceChinaTelecom ServiceProvider = "CHINA_TELECOM" + ServiceTripleLine ServiceProvider = "TRIPLE_LINE" +) + +type DeploymentInstance struct { + Region Region `json:"region,omitempty"` + ServiceProvider ServiceProvider `json:"serviceProvider,omitempty"` + Replicas int `json:"replicas,omitempty"` + City string `json:"city,omitempty"` + RegionId string `json:"regionId,omitempty"` + NetworkType string `json:"networkType,omitempty"` + VpcId string `json:"vpcId,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + SubServiceProviders []string `json:"subServiceProviders,omitempty"` +} + +type ResourceBriefVo struct { + ServiceId string `json:"serviceId"` + ServiceName string `json:"serviceName"` + ResourceId string `json:"resourceId"` + ResourceName string `json:"resourceName"` + Labels map[string]string `json:"labels"` + TotalCpu int `json:"totalCpu"` + TotalMem int `json:"totalMem"` + TotalGpu int `json:"totalGpu"` + TotalPods int `json:"totalPods"` + RunningPods int `json:"runningPods"` + TotalDeploy int `json:"totalDeploy"` + IngressBandwidth string `json:"ingressBandwidth"` + DeployInstance DeploymentInstance `json:"deployInstance"` + ImageList []string `json:"imageList"` + Containers []ContainerDetails `json:"containers"` + ImageRegistrySecrets []ImageRegistrySecret `json:"imageRegistrySecrets"` +} + +type DeploymentResourceBriefVo struct { + ServiceId string `json:"serviceId"` + ServiceName string `json:"serviceName"` + ResourceId string `json:"resourceId"` + ResourceName string `json:"resourceName"` + TotalPods int `json:"totalPods"` + RunningPods int `json:"runningPods"` + DeployInstance DeploymentInstance `json:"deployInstance"` + Containers []ContainerDetails `json:"containers"` + PodBriefVos []PodBriefVo `json:"podBriefVos"` + CreateTime string `json:"createTime"` + LastUpdateTime string `json:"lastUpdateTime"` +} +type PodBriefVo struct { + ServiceId string `json:"serviceId"` + DeploymentName string `json:"deploymentName"` + DeploymentId string `json:"deploymentId"` + PodName string `json:"podName"` + Region string `json:"region"` + City string `json:"city"` + RegionName string `json:"regionName"` + CityName string `json:"cityName"` + Country string `json:"country"` + CountryName string `json:"countryName"` + RegionId string `json:"regionId"` + Labels map[string]string `json:"labels"` + Status string `json:"status"` + Cpu int `json:"cpu"` + Mem int `json:"mem"` + IngressBandwidth string `json:"ingressBandwidth"` + PublicIp string `json:"publicIp"` + Ipv6PublicIp string `json:"ipv6PublicIp"` + InternalIp string `json:"internalIp"` + ImageList []string `json:"imageList"` + Containers []ContainerDetails `json:"containers"` +} + +type PodDetailVo struct { + PodId string `json:"podId"` + Region string `json:"region"` + City string `json:"city"` + RegionName string `json:"regionName"` + CityName string `json:"cityName"` + Country string `json:"country"` + CountryName string `json:"countryName"` + RegionId string `json:"regionId"` + Labels map[string]string `json:"labels"` + Status string `json:"status"` + Cpu int `json:"cpu"` + Mem int `json:"mem"` + IngressBandwidth string `json:"ingressBandwidth"` + PublicIp string `json:"publicIp"` + PodIp string `json:"podIp"` + Ipv6PublicIp string `json:"ipv6PublicIp"` + InternalIp string `json:"internalIp"` + ImageList []string `json:"imageList"` + PodDataStorage int `json:"podDataStorage"` + PodEventDetails []PodEventDetails `json:"podEventDetails"` + Containers []ContainerDetails `json:"containers"` + ContainerStatuses []V1ContainerStatus `json:"containerStatuses"` + CreateTime string `json:"createTime"` +} +type PodEventDetails struct { + EventName string `json:"eventName"` + EventType string `json:"eventType"` + EventMessage string `json:"eventMessage"` +} +type V1ContainerStatus struct { + ContainerID string `json:"containerID"` + Image string `json:"image"` + ImageID string `json:"imageID"` + Name string `json:"name"` + Ready bool `json:"ready"` + RestartCount int `json:"restartCount"` + LastState V1ContainerState `json:"lastState"` + State V1ContainerState `json:"state"` +} +type V1ContainerState struct { + Running V1ContainerStateRunning `json:"running"` + Terminated V1ContainerStateTerminated `json:"terminated"` + Waiting V1ContainerStateWaiting `json:"waiting"` +} +type V1ContainerStateRunning struct { + StartedAt int `json:"startedAt"` +} +type V1ContainerStateTerminated struct { + ContainerID string `json:"containerID"` + ExitCode int `json:"exitCode"` + Signal int `json:"signal"` + StartedAt int `json:"startedAt"` + FinishedAt int `json:"finishedAt"` + Message string `json:"message"` + Reason string `json:"reason"` +} +type V1ContainerStateWaiting struct { + Message string `json:"message"` + Reason string `json:"reason"` +} + +type UpdateDeploymentReplicasRequest struct { + Replicas int `json:"replicas,omitempty"` +} + +type ServiceDetailsVo struct { + ServiceId string `json:"serviceId"` + ServiceName string `json:"serviceName"` + Status string `json:"status"` + TotalCpu int `json:"totalCpu"` + TotalMem int `json:"totalMem"` + TotalGpu int `json:"totalGpu"` + TotalDisk int `json:"totalDisk"` + TotalPods int `json:"totalPods"` + RunningPods int `json:"runningPods"` + RegionSize int `json:"regionSize"` + TagsMap []Tag `json:"tagsMap"` + DeployInstances []DeploymentInstance `json:"deployInstances"` + ResourceBriefVos []ResourceBriefVo `json:"resourceBriefVos"` + ImageRegistrySecrets []ImageRegistrySecret `json:"imageRegistrySecrets"` + LogCollectDetail LogCollectDetail `json:"logCollectDetail"` + CreateTime string `json:"createTime"` + LastUpdateTime string `json:"lastUpdateTime"` +} + +type ServiceBriefVo struct { + ServiceId string `json:"serviceId"` + ServiceName string `json:"serviceName"` + Level string `json:"level"` + Status string `json:"status"` + TotalCpu int `json:"totalCpu"` + TotalMen int `json:"totalMem"` + TotalGpu int `json:"totalGpu"` + TotalDisk int `json:"totalDisk"` + Regions int `json:"regions"` + TotalPods int `json:"totalPods"` + RunningPods int `json:"runningPods"` + TagsMap []Tag `json:"tagMap"` + DeployInstances []DeploymentInstance `json:"deployInstances"` + CreateTime string `json:"createTime"` + LastUpdateTime string `json:"lastUpdateTime"` +} + +type ContainerDetails struct { + Name string `json:"name,omitempty"` + ImageVersion string `json:"imageVersion,omitempty"` + ImageAddress string `json:"imageAddress,omitempty"` + Memory int `json:"memory,omitempty"` + Cpu int `json:"cpu,omitempty"` + Gpu int `json:"gpu,omitempty"` + WorkingDir string `json:"workingDir,omitempty"` + Commands []string `json:"commands,omitempty"` + Args []string `json:"args,omitempty"` + VolumeMounts []V1VolumeMount `json:"volumeMounts,omitempty"` + Ports []V1ContainerPort `json:"ports,omitempty"` + Envs []V1EnvVar `json:"envs,omitempty"` +} + +type LogCollectDetail struct { + ServiceId string `json:"serviceId,omitempty"` + LogCollect bool `json:"logCollect,omitempty"` + LogPath string `json:"logPath,omitempty"` + JsonAnalysis bool `json:"jsonAnalysis,omitempty"` + PushLog bool `json:"pushLog,omitempty"` + Standard bool `json:"standard,omitempty"` + Custom bool `json:"custom,omitempty"` + LogOutputType string `json:"logOutputType,omitempty"` + EsIP string `json:"esIP,omitempty"` + EsPort int `json:"esPort,omitempty"` + EsIndex string `json:"esIndex,omitempty"` + Encrypted bool `json:"encrypted,omitempty"` + EsUserName string `json:"esUserName,omitempty"` + EsUserPassword string `json:"esUserPassword,omitempty"` +} + +type CreateServiceArgs struct { + ServiceName string `json:"serviceName,omitempty"` + PaymentMethod string `json:"paymentMethod,omitempty"` + ContainerGroupName string `json:"containerGroupName,omitempty"` + Containers *[]ContainerDetails `json:"containers,omitempty"` + ImageRegistrySecrets *[]ImageRegistrySecret `json:"imageRegistrySecrets,omitempty"` + Volumes *Volume `json:"volumes,omitempty"` + NeedPublicIp bool `json:"needPublicIp,omitempty"` + NeedIpv6PublicIp bool `json:"needIpv6PublicIp,omitempty"` + Bandwidth int `json:"bandwidth,omitempty"` + Tags *[]Tag `json:"tags,omitempty"` + DeployInstances *[]DeploymentInstance `json:"deployInstances,omitempty"` + LogCollectDetail *LogCollectDetail `json:"logCollectDetail,omitempty"` +} + +type CreateServiceResult struct { + Details ServiceBriefVo `json:"details"` + Result bool `json:"result"` + Action string `json:"action"` +} + +type OrderModel struct { + OrderBy string `json:"orderBy"` + Order string `json:"order"` +} + +type ListServiceResult struct { + Result []ServiceBriefVo `json:"result"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type ListPodResult struct { + Result []PodBriefVo `json:"result"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type MetricsType string + +const ( + MetricsTypeCpu MetricsType = "CPU" + MetricsTypeMemory MetricsType = "MEMORY" + MetricsTypeBandwidthReceive MetricsType = "BANDWIDTH_RECEIVE" + MetricsTypeBandwidthTransmit MetricsType = "BANDWIDTH_TRANSMIT" + MetricsTypeTrafficReceive MetricsType = "TRAFFIC_RECEIVE" + MetricsTypeTrafficTransmit MetricsType = "TRAFFIC_TRANSMIT" + + MetricsTypeNodeBwReceive MetricsType = "NODE_BW_RECEIVE" + MetricsTypeNodeBwTransmit MetricsType = "NODE_BW_TRANSMIT" + MetricsTypeNodeLbBwReceive MetricsType = "NODE_LB_BW_RECEIVE" + MetricsTypeNodeLbBwTransmit MetricsType = "NODE_LB_BW_TRANSMIT" + + MetricsTypeRequestNum MetricsType = "REQUEST_NUMBER" + MetricsTypeRequestRate MetricsType = "REQUEST_RATE" + MetricsTypeRequestDelay MetricsType = "REQUEST_DELAY" + + MetricsTypeUnknown MetricsType = "UNKNOWN" +) + +type Metric struct { + TimeInSecond int `json:"timeInSecond"` + Value float64 `json:"value"` +} + +type ServiceMetricsResult struct { + Metrics []Metric `json:"metrics"` + MaxValue float64 `json:"maxValue"` + AvgValue float64 `json:"avgValue"` + TotalValue float64 `json:"totalValue"` +} + +type GetServiceArgs struct { + ServiceId string +} + +type ServiceAction string + +const ( + ServiceActionStart ServiceAction = "start" + ServiceActionStop ServiceAction = "stop" +) + +type ServiceActionResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type UpdateServiceType string + +const ( + UpdateServiceTypeName UpdateServiceType = "NAME" + UpdateServiceTypeReplicas UpdateServiceType = "REPLICAS" + UpdateServiceTypeNameResource UpdateServiceType = "RESOURCE" +) + +type UpdateServiceArgs struct { + Type UpdateServiceType `json:"type,omitempty"` + DeployInstances *[]DeploymentInstance `json:"deployInstances,omitempty"` + ServiceName string `json:"serviceName,omitempty"` + NeedIpv6PublicIp string `json:"needIpv6PublicIp,omitempty"` + Containers *[]ContainerDetails `json:"containers,omitempty"` + ImageRegistrySecrets *[]ImageRegistrySecret `json:"imageRegistrySecrets,omitempty"` + Bandwidth int `json:"bandwidth,omitempty"` +} + +type UpdateServiceResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details []ServiceBriefVo `json:"details"` +} + +type ServiceBatchOperateArgs struct { + IdList []string `json:"idList,omitempty"` + Action string `json:"action,omitempty"` +} + +type OperationVo struct { + ResourceId string `json:"resourceId"` + Success bool `json:"success"` + Error string `json:"error"` +} + +type ServiceBatchOperateResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details []OperationVo `json:"details"` +} + +type ListDeploymentArgs struct { + DeploymentID string `json:"deploymentID"` +} + +type Networks struct { + NetType string `json:"netType,omitempty"` + NetName string `json:"netName,omitempty"` + NicIndex int `json:"nicIndex,omitempty"` + EniId string `json:"eniId,omitempty"` + Mac string `json:"mac,omitempty"` + Ipv4 *IpAddress `json:"ipv4,omitempty"` + Ipv6 *IpAddress `json:"ipv6,omitempty"` + ReserveIps []string `json:"reserveIps,omitempty"` +} +type IpAddress struct { + Ip string `json:"ip,omitempty"` + Gw string `json:"gw,omitempty"` + Cidr string `json:"cidr,omitempty"` + Mask string `json:"mask,omitempty"` +} + +type NetworkConfig struct { + NodeType string `json:"nodeType,omitempty"` //NoneType + NetworksList *[]Networks `json:"networksList,omitempty"` +} + +type GpuRequest struct { + Type string `json:"type,omitempty"` + Num int `json:"num,omitempty"` +} + +type DiskType string + +const ( + DiskTypeNVME DiskType = "NVME" + DiskTypeSATA DiskType = "SATA" + DiskTypeCDSHDD DiskType = "CDS_HDD" + DiskTypeCDSSSD DiskType = "CDS_SSD" + DiskTypeRBDSSD DiskType = "RBD_SSD" + DiskTypeHDDPASSTHROUGH4T DiskType = "HDD_PASSTHROUGH_4T" + DiskTypeSSDPASSTHROUGH4T DiskType = "SSD_PASSTHROUGH_4T" +) + +type VolumeConfig struct { + Name string `json:"name,omitempty"` + VolumeType DiskType `json:"volumeType,omitempty"` + SizeInGB int `json:"sizeInGB,omitempty"` + PvcName string `json:"pvcName,omitempty"` + PassthroughCode string `json:"passthroughCode,omitempty"` +} + +type SystemVolumeConfig struct { + VolumeType DiskType `json:"volumeType,omitempty"` + SizeInGB int `json:"sizeInGB,omitempty"` + Name string `json:"name,omitempty"` + PvcName string `json:"pvcName,omitempty"` +} + +type DnsConfig struct { + DnsType string `json:"dnsType,omitempty"` + DnsAddress string `json:"dnsAddress,omitempty"` +} + +type KeyConfig struct { + Type string `json:"type,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + BccKeyPairIdList []string `json:"bccKeyPairIdList,omitempty"` +} + +type CreateVmServiceArgs struct { + ServiceName string `json:"serviceName,omitempty"` + VmName string `json:"vmName,omitempty"` + NeedPublicIp bool `json:"needPublicIp,omitempty"` + Bandwidth int `json:"bandwidth,omitempty"` + DeployInstances *[]DeploymentInstance `json:"deployInstances,omitempty"` + DnsConfig *DnsConfig `json:"dnsConfig,omitempty"` + Spec string `json:"spec,omitempty"` + Cpu int `json:"cpu,omitempty"` + Memory int `json:"memory,omitempty"` + ImageId string `json:"imageId,omitempty"` + ImageType ImageType `json:"imageType,omitempty"` + NeedIpv6PublicIp bool `json:"needIpv6PublicIp,omitempty"` + SystemVolume *SystemVolumeConfig `json:"systemVolume,omitempty"` + DataVolumeList *[]VolumeConfig `json:"dataVolumeList,omitempty"` + KeyConfig *KeyConfig `json:"keyConfig,omitempty"` + DisableIntranet bool `json:"disableIntranet,omitempty"` + DisableCloudInit bool `json:"disableCloudInit,omitempty"` + NetworkConfigList *[]NetworkConfig `json:"networkConfigList,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + Hostname string `json:"hostname,omitempty"` + DeploysetIdList []string `json:"deploysetIdList,omitempty"` + PaymentMethod string `json:"paymentMethod,omitempty"` + Gpu *GpuRequest `json:"gpu,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + TemplateId string `json:"templateId,omitempty"` +} + +type ImageDetail struct { + Id string `json:"id"` + ImageId string `json:"imageId"` + Name string `json:"name"` + + NameFri string `json:"nameFri"` + ImageType string `json:"imageType"` + SnapshotId string `json:"snapshotId"` + Cpu int `json:"cpu"` + Memory int `json:"memory"` + OsType string `json:"osType"` + OsVersion string `json:"osVersion"` + OsName string `json:"osName"` + OsBuild string `json:"osBuild"` + OsLang string `json:"osLang"` + DiskSize int `json:"diskSize"` + + CreateTime string `json:"createTime"` + Status string `json:"status"` + MinMem int `json:"minMem"` + MinCpu int `json:"minCpu"` + MinDiskGb int `json:"minDiskGb"` + Desc string `json:"desc"` + OsArch string `json:"osArch"` + EphemeralSize int `json:"ephemeralSize"` + ImageDescription string `json:"imageDescription"` + ShareToUserNumLimit int `json:"shareToUserNumLimit"` + SharedToUserNum int `json:"sharedToUserNum"` + FpgaType string `json:"fpgaType"` +} + +type VmInstanceIdVo struct { + VmId string `json:"vmId"` + VmName string `json:"vmName"` + Region string `json:"region"` + RegionId string `json:"regionId"` + City string `json:"city"` + ServiceProvider string `json:"serviceProvider"` +} + +type ResourceStatus string + +const ( + ResourceStatusStarting = "STARTING" + ResourceStatusRunning = "RUNNING" + ResourceStatusException = "EXCEPTION" + ResourceStatusFailed = "FAILED" + ResourceStatusUnknown = "UNKNOWN" + ResourceStatusTerminated = "TERMINATED" + ResourceStatusWaiting = "WAITING" + ResourceStatusStop = "STOP" + ResourceStatusStopping = "STOPPING" + ResourceStatusTerminating = "TERMINATING" + ResourceStatusNormal = "NORMAL" + // part of status for vm instant + ResourceStatusCreating = "CREATING" + ResourceStatusStopped = "STOPPED" + ResourceStatusRestarting = "RESTARTING" + ResourceStatusReinstalling = "REINSTALLING" + ResourceStatusImaging = "IMAGING" + // part of status for lb + ResourceStatusPending = "PENDING" + ResourceStatusBinding = "BINDING" +) + +type VmServiceBriefVo struct { + ServiceId string `json:"serviceId"` + ServiceName string `json:"serviceName"` + Status string `json:"status"` + TotalCpu int `json:"totalCpu"` + TotalMem int `json:"totalMem"` + TotalDisk int `json:"totalDisk"` + TotalRootDisk int `json:"totalRootDisk"` + Regions int `json:"regions"` + DeployInstances []DeploymentInstance `json:"deployInstances"` + TotalInstances int `json:"totalInstances"` + RunningInstances int `json:"runningInstances"` + OsImage ImageDetail `json:"osImage"` + CreateTime string `json:"createTime"` + TotalGpu int `json:"totalGpu"` + Instances []VmInstanceIdVo `json:"instances"` +} + +type CreateVmServiceResult struct { + Details VmServiceBriefVo `json:"details"` + Result bool `json:"result"` + Action string `json:"action"` +} + +type DeleteVmServiceArgs struct { + ServiceId string `json:"serviceId"` +} + +type DeleteVmServiceResult struct { + Details map[string]string `json:"details"` + Result bool `json:"result"` + Action string `json:"action"` +} + +type UpdateVmType string + +const ( + UpdateVmTypeServiceName UpdateVmType = "serviceName" + UpdateVmTypeVmName UpdateVmType = "vmName" + UpdateVmPassWord UpdateVmType = "password" + UpdateVmReplicas UpdateVmType = "replicas" + UpdateVmResource UpdateVmType = "resource" + UpdateVmSecurityGroup UpdateVmType = "securityGroup" + UpdateVmHostname UpdateVmType = "hostname" +) + +type UpdateBecVmForm struct { + Type UpdateVmType `json:"type,omitempty"` + Cpu int `json:"cpu,omitempty"` + Memory int `json:"memory,omitempty"` + NeedRestart bool `json:"needRestart,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + ImageId string `json:"imageId,omitempty"` + Bandwidth int `json:"bandwidth,omitempty"` + ImageType ImageType `json:"imageType,omitempty"` + VmName string `json:"vmName,omitempty"` + Hostname string `json:"hostname,omitempty"` + VmId string `json:"vmId,omitempty"` + DataVolumeList *[]VolumeConfig `json:"dataVolumeList,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` + SystemVolume *SystemVolumeConfig `json:"systemVolume,omitempty"` + KeyConfig *KeyConfig `json:"keyConfig,omitempty"` + DnsConfig *DnsConfig `json:"dnsConfig,omitempty"` + NeedIpv6PublicIp bool `json:"needIpv6PublicIp"` + NetworkConfigList *[]NetworkConfig `json:"networkConfigList,omitempty"` +} + +type UpdateVmServiceArgs struct { + UpdateBecVmForm + ServiceName string `json:"serviceName,omitempty"` + DeployInstances *[]DeploymentInstance `json:"deployInstances,omitempty"` + ReplicaTemplate ReplicaTemplate `json:"replicaTemplate,omitempty"` +} +type ReplicaTemplate struct { + Type string `json:"type,omitempty"` + TemplateId string `json:"templateId,omitempty"` +} +type UpdateVmServiceResult struct { + Details VmServiceBriefVo `json:"details"` + Result bool `json:"result"` + Action string `json:"action"` +} + +type ListVmServiceArgs struct { + KeywordType string `json:"keywordType,omitempty"` + Keyword string `json:"keyword,omitempty"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Order string `json:"order,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + Status string `json:"status,omitempty"` + Region string `json:"region,omitempty"` + OsName string `json:"osName,omitempty"` + ServiceId string `json:"serviceId,omitempty"` +} + +type ListVmServiceResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []VmServiceBriefVo `json:"result"` +} + +type GetVmServiceDetailArgs struct { + ServiceId string `json:"serviceId"` +} + +type VmServiceDetailsVo struct { + VmServiceBriefVo + Bandwidth string `json:"bandwidth"` + TotalBandwidth string `json:"totalBandwidth"` + DataVolumeList []VolumeConfig `json:"dataVolumeList"` + SystemVolumeList []VolumeConfig `json:"systemVolumeList"` +} + +type VmServiceAction string + +const ( + VmServiceActionStart VmServiceAction = "start" + VmServiceActionStop VmServiceAction = "stop" +) + +type VmServiceActionResult struct { + Details map[string]string `json:"details"` + Result bool `json:"result"` + Action string `json:"action"` +} + +type VmServiceBatchActionResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details []OperationVo `json:"details"` +} + +type VmServiceBatchAction string + +const ( + VmServiceBatchStart VmServiceBatchAction = "start" + VmServiceBatchStop VmServiceBatchAction = "stop" +) + +type VmServiceBatchActionArgs struct { + IdList []string `json:"idList,omitempty"` + Action VmServiceBatchAction `json:"action,omitempty"` +} + +type CreateVmImageArgs struct { + VmId string `json:"vmId,omitempty"` + Name string `json:"name,omitempty"` +} + +type CreateVmImageResult struct { + Success bool `json:"success"` + Result string `json:"result"` +} + +type VmImageOperateResult struct { + Success bool `json:"success"` + Result bool `json:"result"` +} + +type UpdateVmImageArgs struct { + Name string `json:"name,omitempty"` +} + +type ListVmImageArgs struct { + KeywordType string `json:"keywordType"` + Keyword string `json:"keyword"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Order string `json:"order,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + Status string `json:"status"` + Region string `json:"region"` + OsName string `json:"osName"` + ServiceId string `json:"serviceId"` + Type string `json:"type,omitempty"` +} + +type VmImageVo struct { + ImageId string `json:"imageId"` + Status string `json:"status"` + BccImageId string `json:"bccImageId"` + Name string `json:"name"` + AccountId string `json:"accountId"` + ImageType string `json:"imageType"` + SystemDisk int `json:"systemDisk"` + OsType string `json:"osType"` + OsVersion string `json:"osVersion"` + OsName string `json:"osName"` + OsBuild string `json:"osBuild"` + OsLang string `json:"osLang"` + OsArch string `json:"osArch"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type ListVmImageResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []VmImageVo `json:"result"` +} + +type CreateBlbArgs struct { + LbType string `json:"lbType,omitempty"` + PaymentMethod string `json:"paymentMethod,omitempty"` + Region Region `json:"region,omitempty"` + City string `json:"city,omitempty"` + ServiceProvider ServiceProvider `json:"serviceProvider,omitempty"` + RegionId string `json:"regionId,omitempty"` + SubServiceProviders []string `json:"subServiceProviders,omitempty"` + NetworkType string `json:"networkType,omitempty"` + VpcId string `json:"vpcId,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + BlbName string `json:"blbName,omitempty"` + NeedPublicIp bool `json:"needPublicIp,omitempty"` + BandwidthInMbpsLimit int `json:"bandwidthInMbpsLimit,omitempty"` + Tags *[]Tag `json:"tags,omitempty"` + Listeners *[]Listeners `json:"listeners,omitempty"` +} + +type BatchCreateBlbArgs struct { + LbType string `json:"lbType,omitempty"` + PaymentMethod string `json:"paymentMethod,omitempty"` + RegionSelection string `json:"regionSelection,omitempty"` + DeployInstances *[]DeploymentInstance `json:"deployInstances,omitempty"` + BlbName string `json:"blbName,omitempty"` + NeedPublicIp bool `json:"needPublicIp,omitempty"` + BandwidthInMbpsLimit int `json:"bandwidthInMbpsLimit,omitempty"` + Tags *[]Tag `json:"tags,omitempty"` + Listeners *[]Listeners `json:"listeners,omitempty"` +} + +type Protocol string + +const ( + ProtocolTcp Protocol = "TCP" + ProtocolUdp Protocol = "UDP" + ProtocolHttp Protocol = "HTTP" + ProtocolHttps Protocol = "HTTPS" + ProtocolSsl Protocol = "SSL" +) + +type Listeners struct { + Protocol Protocol `json:"protocol,omitempty"` + Port int `json:"port,omitempty"` + BackendPort int `json:"backendPort,omitempty"` + KeepaliveTimeout int `json:"keepaliveTimeout,omitempty"` + Scheduler LbMode `json:"scheduler,omitempty"` + EnableCipTTM bool `json:"enableCipTTM,omitempty"` + EnableVipTTM bool `json:"enableVipTTM,omitempty"` + + // health check config + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + HealthCheckRetry int `json:"healthCheckRetry,omitempty"` + HealthCheckTimeout int `json:"healthCheckTimeout,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` + HealthCheckType string `json:"healthCheckType,omitempty"` +} + +type BlbInstanceVo struct { + BlbId string `json:"blbId"` + BlbName string `json:"blbName"` + Status string `json:"status"` + LbType string `json:"lbType"` + Region Region `json:"region"` + ServiceProvider ServiceProvider `json:"serviceProvider"` + City string `json:"city"` + RegionId string `json:"regionId"` + PublicIp string `json:"publicIp"` + CmPublicIP string `json:"cmPublicIP"` + CtPublicIP string `json:"ctPublicIP"` + UnPublicIP string `json:"unPublicIP"` + InternalIp string `json:"internalIp"` + Ports []Listeners `json:"ports"` + PodCount int `json:"podCount"` + BandwidthInMbpsLimit int `json:"bandwidthInMbpsLimit"` + CreateTime string `json:"createTime"` +} + +type CreateBlbResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details BlbInstanceVo `json:"details"` +} + +type DeleteBlbResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type GetBlbListResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []BlbInstanceVo `json:"result"` +} + +type UpdateBlbArgs struct { + BlbName string `json:"blbName,omitempty"` + BandwidthInMbpsLimit int `json:"bandwidthInMbpsLimit,omitempty"` + Type string `json:"type,omitempty"` +} + +type UpdateBlbResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details BlbInstanceVo `json:"details"` +} + +type LbMode string + +const ( + LbModeWrr LbMode = "wrr" + LbModeMinConn LbMode = "minconn" + LbModeSrch LbMode = "srch" +) + +type BlbMonitorArgs struct { + FrontendPort *Port `json:"frontendPort,omitempty"` + BackendPort int `json:"backendPort,omitempty"` + LbMode LbMode `json:"lbMode,omitempty"` + KeepaliveTimeout int `json:"keepaliveTimeout,omitempty"` + HealthCheck *HealthCheck `json:"healthCheck,omitempty"` + EnableCipTTM bool `json:"enableCipTTM,omitempty"` + EnableVipTTM bool `json:"enableVipTTM,omitempty"` +} + +type BlbMonitorResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type BlbMonitorListResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []Listeners `json:"result"` +} + +type Port struct { + Protocol Protocol `json:"protocol,omitempty"` + Port int `json:"port,omitempty"` +} + +type Stats struct { + Health bool `json:"health"` + Port int `json:"port"` + Protocol Protocol `json:"protocol"` +} + +type BlbBackendPodBriefVo struct { + PodName string `json:"podName"` + PodStatus string `json:"podStatus"` + PodIp string `json:"podIp"` + BackendPort []Stats `json:"backendPort"` + Weight int `json:"weight"` +} + +type GetBlbBackendPodListResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []BlbBackendPodBriefVo `json:"result"` +} + +type BatchCreateBlbResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details []BlbInstanceVo `json:"details"` +} + +type BatchDeleteBlbResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details []OperationVo `json:"details"` +} + +type PortGroup struct { + Port int `json:"port,omitempty"` + BackendPort int `json:"backendPort,omitempty"` +} +type HealthCheck struct { + TimeoutInSeconds int `json:"timeoutInSeconds,omitempty"` + IntervalInSeconds int `json:"intervalInSeconds,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + HealthCheckString *string `json:"healthCheckString"` + HealthCheckType string `json:"healthCheckType,omitempty"` +} +type BatchCreateBlbMonitorArg struct { + Protocol Protocol `json:"protocol,omitempty"` + PortGroups *[]PortGroup `json:"portGroups,omitempty"` + LbMode LbMode `json:"lbMode,omitempty"` + KeepaliveTimeout int `json:"keepaliveTimeout,omitempty"` + HealthCheck *HealthCheck `json:"healthCheck,omitempty"` + EnableCipTTM bool `json:"enableCipTTM,omitempty"` + EnableVipTTM bool `json:"enableVipTTM,omitempty"` +} + +type BatchCreateBlbMonitorResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type ListRequest struct { + KeywordType string `json:"keywordType"` + Keyword string `json:"keyword"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Order string `json:"order,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + Status string `json:"status,omitempty"` + Region string `json:"region,omitempty"` + OsName string `json:"osName,omitempty"` + ServiceId string `json:"serviceId,omitempty"` + City string `json:"city,omitempty"` + ServiceProvider ServiceProvider `json:"serviceProvider,omitempty"` +} + +type KeyPair struct { + KeyPairId string `json:"keyPairId"` + Name string `json:"name"` +} + +type VmInstanceDetailsVo struct { + VmInstanceBriefVo + RootDiskSize int `json:"rootDiskSize"` + DataStorage int `json:"dataStorage"` + DataVolumeList []VolumeConfig `json:"dataVolumeList"` + SystemVolume SystemVolumeConfig `json:"systemVolume"` + BccKeyPairList []KeyPair `json:"bccKeyPairList"` + RackId string `json:"rackId,omitempty"` + HostId string `json:"hostId,omitempty"` + SwitchId string `json:"switchId"` + PrivateIps []string `json:"privateIps"` +} + +type LogicPageVmInstanceResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []VmInstanceDetailsVo `json:"result"` +} + +type GetNodeVmInstanceListResult struct { + Result []VmInstanceBriefVo `json:"result"` + Success bool `json:"success"` +} + +type ActionInfoVo struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} +type DeleteDeploymentActionInfoVo struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string][]string `json:"details"` +} + +type ImageType string + +const ( + ImageTypeBcc ImageType = "bcc" + ImageTypeBec ImageType = "bec" +) + +type UpdateVmInstanceArgs struct { + VmId string `json:"vmId,omitempty"` + Type string `json:"type,omitempty"` + Spec string `json:"spec,omitempty"` + Cpu int `json:"cpu,omitempty"` + Memory int `json:"memory,omitempty"` + NeedRestart bool `json:"needRestart,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + ImageId string `json:"imageId,omitempty"` + Hostname string `json:"hostname,omitempty"` + Bandwidth int `json:"bandwidth,omitempty"` + ImageType ImageType `json:"imageType,omitempty"` + VmName string `json:"vmName,omitempty"` + DataVolumeList *[]VolumeConfig `json:"dataVolumeList,omitempty"` + SystemVolume *SystemVolumeConfig `json:"systemVolume,omitempty"` + KeyConfig *KeyConfig `json:"keyConfig,omitempty"` + DnsConfig *DnsConfig `json:"dnsConfig,omitempty"` + NeedIpv6PublicIp bool `json:"needIpv6PublicIp"` + NetworkConfig *NetworkConfigUpdateVmInstance `json:"networkConfig,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds,omitempty"` +} + +type NetworkConfigUpdateVmInstance struct { + NeedPrivateNetwork bool `json:"needPrivateNetwork"` + NeedPublicNetwork bool `json:"needPublicNetwork"` + PrivateNetworkName string `json:"privateNetworkName,omitempty"` + PublicNetworkName string `json:"publicNetworkName,omitempty"` + PublicNetworkChinaMobileName string `json:"publicNetworkChinaMobileName,omitempty"` + PublicNetworkChinaUnicomName string `json:"publicNetworkChinaUnicomName,omitempty"` + PublicNetworkChinaTelecomName string `json:"publicNetworkChinaTelecomName,omitempty"` +} + +type IpInfo struct { + ServiceProvider ServiceProvider `json:"serviceProvider"` + Ip string `json:"ip"` + Ipv6 string `json:"ipv6"` +} + +type BindSecurityGroupInstances struct { + Instances []InstancesBinding `json:"instances"` +} + +type InstancesBinding struct { + InstanceId string `json:"instanceId"` + SecurityGroupIds []string `json:"securityGroupIds"` +} +type BindSecurityGroupInstancesResponse struct { + Action string `json:"action"` + Result bool `json:"result"` + Details []OperationVo `json:"details"` +} + +type IpPackageVo struct { + PublicIp string `json:"publicIp"` + Ipv6PublicIp string `json:"ipv6PublicIp"` + InternalIp string `json:"internalIp"` + MultiplePublicIp []IpInfo `json:"multiplePublicIp"` + ServiceProvider ServiceProvider `json:"serviceProvider"` +} + +type VmInstanceBriefVo struct { + IpPackageVo + VmId string `json:"vmId"` + Uuid string `json:"uuid"` + VmName string `json:"vmName"` + Status string `json:"status"` + Spec string `json:"spec"` + Cpu int `json:"cpu"` + Mem int `json:"mem"` + Gpu int `json:"gpu"` + Region Region `json:"region"` + City string `json:"city"` + RegionId string `json:"regionId"` + NeedPublicIp bool `json:"needPublicIp"` + NeedIpv6PublicIp bool `json:"needIpv6PublicIp"` + Bandwidth string `json:"bandwidth"` + OsImage ImageDetail `json:"osImage"` + ServiceId string `json:"serviceId"` + CreateTime string `json:"createTime"` + SecurityGroups []SecurityGroup `json:"securityGroups"` + Vpc Vpc `json:"vpc"` + deploysetList []DeploySetVo `json:"deploysetList"` + Hostname string `json:"hostname"` + Dns string `json:"dns"` +} + +type DeploySetVo struct { + DeploysetId string `json:"deploysetId"` + Name string `json:"name"` +} + +type SecurityGroup struct { + Id string `json:"id"` + Name string `json:"name"` + Desc string `json:"desc"` +} + +type Vpc struct { + VpcId string `json:"vpcId"` + Name string `json:"name"` + Cidr string `json:"cidr"` + Description string `json:"description"` + subnet Subnet `json:"subnet"` +} + +type Subnet struct { + SubnetId string `json:"subnetId"` + Name string `json:"name"` + Cidr string `json:"cidr"` + Description string `json:"description"` +} + +type UpdateVmDeploymentResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details VmInstanceBriefVo `json:"details"` +} + +type ReinstallVmInstanceArg struct { + AdminPass string `json:"adminPass,omitempty"` + ImageId string `json:"imageId,omitempty"` + ImageType ImageType `json:"imageType,omitempty"` + ResetDataDisk bool `json:"resetDataDisk,omitempty"` + KeyConfig *KeyConfig `json:"keyConfig,omitempty"` +} + +type ReinstallVmInstanceResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details VmInstanceBriefVo `json:"details"` +} + +type VmInstanceBatchOperateAction string + +const ( + VmInstanceBatchOperateStart VmInstanceBatchOperateAction = "start" + VmInstanceBatchOperateStop VmInstanceBatchOperateAction = "stop" + VmInstanceBatchOperateRestart VmInstanceBatchOperateAction = "restart" +) + +type OperateVmDeploymentResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type VmConfigResult struct { + Cpu int `json:"cpu"` + Mem int `json:"mem"` + Region Region `json:"region"` + ServiceProvider ServiceProvider `json:"serviceProvider"` + City string `json:"city"` + RegionId string `json:"regionId"` + NeedPublicIp bool `json:"needPublicIp"` + Bandwidth string `json:"bandwidth"` + OsImage ImageDetail `json:"osImage"` + DataVolumeList []VolumeConfig `json:"dataVolumeList"` + SystemVolume SystemVolumeConfig `json:"systemVolume"` +} + +type Backends struct { + Name string `json:"name,omitempty"` + Ip string `json:"ip,omitempty"` + Weight int `json:"weight,omitempty"` +} + +type LbDeployPo struct { + ServiceName string `json:"serviceName"` + DeploymentName string `json:"deploymentName"` + CustomOrigName string `json:"customOrigName"` + ServiceId string `json:"serviceId"` + DeploymentType string `json:"deploymentType"` + Region Region `json:"region"` + ServiceProvider ServiceProvider `json:"serviceProvider"` + City string `json:"city"` + Replicas int `json:"replicas"` + PodCpu int `json:"podCpu"` + PodMemory int `json:"podMemory"` + PodGpu int `json:"podGpu"` + PodDataStorage string `json:"podDataStorage"` + Sata int `json:"sata"` + Nvme int `json:"nvme"` + DataDiskNum int `json:"dataDiskNum"` + PodIpRequired bool `json:"podIpRequired"` + Backends []Backends `json:"backends"` +} + +type GetBlbBackendBindingStsListResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []LbDeployPo `json:"result"` +} + +type BlbBindingForm struct { + DeploymentId string `json:"deploymentId,omitempty"` + DefaultWeight int `json:"defaultWeight,omitempty"` + PodWeight *[]Backends `json:"podWeight,omitempty"` +} +type CreateBlbBindingArgs struct { + BindingForms *[]BlbBindingForm `json:"bindingForms,omitempty"` +} + +type DeleteBlbBindPodArgs struct { + PodWeightList *[]Backends `json:"podWeightList,omitempty"` + DeploymentIds []string `json:"deploymentIds,omitempty"` +} + +type DeleteBlbBindPodResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type CreateBlbBindingResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} +type UpdateBindPodWeightArgs struct { + PodWeightList *[]Backends `json:"podWeightList,omitempty"` + DeploymentIds []string `json:"deploymentIds,omitempty"` +} + +type UpdateBindPodWeightResult struct { + Result bool `json:"result"` + Action string `json:"action"` + Details map[string]string `json:"details"` +} + +type CreateVmPrivateIpForm struct { + SecondaryPrivateIpAddressCount int `json:"secondaryPrivateIpAddressCount,omitempty"` + PrivateIps []string `json:"privateIps,omitempty"` +} + +type DeleteVmPrivateIpForm struct { + PrivateIps []string `json:"privateIps,omitempty"` +} + +type IpamResultVo struct { + Success bool `json:"success"` + ErrCode string `json:"errCode"` + ErrMsg string `json:"errMsg"` + Ips []string `json:"ips"` + ErrIPs []string `json:"errIPs"` +} + +type VmPrivateIpResult struct { + Result IpamResultVo `json:"result"` + Success bool `json:"success"` +} + +type ServiceProviderInfo struct { + ServiceProvider ServiceProvider `json:"serviceProvider"` + Name string `json:"name"` + RegionId string `json:"regionId"` + Capability []string `json:"capability"` +} + +type CityInfo struct { + City string `json:"city"` + Name string `json:"name"` + ServiceProviderList []ServiceProviderInfo `json:"serviceProviderList"` +} + +type RegionInfo struct { + Region Region `json:"region"` + Name string `json:"name"` + Country string `json:"country"` + CountryName string `json:"countryName"` + CityList []CityInfo `json:"cityList"` +} + +type GetBecAvailableNodeInfoVoResult struct { + RegionList []RegionInfo `json:"regionList,omitempty"` + NodeSum int `json:"nodeSum,omitempty"` +} +type UpdateVmDeploySetArgs struct { + InstanceId string `json:"instanceId,omitempty"` + DeploysetIdList []string `json:"deploysetIdList,omitempty"` +} +type DeleteVmDeploySetArgs struct { + DeploysetId string `json:"deploysetId,omitempty"` + InstanceIdList []string `json:"instanceIdList,omitempty"` +} +type CreateDeploySetArgs struct { + Name string `json:"name,omitempty"` + Desc string `json:"desc,omitempty"` +} +type CreateDeploySetResponseArgs struct { + DeploysetIdList []string `json:"deploysetIdList,omitempty"` +} + +type LogicPageDeploySetResult struct { + Orders []OrderModel `json:"orders"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []DeploySetDetails `json:"result"` +} + +type DeploySetDetails struct { + DeploysetId string `json:"deploysetId"` + Name string `json:"name"` + Desc string `json:"desc"` + InstanceCount int `json:"instanceCount"` + InstanceTotal int `json:"instanceTotal"` + CreateTime string `json:"createTime"` + NodeInstanceStatisList []NodeInstanceStatis `json:"nodeInstanceStatisList"` +} + +type NodeInstanceStatis struct { + RegionId string `json:"regionId"` + InstanceCount int `json:"instanceCount"` + InstanceTotal int `json:"instanceTotal"` + InstanceIds []string `json:"instanceIds"` +} + +type CreateAppBlbRequest struct { + Desc string `json:"desc,omitempty"` + Name string `json:"name,omitempty"` + RegionId string `json:"regionId,omitempty"` + SubServiceProviders []string `json:"subServiceProviders,omitempty"` + NeedPublicIp bool `json:"needPublicIp,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + VpcId string `json:"vpcId,omitempty"` +} + +type CreateAppBlbResponse struct { + Desc string `json:"desc"` + Name string `json:"name"` + BlbId string `json:"blbId"` +} +type ModifyBecBlbRequest struct { + Desc string `json:"desc,omitempty"` + Name string `json:"name,omitempty"` +} + +type AppBlbDetails struct { + Address string `json:"address"` + BlbId string `json:"blbId"` + Cidr string `json:"cidr"` + CreateTime string `json:"createTime"` + Desc string `json:"desc"` + Listener []AppBlbListener `json:"listener"` + Name string `json:"name"` + PublicIp string `json:"publicIp"` + RegionId string `json:"regionId"` + Status string `json:"status"` + SubnetCidr string `json:"subnetCidr"` + SubnetId string `json:"subnetId"` + VpcId string `json:"vpcId"` + SubnetName string `json:"subnetName"` + VpcName string `json:"vpcName"` +} +type AppBlbListener struct { + Port string `json:"port"` + Type string `json:"type"` +} + +type AppBlbListResponse struct { + BlbList []AppBlbDetails `json:"blbList"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type MarkerRequest struct { + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type CreateBecAppBlbTcpListenerRequest struct { + ListenerPort int `json:"listenerPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` +} + +type CreateBecAppBlbUdpListenerRequest struct { + ListenerPort int `json:"listenerPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + UdpSessionTimeout int `json:"udpSessionTimeout,omitempty"` +} + +type UpdateBecAppBlbTcpListenerRequest struct { + Scheduler string `json:"scheduler,omitempty"` + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` +} + +type UpdateBecAppBlbUdpListenerRequest struct { + Scheduler string `json:"scheduler,omitempty"` + UdpSessionTimeout int `json:"udpSessionTimeout,omitempty"` +} + +type GetBecAppBlbListenerRequest struct { + ListenerPort int `json:"listenerPort,omitempty"` + MarkerRequest +} + +type GetBecAppBlbTcpListenerResponse struct { + IsTruncated bool `json:"isTruncated"` + ListenerList []AppBlbLTcpListenerDetail `json:"listenerList"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} +type GetBecAppBlbUdpListenerResponse struct { + IsTruncated bool `json:"isTruncated"` + ListenerList []AppBlbUdpListenerDetail `json:"listenerList"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type AppBlbLTcpListenerDetail struct { + Scheduler string `json:"scheduler"` + ListenerPort int `json:"listenerPort"` + TcpSessionTimeout int `json:"tcpSessionTimeout"` +} + +type AppBlbUdpListenerDetail struct { + Scheduler string `json:"scheduler"` + ListenerPort int `json:"listenerPort"` + UdpSessionTimeout int `json:"udpSessionTimeout"` +} + +type DeleteBlbListenerRequest struct { + PortTypeList []PortTypeList `json:"portTypeList,omitempty"` +} +type PortTypeList struct { + Port int `json:"port,omitempty"` + Type string `json:"type,omitempty"` +} +type UpdateBlbIpGroupRequest struct { + Desc string `json:"desc,omitempty"` + Name string `json:"name,omitempty"` + IpGroupId string `json:"ipGroupId,omitempty"` +} +type CreateBlbIpGroupRequest struct { + Desc string `json:"desc,omitempty"` + Name string `json:"name,omitempty"` + MemberList []BlbIpGroupMember `json:"memberList,omitempty"` +} +type BlbIpGroupMember struct { + Ip string `json:"ip,omitempty"` + Port int `json:"port,omitempty"` + Weight int `json:"weight,omitempty"` +} +type CreateBlbIpGroupResponse struct { + Desc string `json:"desc"` + Name string `json:"name"` + Id string `json:"id"` +} +type GetBlbIpGroupListRequest struct { + ExactlyMatch bool `json:"exactlyMatch,omitempty"` + Name string `json:"name,omitempty"` + MarkerRequest +} +type GetBlbIpGroupListResponse struct { + IsTruncated bool `json:"isTruncated"` + AppIpGroupList []AppIpGroupDetail `json:"appIpGroupList"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type AppIpGroupDetail struct { + BackendPolicyList []BackendPolicy `json:"backendPolicyList"` + Id string `json:"id"` + Desc string `json:"desc"` + Name string `json:"name"` +} +type BackendPolicy struct { + HealthCheck string `json:"healthCheck"` + HealthCheckHost string `json:"healthCheckHost"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` + HealthCheckUrlPath string `json:"healthCheckUrlPath"` + HealthCheckDownRetry int `json:"healthCheckDownRetry"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond"` + HealthCheckPort int `json:"healthCheckPort"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckUpRetry int `json:"healthCheckUpRetry"` + Id string `json:"id"` + Type string `json:"type"` + UdpHealthCheckString string `json:"udpHealthCheckString"` +} +type DeleteBlbIpGroupRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` +} +type CreateBlbIpGroupBackendPolicyRequest struct { + HealthCheck string `json:"healthCheck,omitempty"` + HealthCheckHost string `json:"healthCheckHost,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + HealthCheckUrlPath string `json:"healthCheckUrlPath,omitempty"` + HealthCheckDownRetry int `json:"healthCheckDownRetry,omitempty"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond,omitempty"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckUpRetry int `json:"healthCheckUpRetry,omitempty"` + IpGroupId string `json:"ipGroupId,omitempty"` + Type string `json:"type,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` +} +type CreateBlbIpGroupBackendPolicyResponse struct { + Id string `json:"id"` +} +type UpdateBlbIpGroupBackendPolicyRequest struct { + HealthCheckHost string `json:"healthCheckHost,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + HealthCheckUrlPath string `json:"healthCheckUrlPath,omitempty"` + HealthCheckDownRetry int `json:"healthCheckDownRetry,omitempty"` + HealthCheckIntervalInSecond int `json:"healthCheckIntervalInSecond,omitempty"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckUpRetry int `json:"healthCheckUpRetry,omitempty"` + IpGroupId string `json:"ipGroupId,omitempty"` + Id string `json:"id,omitempty"` + UdpHealthCheckString string `json:"udpHealthCheckString,omitempty"` +} +type GetBlbIpGroupPolicyListRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` + MarkerRequest +} +type GetBlbIpGroupPolicyListResponse struct { + IsTruncated bool `json:"isTruncated"` + BackendPolicyList []BackendPolicy `json:"backendPolicyList"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} +type DeleteBlbIpGroupBackendPolicyRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` + BackendPolicyIdList []string `json:"backendPolicyIdList,omitempty"` +} +type CreateBlbIpGroupMemberRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` + MemberList []BlbIpGroupMember `json:"memberList,omitempty"` +} +type CreateBlbIpGroupMemberResponse struct { + MemberList []BlbIpGroupMemberResponse `json:"memberList"` +} +type BlbIpGroupMemberResponse struct { + Ip string `json:"ip"` + MemberId string `json:"memberId"` + Port int `json:"port"` + Weight int `json:"weight"` +} +type UpdateBlbIpGroupMemberRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` + MemberList []UpdateBlbIpGroupMember `json:"memberList,omitempty"` +} +type UpdateBlbIpGroupMember struct { + MemberId string `json:"memberId,omitempty"` + Port int `json:"port,omitempty"` + Weight int `json:"weight,omitempty"` +} +type GetBlbIpGroupMemberListRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` + MarkerRequest +} +type GetBlbIpGroupMemberListResponse struct { + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + MemberList []BlbIpGroupMemberDetail `json:"memberList"` +} +type BlbIpGroupMemberDetail struct { + MemberId string `json:"memberId"` + Ip string `json:"ip"` + Port int `json:"port"` + Weight int `json:"weight"` +} +type DeleteBlbIpGroupBackendMemberRequest struct { + IpGroupId string `json:"ipGroupId,omitempty"` + MemberIdList []string `json:"memberIdList,omitempty"` +} +type CreateAppBlbPoliciesRequest struct { + ListenerPort int `json:"listenerPort,omitempty"` + Type string `json:"type,omitempty"` + AppPolicyVos []AppPolicyVo `json:"appPolicyVos,omitempty"` +} +type AppPolicyVo struct { + AppIpGroupId string `json:"appIpGroupId,omitempty"` + Desc string `json:"desc,omitempty"` + Priority int `json:"priority,omitempty"` +} +type GetBlbListenerPolicyRequest struct { + Port int `json:"port,omitempty"` + Type string `json:"type,omitempty"` + MarkerRequest +} +type GetBlbListenerPolicyResponse struct { + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + PolicyList []BlbListenerPolicy `json:"policyList"` +} +type BlbListenerPolicy struct { + AppIpGroupId string `json:"appIpGroupId"` + AppIpGroupName string `json:"appIpGroupName"` + Desc string `json:"desc"` + Type string `json:"type"` + Id string `json:"id"` + FrontendPort int `json:"frontendPort"` + Priority int `json:"priority"` + RuleList []BlbListenerPolicyRule `json:"ruleList"` +} +type BlbListenerPolicyRule struct { + Key string `json:"key"` + Value string `json:"value"` +} +type DeleteAppBlbPoliciesRequest struct { + Type string `json:"type,omitempty"` + Port int `json:"port,omitempty"` + PolicyIdList []string `json:"policyIdList,omitempty"` +} diff --git a/bce-sdk-go/services/bec/api/util.go b/bce-sdk-go/services/bec/api/util.go new file mode 100644 index 0000000..acf97a2 --- /dev/null +++ b/bce-sdk-go/services/bec/api/util.go @@ -0,0 +1,172 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BEC service +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + URI_PREFIX_V2 = bce.URI_PREFIX + "v2" + + DEFAULT_BEC_DOMAIN = "bec." + bce.DEFAULT_REGION + bce.DEFAULT_DOMAIN + + REQUEST_SERVICE_URL = URI_PREFIX + "/service" + REQUEST_POD_URL = URI_PREFIX + "/pod" + + REQUEST_VM_URL = URI_PREFIX + "/vm" + "/service" + + DEPLOY_SET_URL = URI_PREFIX + "/deployset" + + DEPLOYMENT_URL = URI_PREFIX + "/deployment" + + REQUEST_VM_MONITOR_URL = URI_PREFIX + "/monitor" + "/vm" + + SERVICE_MONITOR_URL = URI_PREFIX + "/monitor" + "/service" + "/sts" + + DEPLOYMENT_MONITOR_URL = URI_PREFIX + "/monitor" + "/deployment" + POD_MONITOR_URL = URI_PREFIX + "/monitor" + "/pod" + + REQUEST_VM_SERVICE_MONITOR_URL = URI_PREFIX + "/monitor" + "/service" + "/vm" + + REQUEST_VM_IMAGE_URL = URI_PREFIX + "/vm" + "/image" + + REQUEST_LOADBALANCER_URL = URI_PREFIX + "/blb" + + REQUEST_LOADBALANCER_URL_V2 = URI_PREFIX_V2 + "/appblb" + + REQUEST_LOADBALANCER_MONITOR_URL = URI_PREFIX + "/monitor" + "/lb" + + REQUEST_VM_INSTANCE_URL = URI_PREFIX + "/vm/instance" + + REQUEST_NODE_URL = URI_PREFIX + "/node" +) + +/* +var ( + MetricType = map[string]string{ + "cpu": "cpu", + "memory": "memory", + "bandwidth_receive": "bandwidth_receive", + "bandwidth_transmit": "bandwidth_transmit", + "traffic_receive": "traffic_receive", + "traffic_transmit": "traffic_transmit", + + "node_bw_receive": "node_bw_receive", + "node_bw_transmit": "node_bw_transmit", + "node_lb_bw_receive": "node_lb_bw_receive", + "node_lb_bw_transmit": "node_lb_bw_transmit", + "request_num": "request_num", + "request_rate": "request_rate", + "request_delay": "request_delay", + "unknown": "unknown", + } +) +*/ + +func GetServiceURI() string { + return REQUEST_SERVICE_URL +} + +func GetServiceMetricsURI(serviceId string) string { + return SERVICE_MONITOR_URL + "/" + serviceId +} +func GetDeploymentMetricsURI(deploymentId string) string { + return DEPLOYMENT_MONITOR_URL + "/" + deploymentId +} +func GetPodMetricsURI(podId string) string { + return POD_MONITOR_URL + "/" + podId +} +func GetServiceDetailURI(serviceId string) string { + return REQUEST_SERVICE_URL + "/" + serviceId +} +func GetDeploymentDetailURI(deploymentId string) string { + return DEPLOYMENT_URL + "/" + deploymentId +} + +func GetStartServiceURI(serviceId, action string) string { + return REQUEST_SERVICE_URL + "/" + serviceId + "/" + action +} + +func GetDeleteServiceURI(serviceId string) string { + return REQUEST_SERVICE_URL + "/" + serviceId +} + +func GetUpdateServiceURI(serviceId string) string { + return REQUEST_SERVICE_URL + "/" + serviceId +} + +func GetBachServiceOperateURI() string { + return REQUEST_SERVICE_URL + "/batch/operate" +} + +func GetBachServiceDeleteURI() string { + return REQUEST_SERVICE_URL + "/batch/delete" +} + +func GetVmURI() string { + return REQUEST_VM_URL +} + +func GetDeploySetURI() string { + return DEPLOY_SET_URL +} + +func GetAppBlbURI() string { + return REQUEST_LOADBALANCER_URL_V2 +} + +func GetVmServiceActionURI(serviceId, action string) string { + return REQUEST_VM_URL + "/" + serviceId + "/" + action +} + +func GetVmImageURI() string { + return REQUEST_VM_IMAGE_URL +} + +func GetLoadBalancerURI() string { + return REQUEST_LOADBALANCER_URL +} + +func GetLoadBalancerMonitorURI() string { + return REQUEST_LOADBALANCER_MONITOR_URL +} + +func GetVmMonitorURI() string { + return REQUEST_VM_MONITOR_URL +} + +func GetVmServiceMonitorURI() string { + return REQUEST_VM_SERVICE_MONITOR_URL +} + +func GetLoadBalancerBatchURI() string { + return REQUEST_LOADBALANCER_URL + "/batch" +} + +func GetVmServiceMetricsURI(serviceId, metricsType string) string { + return REQUEST_VM_URL + "/" + serviceId + "/metrics/" + metricsType +} + +func GetVmInstanceURI() string { + return REQUEST_VM_INSTANCE_URL +} + +func GetNodeInfoURI() string { + return REQUEST_NODE_URL +} diff --git a/bce-sdk-go/services/bec/appBlb.go b/bce-sdk-go/services/bec/appBlb.go new file mode 100644 index 0000000..5342ebc --- /dev/null +++ b/bce-sdk-go/services/bec/appBlb.go @@ -0,0 +1,698 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/services/bec/api" + "strconv" +) + +// CreateAppBlb - create app lb with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb +// +// RETURNS: +// - *CreateAppBlbResponse: the result of create app lb +// - error: nil if ok otherwise the specific error +func (c *Client) CreateAppBlb(clientToken string, args *api.CreateAppBlbRequest) (*api.CreateAppBlbResponse, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + + result := &api.CreateAppBlbResponse{} + req := &api.PostHttpReq{Url: api.GetAppBlbURI(), Result: result, Body: args, Params: params} + err := api.Post(c, req) + + return result, err +} + +// UpdateAppBlb - update app lb with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb +// +// RETURNS: +// - *CreateAppBlbResponse: the result of create app lb +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateAppBlb(clientToken, blbId string, args *api.ModifyBecBlbRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId, Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// GetAppBlbList - get app lb list with the specific parameters +// +// PARAMS: +// - args: the arguments to get app lb list +// +// RETURNS: +// - *AppBlbListResponse: the result of app lb list +// - error: nil if ok otherwise the specific error +func (c *Client) GetAppBlbList(args *api.MarkerRequest) (*api.AppBlbListResponse, error) { + + params := make(map[string]string) + if args.Marker != "" { + params["marker"] = args.Marker + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + res := &api.AppBlbListResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI(), Params: params, Result: res} + err := api.Get(c, req) + + return res, err +} + +// GetAppBlbDetails - get app lb detail with the specific parameters +// +// PARAMS: +// - blbId: the arguments to get app lb details +// +// RETURNS: +// - *AppBlbListResponse: the result of app lb detail +// - error: nil if ok otherwise the specific error +func (c *Client) GetAppBlbDetails(blbId string) (*api.AppBlbDetails, error) { + + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + res := &api.AppBlbDetails{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId, Result: res} + err := api.Get(c, req) + return res, err +} + +// DeleteAppBlbInstance - delete app lb with the specific parameters +// +// PARAMS: +// - blbId: the arguments to delete app lb +// +// RETURNS: +// - *AppBlbListResponse: the result of app lb detail +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppBlbInstance(blbId, clientToken string) error { + + if blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId, Params: params} + err := api.Delete(c, req) + return err +} + +// CreateTcpListener - create app lb tcp listener with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb tcp listener +// +// RETURNS: +// - *CreateAppBlbResponse: the result of create app lb tcp listener +// - error: nil if ok otherwise the specific error +func (c *Client) CreateTcpListener(clientToken, blbId string, args *api.CreateBecAppBlbTcpListenerRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/TCPlistener", Body: args, Params: params} + err := api.Post(c, req) + + return err +} + +// UpdateTcpListener - update app lb tcp listener with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb tcp listener +// +// RETURNS: +// - *CreateAppBlbResponse: the result of update app lb tcp listener +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateTcpListener(clientToken, blbId, listenerPort string, args *api.UpdateBecAppBlbTcpListenerRequest) error { + if args == nil || blbId == "" || listenerPort == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + params["listenerPort"] = listenerPort + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/TCPlistener", Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// GetTcpListener - get app lb tcp listener with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to get app lb tcp listener +// +// RETURNS: +// - *CreateAppBlbResponse: the result of get app lb tcp listener +// - error: nil if ok otherwise the specific error +func (c *Client) GetTcpListener(blbId string, args *api.GetBecAppBlbListenerRequest) (*api.GetBecAppBlbTcpListenerResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if args.ListenerPort != 0 { + params["listenerPort"] = strconv.Itoa(args.ListenerPort) + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + if args.Marker != "" { + params["marker"] = args.Marker + } + res := &api.GetBecAppBlbTcpListenerResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/TCPlistener", Params: params, Result: res} + err := api.Get(c, req) + + return res, err +} + +// CreateUdpListener - create app lb tcp listener with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb udp listener +// +// RETURNS: +// - *CreateAppBlbResponse: the result of create app lb udp listener +// - error: nil if ok otherwise the specific error +func (c *Client) CreateUdpListener(clientToken, blbId string, args *api.CreateBecAppBlbUdpListenerRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/UDPlistener", Body: args, Params: params} + err := api.Post(c, req) + + return err +} + +// UpdateUdpListener - update app lb udp listener with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb udp listener +// +// RETURNS: +// - *CreateAppBlbResponse: the result of update app lb udp listener +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateUdpListener(clientToken, blbId, listenerPort string, args *api.UpdateBecAppBlbUdpListenerRequest) error { + if args == nil || blbId == "" || listenerPort == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + params["listenerPort"] = listenerPort + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/UDPlistener", Body: args, Params: params} + err := api.Put(c, req) + return err +} + +// GetUdpListener - get app lb udp listener with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to get app lb udp listener +// +// RETURNS: +// - *CreateAppBlbResponse: the result of get app lb udp listener +// - error: nil if ok otherwise the specific error +func (c *Client) GetUdpListener(blbId string, args *api.GetBecAppBlbListenerRequest) (*api.GetBecAppBlbUdpListenerResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if args.ListenerPort != 0 { + params["listenerPort"] = strconv.Itoa(args.ListenerPort) + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + if args.Marker != "" { + params["marker"] = args.Marker + } + res := &api.GetBecAppBlbUdpListenerResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/UDPlistener", Params: params, Result: res} + err := api.Get(c, req) + + return res, err +} + +// DeleteAppBlbListener - delete app lb listener with the specific parameters +// +// PARAMS: +// - blbId: the arguments to delete app lb listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteAppBlbListener(blbId, clientToken string, args *api.DeleteBlbListenerRequest) error { + + if blbId == "" || args == nil { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + params["batchdelete"] = "" + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/listener", Params: params, Body: args} + err := api.Put(c, req) + return err +} + +// CreateIpGroup - create app lb ip group with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb ip group +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb ip group +// - error: nil if ok otherwise the specific error +func (c *Client) CreateIpGroup(clientToken, blbId string, args *api.CreateBlbIpGroupRequest) (*api.CreateBlbIpGroupResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + res := &api.CreateBlbIpGroupResponse{} + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup", Body: args, Params: params, Result: res} + err := api.Post(c, req) + + return res, err +} + +// UpdateIpGroup - update app lb ip group with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb ip group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateIpGroup(clientToken, blbId string, args *api.UpdateBlbIpGroupRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup", Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// GetIpGroup - get app lb ip group with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to get app lb ip group +// +// RETURNS: +// - *api.GetBlbIpGroupListResponse the result of app lb ip group +// - error: nil if ok otherwise the specific error +func (c *Client) GetIpGroup(blbId string, args *api.GetBlbIpGroupListRequest) (*api.GetBlbIpGroupListResponse, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if args.Name != "" { + params["name"] = args.Name + } + if args.ExactlyMatch != false { + params["exactlyMatch"] = strconv.FormatBool(args.ExactlyMatch) + } else { + params["exactlyMatch"] = strconv.FormatBool(false) + } + if args.Marker != "" { + params["maker"] = args.Marker + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + res := &api.GetBlbIpGroupListResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup", Params: params, Result: res} + err := api.Get(c, req) + + return res, err +} + +// DeleteIpGroup - delete app lb ip group with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to delete app lb ip group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteIpGroup(clientToken, blbId string, args *api.DeleteBlbIpGroupRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + params["delete"] = "" + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup", Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// CreateIpGroupPolicy - create app lb ip group Policy with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb ip group Policy +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb ip group Policy +// - error: nil if ok otherwise the specific error +func (c *Client) CreateIpGroupPolicy(clientToken, blbId string, args *api.CreateBlbIpGroupBackendPolicyRequest) (*api.CreateBlbIpGroupBackendPolicyResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + res := &api.CreateBlbIpGroupBackendPolicyResponse{} + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/backendpolicy", Body: args, Params: params, Result: res} + err := api.Post(c, req) + + return res, err +} + +// UpdateIpGroupPolicy - update app lb ip group Policy with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb ip group Policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateIpGroupPolicy(clientToken, blbId string, args *api.UpdateBlbIpGroupBackendPolicyRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/backendpolicy", Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// GetIpGroupPolicyList - update app lb ip group Policy list with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb ip group Policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) GetIpGroupPolicyList(blbId string, args *api.GetBlbIpGroupPolicyListRequest) (*api.GetBlbIpGroupPolicyListResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if args.IpGroupId != "" { + params["ipGroupId"] = args.IpGroupId + } + + if args.Marker != "" { + params["maker"] = args.Marker + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + res := &api.GetBlbIpGroupPolicyListResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/backendpolicy", Result: res, Params: params} + err := api.Get(c, req) + + return res, err +} + +// DeleteIpGroupPolicy - delete app lb ip group policy with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to delete app lb ip group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteIpGroupPolicy(clientToken, blbId string, args *api.DeleteBlbIpGroupBackendPolicyRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/backendpolicy", Body: args, Params: params} + err := api.Delete(c, req) + return err +} + +// CreateIpGroupMember - create app lb ip group member with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb ip group member +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb ip group member +// - error: nil if ok otherwise the specific error +func (c *Client) CreateIpGroupMember(clientToken, blbId string, args *api.CreateBlbIpGroupMemberRequest) (*api.CreateBlbIpGroupMemberResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + res := &api.CreateBlbIpGroupMemberResponse{} + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/member", Body: args, Params: params, Result: res} + err := api.Post(c, req) + + return res, err +} + +// UpdateIpGroupMember - update app lb ip group member with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb ip group member +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb ip group member +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateIpGroupMember(clientToken, blbId string, args *api.UpdateBlbIpGroupMemberRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/member", Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// GetIpGroupMemberList - get app lb ip group member list with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to update app lb ip group member +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb ip group member +// - error: nil if ok otherwise the specific error +func (c *Client) GetIpGroupMemberList(blbId string, args *api.GetBlbIpGroupMemberListRequest) (*api.GetBlbIpGroupMemberListResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if args.IpGroupId != "" { + params["ipGroupId"] = args.IpGroupId + } + + if args.Marker != "" { + params["maker"] = args.Marker + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + res := &api.GetBlbIpGroupMemberListResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/member", Result: res, Params: params} + err := api.Get(c, req) + + return res, err +} + +// DeleteIpGroupMember - delete app lb ip group member with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to delete app lb ip group member +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteIpGroupMember(clientToken, blbId string, args *api.DeleteBlbIpGroupBackendMemberRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + params["delete"] = "" + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/ipgroup/member", Body: args, Params: params} + err := api.Put(c, req) + + return err +} + +// CreateListenerPolicy - create app lb listener policy with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to create app lb ip listener policy +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb iplistener policy +// - error: nil if ok otherwise the specific error +func (c *Client) CreateListenerPolicy(clientToken, blbId string, args *api.CreateAppBlbPoliciesRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/policys", Body: args, Params: params} + err := api.Post(c, req) + + return err +} + +// GetListenerPolicy - get app lb listener policy with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to get app lb ip listener policy +// +// RETURNS: +// - *api.CreateBlbIpGroupResponse the result of app lb ip listener policy +// - error: nil if ok otherwise the specific error +func (c *Client) GetListenerPolicy(blbId string, args *api.GetBlbListenerPolicyRequest) (*api.GetBlbListenerPolicyResponse, error) { + if args == nil || blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if args.Type != "" { + params["type"] = args.Type + } + if args.Port != 0 { + params["port"] = strconv.Itoa(args.Port) + } + + if args.Marker != "" { + params["maker"] = args.Marker + } + if args.MaxKeys != 0 { + params["maxKeys"] = strconv.Itoa(args.MaxKeys) + } + res := &api.GetBlbListenerPolicyResponse{} + req := &api.GetHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/policys", Result: res, Params: params} + err := api.Get(c, req) + + return res, err +} + +// DeleteListenerPolicy - delete app lb listener policy with the specific parameters +// +// PARAMS: +// - clientToken:idempotent token,an ASCII string no longer than 64 bits,unnecessary +// - args: the arguments to delete app lb listener policy +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteListenerPolicy(clientToken, blbId string, args *api.DeleteAppBlbPoliciesRequest) error { + if args == nil || blbId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + params["batchdelete"] = "" + if clientToken != "" { + params["clientToken"] = clientToken + } + req := &api.PostHttpReq{Url: api.GetAppBlbURI() + "/" + blbId + "/policys", Body: args, Params: params} + err := api.Put(c, req) + + return err +} diff --git a/bce-sdk-go/services/bec/appBlb_test.go b/bce-sdk-go/services/bec/appBlb_test.go new file mode 100644 index 0000000..a8624d0 --- /dev/null +++ b/bce-sdk-go/services/bec/appBlb_test.go @@ -0,0 +1,276 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +////////////////////////////////////////////// +// deploy set test +////////////////////////////////////////////// + +func TestCreateAppBlb(t *testing.T) { + getReq := &api.CreateAppBlbRequest{ + Name: "wcw_test_applb", + Desc: "wcw-test", + RegionId: "cn-hangzhou-cm", + NeedPublicIp: true, + SubnetId: "sbn-tafnx9dd", + VpcId: "vpc-wljmvzmt", + } + res, err := CLIENT.CreateAppBlb("testCreateAppBlb", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateAppBlb(t *testing.T) { + getReq := &api.ModifyBecBlbRequest{ + Name: "wcw_test_applb", + Desc: "wcw-test1", + } + err := CLIENT.UpdateAppBlb("testUpdateAppBlb", "lb-zo8wibx1", getReq) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetAppBlbList(t *testing.T) { + getReq := &api.MarkerRequest{} + res, err := CLIENT.GetAppBlbList(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestGetAppBlbDetails(t *testing.T) { + + res, err := CLIENT.GetAppBlbDetails("applb-cn-hangzhou-cm-h9nh3vpe") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteAppBlbInstance(t *testing.T) { + + err := CLIENT.DeleteAppBlbInstance("applb-cn-hangzhou-cm-h9nh3vpe", "") + ExpectEqual(t.Errorf, nil, err) +} +func TestCreateTcpListener(t *testing.T) { + getReq := &api.CreateBecAppBlbTcpListenerRequest{ + ListenerPort: 80, + Scheduler: "RoundRobin", + TcpSessionTimeout: 1000, + } + err := CLIENT.CreateTcpListener("testCreateTcpListener", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestCreateUdpListener(t *testing.T) { + getReq := &api.CreateBecAppBlbUdpListenerRequest{ + ListenerPort: 80, + Scheduler: "RoundRobin", + UdpSessionTimeout: 1000, + } + err := CLIENT.CreateUdpListener("testCreateTcpListener", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestUpdateTcpListener(t *testing.T) { + getReq := &api.UpdateBecAppBlbTcpListenerRequest{ + Scheduler: "RoundRobin", + TcpSessionTimeout: 800, + } + err := CLIENT.UpdateTcpListener("testUpdateTcpListener", "applb-cn-hangzhou-cm-h9nh3vpe", "80", getReq) + ExpectEqual(t.Errorf, nil, err) +} + +func TestUpdateUdpListener(t *testing.T) { + getReq := &api.UpdateBecAppBlbUdpListenerRequest{ + Scheduler: "RoundRobin", + UdpSessionTimeout: 800, + } + err := CLIENT.UpdateUdpListener("testUpdateUdpListener", "applb-cn-hangzhou-cm-h9nh3vpe", "80", getReq) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetTcpListener(t *testing.T) { + getReq := &api.GetBecAppBlbListenerRequest{ + ListenerPort: 80, + } + res, err := CLIENT.GetTcpListener("applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetUdpListener(t *testing.T) { + getReq := &api.GetBecAppBlbListenerRequest{ + ListenerPort: 80, + } + res, err := CLIENT.GetUdpListener("applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestDeleteAppBlbListener(t *testing.T) { + getReq := &api.DeleteBlbListenerRequest{ + PortTypeList: []api.PortTypeList{ + { + Port: 80, + Type: "TCP", + }, + { + Port: 80, + Type: "UDP", + }, + }, + } + err := CLIENT.DeleteAppBlbListener("applb-cn-hangzhou-cm-h9nh3vpe", "deleteApplbInstance", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestCreateIpGroup(t *testing.T) { + getReq := &api.CreateBlbIpGroupRequest{ + Name: "wcw-testIpGroup", + Desc: "wcw-test", + } + res, err := CLIENT.CreateIpGroup("testIpGroup", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +// bec_ip_group-ukadxdrq +func TestUpdateIpGroup(t *testing.T) { + getReq := &api.UpdateBlbIpGroupRequest{ + Name: "wcw-testIpGroupupdate", + Desc: "wcw-testupdate", + IpGroupId: "bec_ip_group-ukadxdrq", + } + err := CLIENT.UpdateIpGroup("testIpGroup", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestGetIpGroup(t *testing.T) { + getReq := &api.GetBlbIpGroupListRequest{} + res, err := CLIENT.GetIpGroup("applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestDeleteIpGroup(t *testing.T) { + getReq := &api.DeleteBlbIpGroupRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + } + err := CLIENT.DeleteIpGroup("testDeleteIpGroup", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestCreateIpGroupPolicy(t *testing.T) { + getReq := &api.CreateBlbIpGroupBackendPolicyRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + Type: "TCP", + HealthCheck: "TCP", + HealthCheckPort: 80, + HealthCheckTimeoutInSecond: 10, + HealthCheckIntervalInSecond: 3, + HealthCheckDownRetry: 4, + HealthCheckUpRetry: 5, + } + res, err := CLIENT.CreateIpGroupPolicy("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestUpdateIpGroupPolicy(t *testing.T) { + getReq := &api.UpdateBlbIpGroupBackendPolicyRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + Id: "bec_ip_group_policy-yodpsqqr", + HealthCheckPort: 80, + } + err := CLIENT.UpdateIpGroupPolicy("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestGetIpGroupPolicy(t *testing.T) { + getReq := &api.GetBlbIpGroupPolicyListRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + } + res, err := CLIENT.GetIpGroupPolicyList("applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestDeleteIpGroupPolicy(t *testing.T) { + getReq := &api.DeleteBlbIpGroupBackendPolicyRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + BackendPolicyIdList: []string{"bec_ip_group_policy-yodpsqqr"}, + } + err := CLIENT.DeleteIpGroupPolicy("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + +} +func TestCreateIpGroupMember(t *testing.T) { + getReq := &api.CreateBlbIpGroupMemberRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + MemberList: []api.BlbIpGroupMember{ + { + Ip: "172.16.240.25", + Port: 90, + Weight: 100, + }, + }, + } + res, err := CLIENT.CreateIpGroupMember("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestUpdateIpGroupMember(t *testing.T) { + getReq := &api.UpdateBlbIpGroupMemberRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + MemberList: []api.UpdateBlbIpGroupMember{ + { + MemberId: "bec_ip_member-ouiinabp", + Port: 8080, + Weight: 100, + }, + }, + } + err := CLIENT.UpdateIpGroupMember("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestGetIpGroupMemberList(t *testing.T) { + getReq := &api.GetBlbIpGroupMemberListRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + } + res, err := CLIENT.GetIpGroupMemberList("applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestDeleteIpGroupMember(t *testing.T) { + getReq := &api.DeleteBlbIpGroupBackendMemberRequest{ + IpGroupId: "bec_ip_group-ukadxdrq", + MemberIdList: []string{"bec_ip_member-ouiinabp"}, + } + err := CLIENT.DeleteIpGroupMember("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + +} +func TestCreateListenerPolicy(t *testing.T) { + getReq := &api.CreateAppBlbPoliciesRequest{ + ListenerPort: 80, + AppPolicyVos: []api.AppPolicyVo{ + { + AppIpGroupId: "bec_ip_group-ukadxdrq", + Priority: 1, + Desc: "wcw-test", + }, + }, + } + err := CLIENT.CreateListenerPolicy("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetListenerPolicy(t *testing.T) { + getReq := &api.GetBlbListenerPolicyRequest{ + Port: 80, + } + res, err := CLIENT.GetListenerPolicy("applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestDeleteListenerPolicy(t *testing.T) { + getReq := &api.DeleteAppBlbPoliciesRequest{ + Port: 80, + PolicyIdList: []string{ + "bec_policy-scr9cwtk", + }, + } + err := CLIENT.DeleteListenerPolicy("", "applb-cn-hangzhou-cm-h9nh3vpe", getReq) + ExpectEqual(t.Errorf, nil, err) + +} diff --git a/bce-sdk-go/services/bec/client.go b/bce-sdk-go/services/bec/client.go new file mode 100644 index 0000000..78e72ff --- /dev/null +++ b/bce-sdk-go/services/bec/client.go @@ -0,0 +1,42 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// Client of BEC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the BEC service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = api.DEFAULT_BEC_DOMAIN + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} diff --git a/bce-sdk-go/services/bec/deploySet.go b/bce-sdk-go/services/bec/deploySet.go new file mode 100644 index 0000000..4eab59e --- /dev/null +++ b/bce-sdk-go/services/bec/deploySet.go @@ -0,0 +1,175 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// CreateDeploySet - create deploy set with the specific parameters +// +// PARAMS: +// - args: the arguments to create a deploy set +// +// RETURNS: +// - *CreateDeploySetResponseArgs: the result of create deploy set +// - error: nil if ok otherwise the specific error +func (c *Client) CreateDeploySet(args *api.CreateDeploySetArgs) (*api.CreateDeploySetResponseArgs, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.CreateDeploySetResponseArgs{} + req := &api.PostHttpReq{Url: api.GetDeploySetURI() + "/create", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// UpdateVmInstanceDeploySet - update vm instance deploy set with the specific parameters +// +// PARAMS: +// - args: the arguments to update a vm instance deploy set +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateVmInstanceDeploySet(args *api.UpdateVmDeploySetArgs) error { + if args == nil { + return fmt.Errorf("please set argments") + } + req := &api.PostHttpReq{Url: api.GetDeploySetURI() + "/updateRelation", Body: args} + err := api.Post(c, req) + return err +} + +// DeleteVmInstanceFromDeploySet - remove vm instances from deploy set with the specific parameters +// +// PARAMS: +// - args: the arguments to remove vm instances from deploy set +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVmInstanceFromDeploySet(args *api.DeleteVmDeploySetArgs) error { + if args == nil { + return fmt.Errorf("please set argments") + } + req := &api.PostHttpReq{Url: api.GetDeploySetURI() + "/delRelation", Body: args} + err := api.Post(c, req) + return err +} + +// UpdateDeploySet - update deploy set with the specific parameters +// +// PARAMS: +// - args: the arguments to update deploy set +// +// RETURNS: +// - *ListVmServiceResult: the result of get vm services +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateDeploySet(deploySetId string, args *api.CreateDeploySetArgs) error { + if args == nil || deploySetId == "" { + return fmt.Errorf("please set argments") + } + params := make(map[string]string) + params["modifyAttribute"] = "" + req := &api.PostHttpReq{Url: api.GetDeploySetURI() + "/" + deploySetId, Body: args, Params: params} + err := api.Put(c, req) + return err +} + +// GetDeploySetList - get deploy set list with the specific parameters +// RETURNS: +// - *LogicPageDeploySetResult: the result of deploy set list +// - error: nil if ok otherwise the specific error +func (c *Client) GetDeploySetList(args *api.ListRequest) (*api.LogicPageDeploySetResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if args.PageSize != 0 { + params["pageSize"] = strconv.Itoa(args.PageSize) + } + if args.PageNo != 0 { + params["pageNo"] = strconv.Itoa(args.PageNo) + } + if args.KeywordType != "" { + params["keywordType"] = args.KeywordType + } + if args.Keyword != "" { + params["keyword"] = args.Keyword + } + + result := &api.LogicPageDeploySetResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetDeploySetURI() + "/list"). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetDeploySetDetail - get vm service detail with the specific parameters +// +// PARAMS: +// - deploySetId: deploy set id +// +// RETURNS: +// - *DeploySetDetails: the result of deploy set detail +// - error: nil if ok otherwise the specific error +func (c *Client) GetDeploySetDetail(deploySetId string) (*api.DeploySetDetails, error) { + if deploySetId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.DeploySetDetails{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetDeploySetURI() + "/" + deploySetId). + WithResult(result). + Do() + return result, err +} + +// DeleteDeploySet - delete deploy set with the specific parameters +// +// PARAMS: +// - deploySetId: deploy set id +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteDeploySet(deploySetId string) error { + if deploySetId == "" { + return fmt.Errorf("please set argments") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(api.GetDeploySetURI() + "/" + deploySetId). + Do() + + return err +} diff --git a/bce-sdk-go/services/bec/deploySet_test.go b/bce-sdk-go/services/bec/deploySet_test.go new file mode 100644 index 0000000..d3a2368 --- /dev/null +++ b/bce-sdk-go/services/bec/deploySet_test.go @@ -0,0 +1,66 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +////////////////////////////////////////////// +// deploy set test +////////////////////////////////////////////// + +func TestCreateDeploySet(t *testing.T) { + getReq := &api.CreateDeploySetArgs{ + Name: "wcw_test", + Desc: "wcw-test", + } + res, err := CLIENT.CreateDeploySet(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateDeploySet(t *testing.T) { + getReq := &api.CreateDeploySetArgs{ + Name: "wcw_test", + Desc: "wcw-test-gosdk", + } + err := CLIENT.UpdateDeploySet("dset-y4tumnel", getReq) + ExpectEqual(t.Errorf, nil, err) +} +func TestGetDeploySetList(t *testing.T) { + getReq := &api.ListRequest{} + res, err := CLIENT.GetDeploySetList(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestGetDeploySetDetail(t *testing.T) { + res, err := CLIENT.GetDeploySetDetail("dset-y4tumnel") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestUpdateVmInstanceDeploySet(t *testing.T) { + getReq := &api.UpdateVmDeploySetArgs{ + InstanceId: "vm-dstkrmda-cn-langfang-ct-4thbz", + DeploysetIdList: []string{"dset-y4tumnel"}, + } + err := CLIENT.UpdateVmInstanceDeploySet(getReq) + ExpectEqual(t.Errorf, nil, err) + +} + +func TestDeleteVmInstanceFromDeploySet(t *testing.T) { + getReq := &api.DeleteVmDeploySetArgs{ + DeploysetId: "dset-y4tumnel", + InstanceIdList: []string{"vm-dstkrmda-cn-langfang-ct-4thbz"}, + } + err := CLIENT.DeleteVmInstanceFromDeploySet(getReq) + ExpectEqual(t.Errorf, nil, err) + +} + +func TestDeleteDeploySet(t *testing.T) { + err := CLIENT.DeleteDeploySet("dset-y4tumnel") + ExpectEqual(t.Errorf, nil, err) + +} diff --git a/bce-sdk-go/services/bec/image.go b/bce-sdk-go/services/bec/image.go new file mode 100644 index 0000000..8f19ec8 --- /dev/null +++ b/bce-sdk-go/services/bec/image.go @@ -0,0 +1,151 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BOS service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// CreateVmImage - create a vm image +// +// PARAMS: +// - args: the create vm image args +// +// RETURNS: +// - *api.CreateVmImageResult: the result image +// - error: nil if ok otherwise the specific error +func (c *Client) CreateVmImage(args *api.CreateVmImageArgs) (*api.CreateVmImageResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.CreateVmImageResult{} + req := &api.PostHttpReq{Url: api.GetVmImageURI(), Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// DeleteVmImage - delete a vm image +// +// PARAMS: +// - args: the delete vm image args, spec vmId list +// +// RETURNS: +// - *api.VmImageOperateResult: the result image delete +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVmImage(args []string) (*api.VmImageOperateResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmImageOperateResult{} + params := make(map[string]string) + params["imageIdList"] = strings.Join(args, ",") + req := &api.PostHttpReq{Url: api.GetVmImageURI(), Result: result, Params: params} + err := api.Delete(c, req) + + return result, err +} + +// UpdateVmImage - update a vm image +// +// PARAMS: +// - imageId: image id +// - args: the update vm image args +// +// RETURNS: +// - *api.VmImageOperateResult: the result image update +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateVmImage(imageId string, args *api.UpdateVmImageArgs) (*api.VmImageOperateResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmImageOperateResult{} + req := &api.PostHttpReq{Url: api.GetVmImageURI() + "/" + imageId, Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// ListVmImage - image list +// +// PARAMS: +// - args: the vm image list args +// +// RETURNS: +// - *api.ListVmImageResult: the list of vm images +// - error: nil if ok otherwise the specific error +func (c *Client) ListVmImage(args *api.ListVmImageArgs) (*api.ListVmImageResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if args.PageNo != 0 { + params["PageNo"] = strconv.Itoa(args.PageNo) + } + if args.PageSize != 0 { + params["PageSize"] = strconv.Itoa(args.PageSize) + } + if args.Order != "" { + params["Order"] = args.Order + } + if args.OrderBy != "" { + params["OrderBy"] = args.OrderBy + } + if args.Type != "" { + params["Type"] = args.Type + } + if args.KeywordType != "" { + params["keywordType"] = args.KeywordType + } + if args.Keyword != "" { + params["keyword"] = args.Keyword + } + if args.Status != "" { + params["status"] = args.Status + } + if args.Region != "" { + params["region"] = args.Region + } + if args.OsName != "" { + params["osName"] = args.OsName + } + if args.ServiceId != "" { + params["serviceId"] = args.ServiceId + } + + result := &api.ListVmImageResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmImageURI()). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/bec/image_test.go b/bce-sdk-go/services/bec/image_test.go new file mode 100644 index 0000000..7839cba --- /dev/null +++ b/bce-sdk-go/services/bec/image_test.go @@ -0,0 +1,39 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +////////////////////////////////////////////// +// image API +////////////////////////////////////////////// + +func TestCreateVmImage(t *testing.T) { + getReq := &api.CreateVmImageArgs{VmId: "vm-dstkrmda-cn-jinan-cm-235ew", Name: "wcw-test"} + res, err := CLIENT.CreateVmImage(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateVmImage(t *testing.T) { + getReq := &api.UpdateVmImageArgs{Name: "wcw-test1"} + res, err := CLIENT.UpdateVmImage("im-dqoicjmz", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestListVmImage(t *testing.T) { + getReq := &api.ListVmImageArgs{OsName: "CentOS", Status: "IMAGING"} + res, err := CLIENT.ListVmImage(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteVmImage(t *testing.T) { + req := []string{"im-dqoicjmz"} + res, err := CLIENT.DeleteVmImage(req) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} diff --git a/bce-sdk-go/services/bec/init_test.go b/bce-sdk-go/services/bec/init_test.go new file mode 100644 index 0000000..ccf76b7 --- /dev/null +++ b/bce-sdk-go/services/bec/init_test.go @@ -0,0 +1,68 @@ +package bec + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" +) + +var CLIENT *Client + +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + fmt.Printf("init \n") + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 6; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} diff --git a/bce-sdk-go/services/bec/loadBalancer.go b/bce-sdk-go/services/bec/loadBalancer.go new file mode 100644 index 0000000..fe42f08 --- /dev/null +++ b/bce-sdk-go/services/bec/loadBalancer.go @@ -0,0 +1,588 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// CreateBlb - create lb +// +// PARAMS: +// - args: the lb create args +// +// RETURNS: +// - *api.CreateBlbResult: the create lb result +// - error: nil if ok otherwise the specific error +func (c *Client) CreateBlb(args *api.CreateBlbArgs) (*api.CreateBlbResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.CreateBlbResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI(), Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// DeleteBlb - delete lb +// +// PARAMS: +// - blbId: lb id +// +// RETURNS: +// - *api.DeleteBlbResult: delete lb result +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteBlb(blbId string) (*api.DeleteBlbResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.DeleteBlbResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(api.GetLoadBalancerURI() + "/" + blbId). + WithResult(result). + Do() + + return result, err +} + +// GetBlbList - get lb list +// +// PARAMS: +// - lbType: lb type +// - order: list order +// - orderBy: order by +// - keyword: the key word +// - keywordType: key word type +// - status: lb status +// - region: lb's region +// - pageNo: page NO +// - pageSize: page size +// +// RETURNS: +// - *api.GetBlbListResult: the list of lb +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbList(lbType, order, orderBy, keyword, keywordType, status, region string, + pageNo, pageSize int) (*api.GetBlbListResult, error) { + + params := make(map[string]string) + if order != "" { + params["order"] = order + } + if orderBy != "" { + params["orderBy"] = orderBy + } + if keyword != "" { + params["keyword"] = keyword + } + if keywordType != "" { + params["keywordType"] = keywordType + } + if status != "" { + params["status"] = status + } + if region != "" { + params["region"] = region + } + if pageSize != 0 { + params["pageSize"] = strconv.Itoa(pageSize) + } + if pageNo != 0 { + params["pageNo"] = strconv.Itoa(pageNo) + } + if lbType != "" { + params["lbType"] = lbType + } + + result := &api.GetBlbListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI()). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetBlbDetail - lb detail +// +// PARAMS: +// - blbId: lb id +// +// RETURNS: +// - *api.BlbInstanceVo: lb info +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbDetail(blbId string) (*api.BlbInstanceVo, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BlbInstanceVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI() + "/" + blbId). + WithResult(result). + Do() + + return result, err +} + +// UpdateBlb - update lb +// +// PARAMS: +// - blbId: lb id +// - args: the vm image list args +// +// RETURNS: +// - *api.UpdateBlbResult: update lb result +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateBlb(blbId string, args *api.UpdateBlbArgs) (*api.UpdateBlbResult, error) { + if blbId == "" || args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.UpdateBlbResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId, Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// CreateBlbMonitorPort - create lb monitor port +// +// PARAMS: +// - blbId: lb id +// - args: create lb monitor port args +// +// RETURNS: +// - *api.BlbMonitorResult: create lb monitor port result +// - error: nil if ok otherwise the specific error +func (c *Client) CreateBlbMonitorPort(blbId string, args *api.BlbMonitorArgs) (*api.BlbMonitorResult, error) { + if blbId == "" || args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BlbMonitorResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId + "/monitor", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// DeleteBlbMonitorPort - delete lb monitor port +// +// PARAMS: +// - blbId: lb id +// - args: delete lb monitor port args +// +// RETURNS: +// - *api.BlbMonitorResult: delete lb monitor result +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteBlbMonitorPort(blbId string, args *[]api.Port) (*api.BlbMonitorResult, error) { + if blbId == "" || args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BlbMonitorResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId + "/monitor", Body: args, Result: result} + err := api.Delete(c, req) + + return result, err +} + +// GetBlbMonitorPortList - get lb's monitor port list +// +// PARAMS: +// - blbId: lb id +// - pageNo: page no +// - pageSize: page size +// +// RETURNS: +// - *api.BlbMonitorListResult: the list of lb monitor ports +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbMonitorPortList(blbId string, pageNo, pageSize int) (*api.BlbMonitorListResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + params := make(map[string]string) + if pageSize != 0 { + params["pageSize"] = strconv.Itoa(pageSize) + } + if pageNo != 0 { + params["pageNo"] = strconv.Itoa(pageNo) + } + result := &api.BlbMonitorListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI() + "/" + blbId + "/monitor"). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// UpdateBlbMonitorPort - update lb monitor port +// +// PARAMS: +// - blbId: lb id +// - args: monitor info args +// +// RETURNS: +// - *api.BlbMonitorResult: update lb monitor result +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateBlbMonitorPort(blbId string, args *api.BlbMonitorArgs) (*api.BlbMonitorResult, error) { + if blbId == "" || args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BlbMonitorResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId + "/monitor", Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// GetBlbMonitorPortDetails - get lb monitor port detail +// +// PARAMS: +// - blbId: lb id +// - protocol: protocol +// - port: port +// +// RETURNS: +// - *api.BlbMonitorArgs: lb monitor info result +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbMonitorPortDetails(blbId string, protocol api.Protocol, port int) (*api.BlbMonitorArgs, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if protocol != "" { + params["protocol"] = string(protocol) + } + if port != 0 { + params["port"] = strconv.Itoa(port) + } + result := &api.BlbMonitorArgs{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI() + "/" + blbId + "/monitor/port"). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// BatchCreateBlb - batch create lb +// +// PARAMS: +// - args: batch create lb args +// +// RETURNS: +// - *api.BatchCreateBlbResult: the result of batch create lb +// - error: nil if ok otherwise the specific error +func (c *Client) BatchCreateBlb(args *api.BatchCreateBlbArgs) (*api.BatchCreateBlbResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BatchCreateBlbResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/batch/create", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// BatchDeleteBlb - batch delete lb +// +// PARAMS: +// - blbIdList: the list of lb +// +// RETURNS: +// - *api.BatchDeleteBlbResult: the result of batch delete lb +// - error: nil if ok otherwise the specific error +func (c *Client) BatchDeleteBlb(blbIdList []string) (*api.BatchDeleteBlbResult, error) { + if blbIdList == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BatchDeleteBlbResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/batch/delete", Result: result, Body: blbIdList} + err := api.Post(c, req) + + return result, err +} + +// BatchCreateBlbMonitor - batch create lb monitor +// +// PARAMS: +// - blbId: lb id +// - args: batch create lb monitor args +// +// RETURNS: +// - *api.BatchCreateBlbMonitorResult: the result of batch create lb nonitor +// - error: nil if ok otherwise the specific error +func (c *Client) BatchCreateBlbMonitor(blbId string, args *api.BatchCreateBlbMonitorArg) (*api.BatchCreateBlbMonitorResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.BatchCreateBlbMonitorResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerBatchURI() + "/create/" + blbId + "/monitor", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// GetBlbBackendPodList - get lb backend list +// +// PARAMS: +// - blbId: lb id +// - pageNo: page NO +// - pageSize: page size +// +// RETURNS: +// - *api.GetBlbBackendPodListResult: the result of lb backend list +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbBackendPodList(blbId string, pageNo, pageSize int) (*api.GetBlbBackendPodListResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if pageSize != 0 { + params["pageSize"] = strconv.Itoa(pageSize) + } + if pageNo != 0 { + params["pageNo"] = strconv.Itoa(pageNo) + } + result := &api.GetBlbBackendPodListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI() + "/" + blbId + "/binded"). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetBlbBackendBindingStsList - get lb backend's statefulset list +// +// PARAMS: +// - blbId: lb id +// - keyword: the key word +// - keywordType: key word type +// - pageNo: page NO +// - pageSize: page size +// +// RETURNS: +// - *api.GetBlbBackendBindingStsListResult: the list of sts result +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbBackendBindingStsList(blbId string, pageNo, pageSize int, keywordType, keyword string) (*api.GetBlbBackendBindingStsListResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if pageSize != 0 { + params["pageSize"] = strconv.Itoa(pageSize) + } + if pageNo != 0 { + params["pageNo"] = strconv.Itoa(pageNo) + } + if keywordType != "" { + params["keywordType"] = keywordType + } + + if keyword != "" { + params["keyword"] = keyword + } + + result := &api.GetBlbBackendBindingStsListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI() + "/" + blbId + "/binding"). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetBlbBindingPodListWithSts - image list +// +// PARAMS: +// - blbId: lb id +// - stsName: sts name +// +// RETURNS: +// - *api.Backends: the list of backend +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbBindingPodListWithSts(blbId, stsName string) (*[]api.Backends, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if stsName != "" { + params["stsName"] = stsName + } + + result := &[]api.Backends{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerURI() + "/" + blbId + "/bindingpod"). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// CreateBlbBinding - create lb binding +// +// PARAMS: +// - blbId: lb id +// - args: create lb binding args +// +// RETURNS: +// - *api.CreateBlbBindingResult: the result of lb binding +// - error: nil if ok otherwise the specific error +func (c *Client) CreateBlbBinding(blbId string, args *api.CreateBlbBindingArgs) (*api.CreateBlbBindingResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.CreateBlbBindingResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId + "/binding", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// DeleteBlbBindPod - delete lb bind pod +// +// PARAMS: +// - blbId: lb id +// - args: delete lb bind pod args +// +// RETURNS: +// - *api.DeleteBlbBindPodResult: the result of delete lb pod +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteBlbBindPod(blbId string, args *api.DeleteBlbBindPodArgs) (*api.DeleteBlbBindPodResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.DeleteBlbBindPodResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId + "/binded", Result: result, Body: args} + err := api.Delete(c, req) + + return result, err +} + +// UpdateBlbBindPodWeight - update bind pod weight +// +// PARAMS: +// - blbId: lb id +// - args: update bind pod weight args +// +// RETURNS: +// - *api.UpdateBindPodWeightResult: the result of update bind pod weight +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateBlbBindPodWeight(blbId string, args *api.UpdateBindPodWeightArgs) (*api.UpdateBindPodWeightResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.UpdateBindPodWeightResult{} + req := &api.PostHttpReq{Url: api.GetLoadBalancerURI() + "/" + blbId + "/binded", Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// GetBlbMetrics - get lb metrics +// +// PARAMS: +// - blbId: lb id +// - ipType: ip type +// - port: port +// - serviceProviderStr: service Provider +// - offsetInSeconds: offset Seconds +// - metricsType: metrics Type +// +// RETURNS: +// - *api.ServiceMetricsResult: the list of vm images +// - error: nil if ok otherwise the specific error +func (c *Client) GetBlbMetrics(blbId, ipType, port, serviceProviderStr string, start, end, stepInMin int, metricsType api.MetricsType) (*api.ServiceMetricsResult, error) { + if blbId == "" { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + params["blbId"] = blbId + if port != "" { + params["port"] = port + } + + if serviceProviderStr != "" { + params["serviceProvider"] = serviceProviderStr + } + + if ipType != "" { + params["ipType"] = ipType + } + if start != 0 { + params["start"] = strconv.Itoa(start) + } + if metricsType != "" { + params["metricsType"] = string(metricsType) + } + + if end != 0 { + params["end"] = strconv.Itoa(end) + } + if stepInMin != 0 { + params["stepInMin"] = strconv.Itoa(stepInMin) + } + + result := &api.ServiceMetricsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetLoadBalancerMonitorURI() + "/" + blbId). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/bec/loadBalancer_test.go b/bce-sdk-go/services/bec/loadBalancer_test.go new file mode 100644 index 0000000..d805589 --- /dev/null +++ b/bce-sdk-go/services/bec/loadBalancer_test.go @@ -0,0 +1,180 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// //////////////////////////////////////////// +// Loadbalancer API +// //////////////////////////////////////////// +func TestCreateBlb(t *testing.T) { + getReq := &api.CreateBlbArgs{ + BlbName: "gosdk-test", + RegionId: "cn-hangzhou-cm", + LbType: "vm", + NetworkType: "vpc", + } + res, err := CLIENT.CreateBlb(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCreateBlbVpc(t *testing.T) { + getReq := &api.CreateBlbArgs{ + BlbName: "gosdk-test1", + RegionId: "cn-baoding-ix", + LbType: "vm", + NetworkType: "vpc", + SubServiceProviders: []string{"cm"}, + } + res, err := CLIENT.CreateBlb(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteBlb(t *testing.T) { + res, err := CLIENT.DeleteBlb("xxxx") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbList(t *testing.T) { + res, err := CLIENT.GetBlbList("vm", "desc", "createTime", "", "", + "", "", 1, 100) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbDetail(t *testing.T) { + res, err := CLIENT.GetBlbDetail("applb-cn-hangzhou-cm-wkfdcbin") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateBlb(t *testing.T) { + getReq := &api.UpdateBlbArgs{BlbName: "applb-cn-hangzhou-cm-wkfdcbin", BandwidthInMbpsLimit: 1000, Type: "bandwidth"} + res, err := CLIENT.UpdateBlb("applb-cn-hangzhou-cm-wkfdcbin", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCreateBlbMonitorPort(t *testing.T) { + + str := "" + t.Logf("%v", &str) + getReq := &api.BlbMonitorArgs{LbMode: api.LbModeWrr, FrontendPort: &api.Port{Protocol: api.ProtocolTcp, Port: 80}, + BackendPort: 80, HealthCheck: &api.HealthCheck{HealthCheckString: &str, HealthCheckType: "tcp", + HealthyThreshold: 1000, UnhealthyThreshold: 1000, TimeoutInSeconds: 50, IntervalInSeconds: 3}} + res, err := CLIENT.CreateBlbMonitorPort("applb-cn-hangzhou-cm-wkfdcbin", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteBlbMonitorPort(t *testing.T) { + req := []api.Port{{Protocol: api.ProtocolUdp, Port: 81}} + res, err := CLIENT.DeleteBlbMonitorPort("applb-cn-hangzhou-cm-3vkqupsp", &req) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbMonitorPortList(t *testing.T) { + res, err := CLIENT.GetBlbMonitorPortList("applb-cn-hangzhou-cm-wkfdcbin", 1, 100) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateBlbMonitorPort(t *testing.T) { + str := "" + getReq := &api.BlbMonitorArgs{LbMode: api.LbModeWrr, FrontendPort: &api.Port{Protocol: api.ProtocolTcp, Port: 80}, + BackendPort: 8090, HealthCheck: &api.HealthCheck{HealthCheckString: &str, HealthCheckType: "tcp", + HealthyThreshold: 1000, UnhealthyThreshold: 1000, TimeoutInSeconds: 60, IntervalInSeconds: 3}} + res, err := CLIENT.UpdateBlbMonitorPort("applb-cn-hangzhou-cm-wkfdcbin", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbMonitorPortDetails(t *testing.T) { + res, err := CLIENT.GetBlbMonitorPortDetails("applb-cn-hangzhou-cm-3vkqupsp", api.ProtocolTcp, 80) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbBackendPodList(t *testing.T) { + res, err := CLIENT.GetBlbBackendPodList("applb-cn-langfang-ct-whak2ian", 0, 0) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbBackendBindingStsList(t *testing.T) { + res, err := CLIENT.GetBlbBackendBindingStsList("applb-cn-langfang-ct-whak2ian", 0, 0, "", "") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbBindingPodListWithSts(t *testing.T) { + res, err := CLIENT.GetBlbBindingPodListWithSts("lb-pclalzin", "sts-loy3f9tk-2-t-langfang") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCreateBlbBinding(t *testing.T) { + getReq := &api.CreateBlbBindingArgs{BindingForms: &[]api.BlbBindingForm{ + api.BlbBindingForm{DeploymentId: "vm-xqjitfy1-cn-langfang-ct", PodWeight: &[]api.Backends{ + api.Backends{Name: "vm-xqjitfy1-cn-langfang-ct-d1f7x", Ip: "172.16.8.22", Weight: 100}}, + }}} + res, err := CLIENT.CreateBlbBinding("lb-jgvg4pbz", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteBlbBindPod(t *testing.T) { + getReq := &api.DeleteBlbBindPodArgs{PodWeightList: &[]api.Backends{ + api.Backends{Name: "vm-xqjitfy1-cn-langfang-ct-d1f7x", Ip: "172.16.8.22", Weight: 100}}, + DeploymentIds: []string{"vvm-xqjitfy1-cn-langfang-ct"}} + res, err := CLIENT.DeleteBlbBindPod("lb-jgvg4pbz", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateBlbBindPodWeight(t *testing.T) { + getReq := &api.UpdateBindPodWeightArgs{PodWeightList: &[]api.Backends{ + api.Backends{Name: "vm-xxxxx", Ip: "172.16.xx.xx", Weight: 10}}, + DeploymentIds: []string{"vmrs-xxxxxx"}} + res, err := CLIENT.UpdateBlbBindPodWeight("lb-xxxxx", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetBlbMetrics(t *testing.T) { + res, err := CLIENT.GetBlbMetrics("applb-cn-langfang-ct-lpcfbjv6", "extranet", "", "", + 1657613108, 1660291508, 1, api.MetricsTypeTrafficReceive) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBatchCreateBlb(t *testing.T) { + getReq := &api.BatchCreateBlbArgs{BlbName: "xxxx-test", DeployInstances: &[]api.DeploymentInstance{ + api.DeploymentInstance{Region: api.RegionSouthChina, Replicas: 1, City: "GUANGZHOU", ServiceProvider: api.ServiceChinaUnicom}, + }, LbType: "vm"} + res, err := CLIENT.BatchCreateBlb(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBatchDeleteBlb(t *testing.T) { + res, err := CLIENT.BatchDeleteBlb([]string{"lb-xxxx", "lb-xxxx-2", "lb-xxxx-3"}) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBatchCreateBlbMonitor(t *testing.T) { + str := "\\00\\01\\01\\00\\01\\00\\00\\00\\00\\00\\00\\05baidu\\03com\\00\\00\\01\\00\\01" + getReq := &api.BatchCreateBlbMonitorArg{Protocol: api.ProtocolUdp, LbMode: api.LbModeWrr, HealthCheck: &api.HealthCheck{HealthCheckString: &str, HealthCheckType: "udp", + HealthyThreshold: 1000, UnhealthyThreshold: 1000, TimeoutInSeconds: 60, IntervalInSeconds: 3}, PortGroups: &[]api.PortGroup{api.PortGroup{ + Port: 82, BackendPort: 82}, api.PortGroup{Port: 443, BackendPort: 443}}} + res, err := CLIENT.BatchCreateBlbMonitor("applb-cn-hangzhou-cm-3vkqupsp", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} diff --git a/bce-sdk-go/services/bec/node.go b/bce-sdk-go/services/bec/node.go new file mode 100644 index 0000000..74daa19 --- /dev/null +++ b/bce-sdk-go/services/bec/node.go @@ -0,0 +1,45 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// GetBecAvailableNodeInfoVo - get available node +// +// PARAMS: +// - args: the type +// +// RETURNS: +// - *api.GetBecAvailableNodeInfoVoResult: get available node +// - error: nil if ok otherwise the specific error +func (c *Client) GetBecAvailableNodeInfoVo(getType string) (*api.GetBecAvailableNodeInfoVoResult, error) { + if getType == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.GetBecAvailableNodeInfoVoResult{} + req := &api.GetHttpReq{Url: api.GetNodeInfoURI() + "/type/" + getType, Result: result} + err := api.Get(c, req) + + return result, err +} diff --git a/bce-sdk-go/services/bec/node_test.go b/bce-sdk-go/services/bec/node_test.go new file mode 100644 index 0000000..0cfe86c --- /dev/null +++ b/bce-sdk-go/services/bec/node_test.go @@ -0,0 +1,14 @@ +package bec + +import ( + "testing" +) + +// //////////////////////////////////////////// +// node API +// //////////////////////////////////////////// +func TestGetBecAvailableNodeInfoVo(t *testing.T) { + res, err := CLIENT.GetBecAvailableNodeInfoVo("vm") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} diff --git a/bce-sdk-go/services/bec/scenario_test.go b/bce-sdk-go/services/bec/scenario_test.go new file mode 100644 index 0000000..29c7ce4 --- /dev/null +++ b/bce-sdk-go/services/bec/scenario_test.go @@ -0,0 +1,305 @@ +package bec + +import ( + "fmt" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// //////////////////////////////////////////// +// vmService API +// //////////////////////////////////////////// +// 定义参数 城市、运营商中文名、镜像名称、服务名称 +func TestVmServiceSce(t *testing.T) { + cityName := "杭州" + serviceProviderName := "移动" + image := "fyy-test" + name := "bec-tst" + //创建无实例虚机服务,并获取服务ID + getReq := &api.CreateVmServiceArgs{ServiceName: name} + resVm, err := CLIENT.CreateVmService(getReq) + serviceId := resVm.Details.ServiceId + // 根据城市与运营商中文名称获取城市与运营商编号还有REGION编号 + var city string + var provider api.ServiceProvider + var region api.Region + resNode, err := CLIENT.GetBecAvailableNodeInfoVo("vm") + if err == nil { + for _, v := range resNode.RegionList { + for _, cityInfo := range v.CityList { + if cityInfo.Name == cityName { + for _, providerInfo := range cityInfo.ServiceProviderList { + if providerInfo.Name == serviceProviderName { + city = cityInfo.City + provider = providerInfo.ServiceProvider + region = v.Region + } + } + } + } + } + } + + // 根据镜像名称获取镜像ID + imageReq := &api.ListVmImageArgs{KeywordType: "name", Keyword: image} + res, err := CLIENT.ListVmImage(imageReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + return + } + if len(res.Result) == 0 { + err = fmt.Errorf("no such image name %s", image) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", "no such image name") + return + } + imageId := res.Result[0].ImageId + + // 创建虚机,并获取虚机ID + createVmiReq := &api.CreateVmServiceArgs{ImageId: imageId, Cpu: 1, Memory: 2, NeedPublicIp: true, Bandwidth: 50, + DeployInstances: &[]api.DeploymentInstance{api.DeploymentInstance{City: city, Region: region, + ServiceProvider: provider, Replicas: 1}}, AdminPass: "xxxxxx111xxB@", ImageType: api.ImageTypeBec} + createVmiRes, err := CLIENT.CreateVmServiceInstance(serviceId, createVmiReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + return + } + + vmiId := createVmiRes.Details.Instances[0].VmId + + // 每隔10秒获取一次虚机创建状态,并打印虚机状态,直到虚机进入运行中 + var stateRes *api.VmInstanceDetailsVo + ticker := time.NewTicker(10 * time.Second) + errTime := 3 + in := true + for in { + select { + case <-ticker.C: + //stateRes, err := CLIENT.GetVmServiceDetail(vmId) + stateRes, err = CLIENT.GetVirtualMachine(vmiId) + if err != nil && errTime > 0 { + errTime-- + continue + } + if errTime == 0 { + in = false + break + } + fmt.Println("vm status is ", stateRes.Status) + if stateRes != nil && stateRes.Status == api.ResourceStatusRunning { + in = false + break + } + } + } + + // 打印指定虚机的内外网IP、虚机名称、ID + vmStatusRes, err := CLIENT.GetVirtualMachine(vmiId) + fmt.Printf("ip:%s, internalIp:%s, vmName:%s, vmId: %s\n", vmStatusRes.PublicIp, + vmStatusRes.InternalIp, vmStatusRes.VmName, vmStatusRes.VmId) + + // 添加虚机辅助IP + crateVmPrivateIpReq := &api.CreateVmPrivateIpForm{SecondaryPrivateIpAddressCount: 1} + _, err = CLIENT.CreateVmPrivateIp(vmiId, crateVmPrivateIpReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + return + } + + // 删除虚机辅助IP + GetVmRes, err := CLIENT.GetVirtualMachine(vmiId) + privateIp := GetVmRes.PrivateIps + deleteVmPrivateIpReq := &api.DeleteVmPrivateIpForm{PrivateIps: privateIp} + delRes, err := CLIENT.DeleteVmPrivateIp(vmiId, deleteVmPrivateIpReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", delRes) + + // 重置虚机密码 + updateVmReq := &api.UpdateVmInstanceArgs{Type: "password", KeyConfig: &api.KeyConfig{Type: "password", AdminPass: "12345asdf@"}} + updateVmRes, err := CLIENT.UpdateVmInstance(vmiId, updateVmReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", updateVmRes) + + // 每隔10秒获取一次虚机创建状态,并打印虚机状态,直到虚机进入运行中 + ticker = time.NewTicker(10 * time.Second) + errTime = 3 + in = true + for in { + select { + case <-ticker.C: + //stateRes, err := CLIENT.GetVmServiceDetail(vmId) + stateRes, err = CLIENT.GetVirtualMachine(vmiId) + if err != nil && errTime > 0 { + errTime-- + continue + } + if errTime == 0 { + in = false + break + } + fmt.Println("vm status is ", stateRes.Status) + if stateRes != nil && stateRes.Status == api.ResourceStatusRunning { + in = false + break + } + } + } + + // 关机虚机,每隔10秒获取一次虚机创建状态,并打印虚机状态,直到虚机关机 + operateVmRes, err := CLIENT.OperateVmDeployment(vmiId, api.VmInstanceBatchOperateStop) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", operateVmRes) + return + } + + var vmStateRes *api.VmInstanceDetailsVo + ticker = time.NewTicker(10 * time.Second) + errTime = 3 + in = true + for in { + select { + case <-ticker.C: + //stateRes, err := CLIENT.GetVmServiceDetail(vmId) + vmStateRes, err = CLIENT.GetVirtualMachine(vmiId) + if err != nil && errTime > 0 { + errTime-- + continue + } + if errTime == 0 { + in = false + break + } + fmt.Println("vm status is ", vmStateRes.Status) + if vmStateRes != nil && vmStateRes.Status == api.ResourceStatusStopped { + in = false + break + } + } + } + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", vmStateRes) + // 删除虚机 + deleteVmRes, err := CLIENT.DeleteVmInstance(vmiId) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", deleteVmRes) + // 删除服务 + deleteVmServiceRes, err := CLIENT.DeleteVmService(serviceId) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", deleteVmServiceRes) +} + +// 创建LocalDNS虚机 +func TestCreateVmServiceWithLocalDns(t *testing.T) { + getReq := &api.CreateVmServiceArgs{ServiceName: "xxxxxxx@-local", ImageId: "im-dikfttnj-3-u-guangzhou", AdminPass: "x123xxx@", + SystemVolume: &api.SystemVolumeConfig{VolumeType: api.DiskTypeNVME}, Cpu: 1, Memory: 2, + DeployInstances: &[]api.DeploymentInstance{api.DeploymentInstance{City: "HANGZHOU", Region: api.RegionEastChina, + ServiceProvider: api.ServiceChinaMobile, Replicas: 1}}, ImageType: api.ImageTypeBec, KeyConfig: &api.KeyConfig{Type: "password", AdminPass: "xxxx123@"}, + DnsConfig: &api.DnsConfig{DnsType: "LOCAL"}} + res, err := CLIENT.CreateVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +// 创建密钥对虚机 +func TestCreateVmServiceWithKeypair(t *testing.T) { + getReq := &api.CreateVmServiceArgs{ServiceName: "xxxxxxx@-key", ImageId: "im-dikfttnj-3-u-guangzhou", + SystemVolume: &api.SystemVolumeConfig{VolumeType: api.DiskTypeNVME}, Cpu: 1, Memory: 2, + DeployInstances: &[]api.DeploymentInstance{api.DeploymentInstance{City: "HANGZHOU", Region: api.RegionEastChina, + ServiceProvider: api.ServiceChinaMobile, Replicas: 1}}, ImageType: api.ImageTypeBec, KeyConfig: &api.KeyConfig{Type: "bccKeyPair", BccKeyPairIdList: []string{"k-r4FmM6flink"}}} + res, err := CLIENT.CreateVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBlbScenario(t *testing.T) { + // 创建负载均衡器 + // 每隔10秒获取一次负载均衡器状态,并打印负载均衡器状态与IP,直到创建完成 + getReq := &api.CreateBlbArgs{BlbName: "xxxx-test", Region: api.RegionEastChina, + City: "HANGZHOU", LbType: "vm", ServiceProvider: api.ServiceChinaMobile} + res, err := CLIENT.CreateBlb(getReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + return + } + + lbId := res.Details.BlbId + var stateRes *api.BlbInstanceVo + ticker := time.NewTicker(10 * time.Second) + errTime := 3 + in := true + for in { + select { + case <-ticker.C: + //stateRes, err := CLIENT.GetVmServiceDetail(vmId) + stateRes, err = CLIENT.GetBlbDetail(lbId) + if err != nil && errTime > 0 { + errTime-- + continue + } + if errTime == 0 { + in = false + break + } + fmt.Printf("lb status is %s, ip is %s", stateRes.Status, stateRes.PublicIp) + if stateRes != nil && stateRes.Status == api.ResourceStatusRunning { + in = false + break + } + } + } + + // 创建TCP监听 + str := "" + blbMonitorReq := &api.BlbMonitorArgs{LbMode: api.LbModeWrr, FrontendPort: &api.Port{Protocol: api.ProtocolTcp, Port: 80}, + BackendPort: 80, HealthCheck: &api.HealthCheck{HealthCheckString: &str, HealthCheckType: "tcp", + HealthyThreshold: 1000, UnhealthyThreshold: 1000, TimeoutInSeconds: 60, IntervalInSeconds: 3}} + blbMonitorRes, err := CLIENT.CreateBlbMonitorPort(lbId, blbMonitorReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", blbMonitorRes) + return + } + + vmiId := "vm-brcvrwvt-1-m-hangzhou-ehkrm" + // 按虚机添加后端服务器 + createBlbBindingReq := &api.CreateBlbBindingArgs{BindingForms: &[]api.BlbBindingForm{ + api.BlbBindingForm{DeploymentId: vmiId, PodWeight: &[]api.Backends{ + api.Backends{Name: vmiId, Weight: 100}}, + }}} + createBlbBindingRes, err := CLIENT.CreateBlbBinding(lbId, createBlbBindingReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", createBlbBindingRes) + return + } + + // 查询负载均衡器状态,打印负载均衡器后端服务器 + getBlbBackendPodRes, err := CLIENT.GetBlbBackendPodList(lbId, 0, 0) + if len(getBlbBackendPodRes.Result) > 0 { + for _, v := range getBlbBackendPodRes.Result { + fmt.Println("backend rs is ", v.PodName) + } + } + + // 从后端服务器删除虚机 + deleteBlbBindPodReq := &api.DeleteBlbBindPodArgs{PodWeightList: &[]api.Backends{ + api.Backends{Name: vmiId}}} + deleteBlbBindPodRes, err := CLIENT.DeleteBlbBindPod(lbId, deleteBlbBindPodReq) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", deleteBlbBindPodRes) + } + + // 删除负载均衡器 + deleteRes, err := CLIENT.DeleteBlb(lbId) + if err != nil { + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", deleteRes) + } +} diff --git a/bce-sdk-go/services/bec/service.go b/bce-sdk-go/services/bec/service.go new file mode 100644 index 0000000..a800249 --- /dev/null +++ b/bce-sdk-go/services/bec/service.go @@ -0,0 +1,490 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// CreateService - create a container service with the specific parameters +// +// PARAMS: +// - args: the arguments to create a container service +// +// RETURNS: +// - *CreateClusterResult: the result of create a container service +// - error: nil if ok otherwise the specific error +func (c *Client) CreateService(args *api.CreateServiceArgs) (*api.CreateServiceResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.CreateServiceResult{} + req := &api.PostHttpReq{Url: api.GetServiceURI() + "/create", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// ListService - list container service with the specific parameters +// +// PARAMS: +// - pageNo: page No +// - pageSize: page Size +// - keywordType: keyword Type +// - keyword: keyword +// - order: order +// - orderBy: orderBy +// - status: status +// +// RETURNS: +// - *ListServiceResult: the result of list container service +// - error: nil if ok otherwise the specific error +func (c *Client) ListService(pageNo, pageSize int, keywordType, keyword, order, orderBy, status string) (*api.ListServiceResult, error) { + + params := make(map[string]string) + if pageNo != 0 { + params["pageNo"] = strconv.Itoa(pageNo) + } + if pageSize != 0 { + params["pageSize"] = strconv.Itoa(pageSize) + } + if keyword != "" { + params["keyword"] = keyword + } + if keywordType != "" { + params["keywordType"] = keywordType + } + if status != "" { + params["status"] = status + } + if order != "" { + params["order"] = order + } + if orderBy != "" { + params["orderBy"] = orderBy + } + + result := &api.ListServiceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetServiceURI()). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetService - get container service with the specific parameters +// +// PARAMS: +// - serviceId: the service id +// +// RETURNS: +// - *ServiceBriefVo: the result of get container service +// - error: nil if ok otherwise the specific error +func (c *Client) GetService(serviceId string) (*api.ServiceDetailsVo, error) { + result := &api.ServiceDetailsVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetServiceDetailURI(serviceId)). + WithResult(result). + Do() + + return result, err +} + +// ServiceAction - operate service with the specific parameters +// +// PARAMS: +// - serviceId: the service id +// - action: operate action +// +// RETURNS: +// - *ServiceActionResult: the result of operate service +// - error: nil if ok otherwise the specific error +func (c *Client) ServiceAction(serviceId string, action api.ServiceAction) (*api.ServiceActionResult, error) { + result := &api.ServiceActionResult{} + req := &api.PostHttpReq{Url: api.GetStartServiceURI(serviceId, string(action)), Result: result, Body: nil} + err := api.Put(c, req) + + return result, err +} + +// UpdateService - update service with the specific parameters +// +// PARAMS: +// - serviceId: the service id +// - args: the arguments to update service +// +// RETURNS: +// - *UpdateServiceResult: the result of update service +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateService(serviceId string, args *api.UpdateServiceArgs) (*api.UpdateServiceResult, error) { + if args == nil { + args = &api.UpdateServiceArgs{} + } + + result := &api.UpdateServiceResult{} + req := &api.PostHttpReq{Url: api.GetUpdateServiceURI(serviceId), Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// DeleteService - delete service with the specific parameters +// +// PARAMS: +// - serviceId: the service id +// +// RETURNS: +// - *ServiceActionResult: the result of delete service +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteService(serviceId string) (*api.ServiceActionResult, error) { + result := &api.ServiceActionResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(api.GetDeleteServiceURI(serviceId)). + WithResult(result). + Do() + + return result, err +} + +// GetServiceMetrics - get service metrics with the specific parameters +// +// PARAMS: +// - serviceId: the service id +// - metricsType: metrics Type +// - serviceProviderStr: service Provider +// - offsetInSeconds: offset Seconds +// +// RETURNS: +// - *ServiceMetricsResult: the result of get service metrics +// - error: nil if ok otherwise the specific error +func (c *Client) GetServiceMetrics(serviceId string, metricsType api.MetricsType, serviceProviderStr api.ServiceProvider, start, end, stepInMin int) (*api.ServiceMetricsResult, error) { + params := make(map[string]string) + if serviceProviderStr != "" { + params["serviceProvider"] = string(serviceProviderStr) + } + if metricsType != "" { + params["metricsType"] = string(metricsType) + } + if serviceId != "" { + params["serviceId"] = string(serviceId) + } + if stepInMin != 0 { + params["stepInMin"] = strconv.Itoa(stepInMin) + } + if start != 0 { + params["start"] = strconv.Itoa(start) + } + if end != 0 { + params["end"] = strconv.Itoa(end) + } + + result := &api.ServiceMetricsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetServiceMetricsURI(serviceId)). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// ServiceBatchOperate - batch operate service with the specific parameters +// +// PARAMS: +// - args: the arguments to batch operate service +// +// RETURNS: +// - *ServiceBatchOperateResult: the result of batch operate service +// - error: nil if ok otherwise the specific error +func (c *Client) ServiceBatchOperate(args *api.ServiceBatchOperateArgs) (*api.ServiceBatchOperateResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + if args.Action != "start" && args.Action != "stop" { + return nil, fmt.Errorf("action is start|stop, please check") + } + + result := &api.ServiceBatchOperateResult{} + req := &api.PostHttpReq{Url: api.GetBachServiceOperateURI(), Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// ServiceBatchDelete - batch delete service with the specific parameters +// +// PARAMS: +// - args: the arguments to batch delete service +// +// RETURNS: +// - *ServiceBatchOperateResult: the result of batch delete service +// - error: nil if ok otherwise the specific error +func (c *Client) ServiceBatchDelete(args *[]string) (*api.ServiceBatchOperateResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.ServiceBatchOperateResult{} + req := &api.PostHttpReq{Url: api.GetBachServiceDeleteURI(), Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// GetPodDeployment - get pod deployment with the specific parameters +// +// PARAMS: +// - deploymentId: the deploymentId id +// +// RETURNS: +// - *DeploymentResourceBriefVo: the result of get pod deployment +// - error: nil if ok otherwise the specific error +func (c *Client) GetPodDeployment(deploymentId string) (*api.DeploymentResourceBriefVo, error) { + result := &api.DeploymentResourceBriefVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetDeploymentDetailURI(deploymentId)). + WithResult(result). + Do() + + return result, err +} + +// GetPodDeploymentMetrics - get Pod Deployment metrics with the specific parameters +// +// PARAMS: +// - deploymentId: the pod deployment id +// - metricsType: metrics Type +// - serviceProviderStr: service Provider +// - offsetInSeconds: offset Seconds +// +// RETURNS: +// - *ServiceMetricsResult: the result of get Pod Deployment metrics +// - error: nil if ok otherwise the specific error +func (c *Client) GetPodDeploymentMetrics(deploymentId string, metricsType api.MetricsType, serviceProviderStr api.ServiceProvider, start, end, stepInMin int) (*api.ServiceMetricsResult, error) { + params := make(map[string]string) + if serviceProviderStr != "" { + params["serviceProvider"] = string(serviceProviderStr) + } + if metricsType != "" { + params["metricsType"] = string(metricsType) + } + if deploymentId != "" { + params["deploymentId"] = deploymentId + } + if stepInMin != 0 { + params["stepInMin"] = strconv.Itoa(stepInMin) + } + if start != 0 { + params["start"] = strconv.Itoa(start) + } + if end != 0 { + params["end"] = strconv.Itoa(end) + } + + result := &api.ServiceMetricsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetDeploymentMetricsURI(deploymentId)). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// UpdatePodDeploymentReplicas - update pod deployment replicas with the specific parameters +// +// PARAMS: +// - deploymentId: the deploymentId id +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdatePodDeploymentReplicas(deploymentId string, args *api.UpdateDeploymentReplicasRequest) (*api.ActionInfoVo, error) { + if args == nil || deploymentId == "" { + return nil, fmt.Errorf("please set argments") + } + res := &api.ActionInfoVo{} + req := &api.PostHttpReq{Url: api.DEPLOYMENT_URL + "/" + deploymentId, Result: res, Body: args} + err := api.Put(c, req) + return res, err +} + +// DeletePodDeployment - delete pod deployment with the specific parameters +// +// PARAMS: +// - deploymentIDs: the deployment id array +// +// RETURNS: +// - *ServiceActionResult: the result of delete service +// - error: nil if ok otherwise the specific error +func (c *Client) DeletePodDeployment(args *[]string) (*api.DeleteDeploymentActionInfoVo, error) { + result := &api.DeleteDeploymentActionInfoVo{} + req := &api.PostHttpReq{Url: api.DEPLOYMENT_URL, Body: args, Result: result} + err := api.Delete(c, req) + return result, err +} + +// GetPodList - list pod with the specific parameters +// +// PARAMS: +// - pageNo: page No +// - pageSize: page Size +// - keyword: keyword +// - order: order +// - orderBy: orderBy +// +// RETURNS: +// - *ListPodResult: the result of list pod +// - error: nil if ok otherwise the specific error +func (c *Client) GetPodList(pageNo, pageSize int, keyword, order, orderBy, serviceId, deploymentId string) (*api.ListPodResult, error) { + + params := make(map[string]string) + if pageNo != 0 { + params["pageNo"] = strconv.Itoa(pageNo) + } + if pageSize != 0 { + params["pageSize"] = strconv.Itoa(pageSize) + } + if keyword != "" { + params["keyword"] = keyword + } + if order != "" { + params["order"] = order + } + if orderBy != "" { + params["orderBy"] = orderBy + } + if serviceId != "" { + params["serviceId"] = serviceId + } + if deploymentId != "" { + params["deploymentId"] = deploymentId + } + + result := &api.ListPodResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.REQUEST_POD_URL). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetPodMetrics - get Pod metrics with the specific parameters +// +// PARAMS: +// - deploymentId: the pod deployment id +// - metricsType: metrics Type +// - serviceProviderStr: service Provider +// - offsetInSeconds: offset Seconds +// +// RETURNS: +// - *ServiceMetricsResult: the result of get Pod Deployment metrics +// - error: nil if ok otherwise the specific error +func (c *Client) GetPodMetrics(podId string, metricsType api.MetricsType, serviceProviderStr api.ServiceProvider, start, end, stepInMin int) (*api.ServiceMetricsResult, error) { + params := make(map[string]string) + if serviceProviderStr != "" { + params["serviceProvider"] = string(serviceProviderStr) + } + if metricsType != "" { + params["metricsType"] = string(metricsType) + } + if podId != "" { + params["podId"] = podId + } + if stepInMin != 0 { + params["stepInMin"] = strconv.Itoa(stepInMin) + } + if start != 0 { + params["start"] = strconv.Itoa(start) + } + if end != 0 { + params["end"] = strconv.Itoa(end) + } + + result := &api.ServiceMetricsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetPodMetricsURI(podId)). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetPodDetail - get pod detail with the specific parameters +// +// PARAMS: +// - podId: pod id +// +// RETURNS: +// - *ListPodResult: the result of list pod +// - error: nil if ok otherwise the specific error +func (c *Client) GetPodDetail(podId string) (*api.PodDetailVo, error) { + + if podId == "" { + return nil, fmt.Errorf("please set argments") + } + result := &api.PodDetailVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.REQUEST_POD_URL + "/" + podId). + WithResult(result). + Do() + + return result, err +} + +// RestartPod - restart pod with the specific parameters +// +// PARAMS: +// - podId: pod id +// +// RETURNS: +// - *ListPodResult: the result of restart pod +// - error: nil if ok otherwise the specific error +func (c *Client) RestartPod(podId string) error { + + if podId == "" { + return fmt.Errorf("please set argments") + } + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(api.REQUEST_POD_URL + "/" + podId + "/restart"). + Do() + + return err +} diff --git a/bce-sdk-go/services/bec/service_test.go b/bce-sdk-go/services/bec/service_test.go new file mode 100644 index 0000000..c7ab8d1 --- /dev/null +++ b/bce-sdk-go/services/bec/service_test.go @@ -0,0 +1,161 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// //////////////////////////////////////////// +// service API +// //////////////////////////////////////////// +func TestListService(t *testing.T) { + res, err := CLIENT.ListService(1, 100, + "", "", "", "", "") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetService(t *testing.T) { + res, err := CLIENT.GetService("s-f9ngbkbc") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCreateService(t *testing.T) { + getReq := &api.CreateServiceArgs{ServiceName: "xxxx-1-test", + PaymentMethod: "postpay", ContainerGroupName: "cg1", + Bandwidth: 100, + NeedPublicIp: false, + Containers: &[]api.ContainerDetails{ + api.ContainerDetails{ + Name: "container01", + Cpu: 1, + Memory: 2, + ImageAddress: "hub.baidubce.com/public/mysql", + ImageVersion: "5.7", + Commands: []string{"sh", + "-c", + "echo OK!&& sleep 3660"}, + VolumeMounts: []api.V1VolumeMount{ + api.V1VolumeMount{ + MountPath: "/temp", + Name: "emptydir01", + }, + }}, + }, + DeployInstances: &[]api.DeploymentInstance{ + api.DeploymentInstance{ + Replicas: 1, + RegionId: "cn-langfang-ct", + }, + }, + Volumes: &api.Volume{ + EmptyDir: &[]api.EmptyDir{ + api.EmptyDir{Name: "emptydir01"}, + }, + }, + Tags: &[]api.Tag{ + api.Tag{ + TagKey: "a", + TagValue: "1"}, + }, + } + res, err := CLIENT.CreateService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetServiceMetrics(t *testing.T) { + res, err := CLIENT.GetServiceMetrics("s-f9ngbkbc", api.MetricsTypeMemory, "", 1661270400, 1661356800, 0) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateService(t *testing.T) { + getReq := &api.UpdateServiceArgs{ServiceName: "s-f9ngbkbc", Type: api.UpdateServiceTypeReplicas, DeployInstances: &[]api.DeploymentInstance{ + api.DeploymentInstance{Region: api.RegionEastChina, Replicas: 1, City: "HANGZHOU", ServiceProvider: api.ServiceChinaMobile}, + }} + res, err := CLIENT.UpdateService("s-f9ngbkbc", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestStopService(t *testing.T) { + res, err := CLIENT.ServiceAction("s-f9ngbkbc", api.ServiceActionStop) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestStartService(t *testing.T) { + res, err := CLIENT.ServiceAction("s-f9ngbkbc", api.ServiceActionStart) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteService(t *testing.T) { + res, err := CLIENT.DeleteService("xxxx-1") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestClient_ServiceBatchOperate(t *testing.T) { + getReq := &api.ServiceBatchOperateArgs{IdList: []string{"xxxx-1", "xxx-2"}, Action: "start"} + res, err := CLIENT.ServiceBatchOperate(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + +} + +func TestClient_ServiceBatchDelete(t *testing.T) { + getReq := &[]string{"xxxx-1", "xxx-2"} + res, err := CLIENT.ServiceBatchDelete(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetPodDeployment(t *testing.T) { + res, err := CLIENT.GetPodDeployment("sts-f9ngbkbc-cn-langfang-ct-uxe4z") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestGetPodDeploymentMetrics(t *testing.T) { + res, err := CLIENT.GetPodDeploymentMetrics("sts-f9ngbkbc-cn-langfang-ct-uxe4z", api.MetricsTypeMemory, "", 1661270400, 1661356800, 0) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestUpdatePodDeploymentReplicas(t *testing.T) { + getReq := &api.UpdateDeploymentReplicasRequest{ + Replicas: 2, + } + res, err := CLIENT.UpdatePodDeploymentReplicas("sts-f9ngbkbc-cn-langfang-ct-uxe4z", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestDeletePodDeployment(t *testing.T) { + getReq := &[]string{"sts-f9ngbkbc-cn-jinan-un-0cloi"} + res, err := CLIENT.DeletePodDeployment(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetPodList(t *testing.T) { + res, err := CLIENT.GetPodList(1, 100, + "", "", "", "", "") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestGetPodMetrics(t *testing.T) { + res, err := CLIENT.GetPodMetrics("sts-f9ngbkbc-cn-langfang-ct-uxe4z-0", api.MetricsTypeMemory, "", 1661270400, 1661356800, 0) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestGetPodDetail(t *testing.T) { + res, err := CLIENT.GetPodDetail("sts-f9ngbkbc-cn-langfang-ct-uxe4z-0") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} +func TestRestartPod(t *testing.T) { + err := CLIENT.RestartPod("sts-f9ngbkbc-cn-langfang-ct-uxe4z-0") + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/bec/vm.go b/bce-sdk-go/services/bec/vm.go new file mode 100644 index 0000000..302f826 --- /dev/null +++ b/bce-sdk-go/services/bec/vm.go @@ -0,0 +1,271 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// CreateVmService - create vm service with the specific parameters +// +// PARAMS: +// - args: the arguments to create a vm service +// +// RETURNS: +// - *CreateVmServiceResult: the result of create vm service +// - error: nil if ok otherwise the specific error +func (c *Client) CreateVmService(args *api.CreateVmServiceArgs) (*api.CreateVmServiceResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.CreateVmServiceResult{} + req := &api.PostHttpReq{Url: api.GetVmURI(), Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// UpdateVmService - update vm service with the specific parameters +// +// PARAMS: +// - args: the arguments to update a vm service +// +// RETURNS: +// - *UpdateVmServiceResult: the result of update vm service +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateVmService(serviceId string, args *api.UpdateVmServiceArgs) (*api.UpdateVmServiceResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.UpdateVmServiceResult{} + req := &api.PostHttpReq{Url: api.GetVmURI() + "/" + serviceId, Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// GetVmServiceList - get vm services with the specific parameters +// +// PARAMS: +// - args: the arguments to get vm services +// +// RETURNS: +// - *ListVmServiceResult: the result of get vm services +// - error: nil if ok otherwise the specific error +func (c *Client) GetVmServiceList(args *api.ListVmServiceArgs) (*api.ListVmServiceResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if args.PageSize != 0 { + params["pageSize"] = strconv.Itoa(args.PageSize) + } + if args.PageNo != 0 { + params["pageNo"] = strconv.Itoa(args.PageNo) + } + if args.OrderBy != "" { + params["orderBy"] = args.OrderBy + } + if args.Order != "" { + params["order"] = args.Order + } + if args.KeywordType != "" { + params["keywordType"] = args.KeywordType + } + if args.Keyword != "" { + params["keyword"] = args.Keyword + } + if args.Status != "" { + params["status"] = args.Status + } + if args.Region != "" { + params["region"] = args.Region + } + if args.OsName != "" { + params["osName"] = args.OsName + } + if args.ServiceId != "" { + params["serviceId"] = args.ServiceId + } + + result := &api.ListVmServiceResult{} + req := &api.GetHttpReq{Url: api.GetVmURI(), Result: result, Params: params} + err := api.Get(c, req) + + return result, err +} + +// GetVmServiceDetail - get vm service detail with the specific parameters +// +// PARAMS: +// - serviceId: vm service id +// +// RETURNS: +// - *VmServiceDetailsVo: the result of vm service detail +// - error: nil if ok otherwise the specific error +func (c *Client) GetVmServiceDetail(serviceId string) (*api.VmServiceDetailsVo, error) { + if serviceId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmServiceDetailsVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmURI() + "/" + serviceId). + WithResult(result). + Do() + return result, err +} + +// GetVmServiceMetrics - get vm service metrics with the specific parameters +// +// PARAMS: +// - serviceId: service id +// - serviceProviderStr: service Provider +// - offsetInSeconds: offset Seconds +// - metricsType: metrics Type +// +// RETURNS: +// - *ServiceMetricsResult: the result of get vm service metrics +// - error: nil if ok otherwise the specific error +func (c *Client) GetVmServiceMetrics(serviceId, serviceProviderStr string, start, end, stepInMin int, metricsType api.MetricsType) (*api.ServiceMetricsResult, error) { + + params := make(map[string]string) + params["serviceId"] = serviceId + if serviceProviderStr != "" { + params["serviceProvider"] = serviceProviderStr + } + if metricsType != "" { + params["metricsType"] = string(metricsType) + } + if start != 0 { + params["start"] = strconv.Itoa(start) + } + if end != 0 { + params["end"] = strconv.Itoa(end) + } + if stepInMin != 0 { + params["stepInMin"] = strconv.Itoa(stepInMin) + } + result := &api.ServiceMetricsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmServiceMonitorURI() + "/" + serviceId). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// VmServiceAction - operate vm service with the specific parameters +// +// PARAMS: +// - serviceId: service id +// - action: operation action +// +// RETURNS: +// - *VmServiceActionResult: the result of operate vm service +// - error: nil if ok otherwise the specific error +func (c *Client) VmServiceAction(serviceId string, action api.VmServiceAction) (*api.VmServiceActionResult, error) { + if serviceId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmServiceActionResult{} + req := &api.PostHttpReq{Url: api.GetVmServiceActionURI(serviceId, string(action)), Result: result, Body: nil} + err := api.Put(c, req) + + return result, err +} + +// DeleteVmService - delete a vm service with the specific parameters +// +// PARAMS: +// - serviceId: service id +// +// RETURNS: +// - *VmServiceActionResult: the result of delete vm service +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVmService(serviceId string) (*api.VmServiceActionResult, error) { + if serviceId == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmServiceActionResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(api.GetVmURI() + "/" + serviceId). + WithResult(result). + Do() + + return result, err +} + +// BatchDeleteVmService - batch delete vm service with the specific parameters +// +// PARAMS: +// - serviceIds: service id list +// +// RETURNS: +// - *VmServiceBatchActionResult: the result of batch delete service id list +// - error: nil if ok otherwise the specific error +func (c *Client) BatchDeleteVmService(serviceIds *[]string) (*api.VmServiceBatchActionResult, error) { + if serviceIds == nil { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmServiceBatchActionResult{} + req := &api.PostHttpReq{Url: api.GetVmURI() + "/batch/delete", Result: result, Body: serviceIds} + err := api.Post(c, req) + + return result, err +} + +// BatchOperateVmService - batch operate vm service with the specific parameters +// +// PARAMS: +// - args: the arguments to batch operate vm service +// +// RETURNS: +// - *VmServiceBatchActionResult: the result of batch operate vm service +// - error: nil if ok otherwise the specific error +func (c *Client) BatchOperateVmService(args *api.VmServiceBatchActionArgs) (*api.VmServiceBatchActionResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + if args.Action != "start" && args.Action != "stop" { + return nil, fmt.Errorf("action is start|stop, please check") + } + + result := &api.VmServiceBatchActionResult{} + req := &api.PostHttpReq{Url: api.GetVmURI() + "/batch/operate", Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} diff --git a/bce-sdk-go/services/bec/vmInstance.go b/bce-sdk-go/services/bec/vmInstance.go new file mode 100644 index 0000000..8328d0b --- /dev/null +++ b/bce-sdk-go/services/bec/vmInstance.go @@ -0,0 +1,335 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BEC service + +// Package bec defines the BEC services of BCE. The supported APIs are all defined in sub-package + +package bec + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// CreateVmServiceInstance - create service vm instance with the specific parameters +// +// PARAMS: +// - serviceId: service Id +// - args: the arguments to create service vm instance +// +// RETURNS: +// - *CreateVmServiceResult: the result of create service instance +// - error: nil if ok otherwise the specific error +func (c *Client) CreateVmServiceInstance(serviceId string, args *api.CreateVmServiceArgs) (*api.CreateVmServiceResult, error) { + if serviceId == "" || args == nil { + return nil, fmt.Errorf("please set argments") + } + result := &api.CreateVmServiceResult{} + req := &api.PostHttpReq{Url: api.GetVmURI() + "/" + serviceId + "/instance", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// GetVmInstanceList - get vm list with the specific parameters +// +// PARAMS: +// - args: the arguments to get vm list +// +// RETURNS: +// - *LogicPageVmInstanceResult: the result of get vm list +// - error: nil if ok otherwise the specific error +func (c *Client) GetVmInstanceList(args *api.ListRequest) (*api.LogicPageVmInstanceResult, error) { + if args == nil { + return nil, fmt.Errorf("please set argments") + } + + params := make(map[string]string) + if args.PageSize != 0 { + params["pageSize"] = strconv.Itoa(args.PageSize) + } + if args.PageNo != 0 { + params["pageNo"] = strconv.Itoa(args.PageNo) + } + if args.OrderBy != "" { + params["orderBy"] = args.OrderBy + } + if args.Order != "" { + params["order"] = args.Order + } + if args.KeywordType != "" { + params["keywordType"] = args.KeywordType + } + if args.Keyword != "" { + params["keyword"] = args.Keyword + } + if args.Status != "" { + params["status"] = args.Status + } + if args.Region != "" { + params["region"] = args.Region + } + if args.OsName != "" { + params["osName"] = args.OsName + } + if args.ServiceId != "" { + params["serviceId"] = args.ServiceId + } + + result := &api.LogicPageVmInstanceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmInstanceURI()). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetVirtualMachine - get vm with the specific parameters +// +// PARAMS: +// - vmID: vm id +// +// RETURNS: +// - *VmInstanceDetailsVo: the result of get vm +// - error: nil if ok otherwise the specific error +func (c *Client) GetVirtualMachine(vmID string) (*api.VmInstanceDetailsVo, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmInstanceDetailsVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmInstanceURI() + "/" + vmID). + WithResult(result). + Do() + + return result, err +} + +// DeleteVmInstance - delete vm instance with the specific parameters +// +// PARAMS: +// - vmID: vm id +// +// RETURNS: +// - *ActionInfoVo: the result of delete vm instance +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVmInstance(vmID string) (*api.ActionInfoVo, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.ActionInfoVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(api.GetVmInstanceURI() + "/" + vmID). + WithResult(result). + Do() + + return result, err +} + +// UpdateVmInstance - update vm with the specific parameters +// +// PARAMS: +// - vmID: vm id +// - args: the arguments to update vm +// +// RETURNS: +// - *UpdateVmDeploymentResult: the result of update vm +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateVmInstance(vmID string, args *api.UpdateVmInstanceArgs) (*api.UpdateVmDeploymentResult, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.UpdateVmDeploymentResult{} + req := &api.PostHttpReq{Url: api.GetVmInstanceURI() + "/" + vmID, Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// BindSecurityGroup - bind vm instance to security group +// +// PARAMS: +// - action: bind +// - args: the arguments to update vm +// +// RETURNS: +// - *UpdateVmDeploymentResult: the result of update vm +// - error: nil if ok otherwise the specific error +func (c *Client) BindSecurityGroup(action string, args *api.BindSecurityGroupInstances) (*api.BindSecurityGroupInstancesResponse, error) { + + result := &api.BindSecurityGroupInstancesResponse{} + req := &api.PostHttpReq{Url: api.GetVmInstanceURI() + "/securityGroup" + "/" + action, Result: result, Body: args} + err := api.Put(c, req) + return result, err +} + +// ReinstallVmInstance - reinstall vm instance with the specific parameters +// +// PARAMS: +// - vmID: vm id +// - args: the arguments to reinstall vm instance +// +// RETURNS: +// - *ReinstallVmInstanceResult: the result of reinstall vm instance +// - error: nil if ok otherwise the specific error +func (c *Client) ReinstallVmInstance(vmID string, args *api.ReinstallVmInstanceArg) (*api.ReinstallVmInstanceResult, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.ReinstallVmInstanceResult{} + req := &api.PostHttpReq{Url: api.GetVmInstanceURI() + "/" + vmID + "/system/reinstall", Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} + +// OperateVmDeployment - operate vm with the specific parameters +// +// PARAMS: +// - vmID: vm id +// - action: the arguments to operate vm +// +// RETURNS: +// - *OperateVmDeploymentResult: the result of operate vm +// - error: nil if ok otherwise the specific error +func (c *Client) OperateVmDeployment(vmID string, action api.VmInstanceBatchOperateAction) (*api.OperateVmDeploymentResult, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.OperateVmDeploymentResult{} + req := &api.PostHttpReq{Url: api.GetVmInstanceURI() + "/" + vmID + "/" + string(action), Result: result, Body: nil} + err := api.Put(c, req) + + return result, err +} + +// GetVmInstanceMetrics - get vm metrics with the specific parameters +// +// PARAMS: +// - vmId: vm id +// - offsetInSeconds: offset Seconds +// - serviceProvider: service provider +// - metricsType: metrics Type +// RETURNS: +// - *ServiceMetricsResult: the result of get vm metrics +// - error: nil if ok otherwise the specific error + +func (c *Client) GetVmInstanceMetrics(vmId, serviceProviderStr string, start, end, stepInMin int, metricsType api.MetricsType) (*api.ServiceMetricsResult, error) { + + params := make(map[string]string) + if serviceProviderStr != "" { + params["serviceProvider"] = serviceProviderStr + } + if metricsType != "" { + params["metricsType"] = string(metricsType) + } + if start != 0 { + params["start"] = strconv.Itoa(start) + } + if end != 0 { + params["end"] = strconv.Itoa(end) + } + if stepInMin != 0 { + params["stepInMin"] = strconv.Itoa(stepInMin) + } + result := &api.ServiceMetricsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmMonitorURI() + "/" + vmId). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// GetVmConfig - get vm config with the specific parameters +// +// PARAMS: +// - vmID: vm id +// +// RETURNS: +// - *VmConfigResult: the result of get vm config +// - error: nil if ok otherwise the specific error +func (c *Client) GetVmConfig(vmID string) (*api.VmConfigResult, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmConfigResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(api.GetVmInstanceURI() + "/" + vmID + "/config"). + WithResult(result). + Do() + + return result, err +} + +// CreateVmPrivateIp - create vm private ip with the specific parameters +// +// PARAMS: +// - vmID: vm id +// - args: the args to create vm private ip +// +// RETURNS: +// - *VmConfigResult: the result of create vm private ip +// - error: nil if ok otherwise the specific error +func (c *Client) CreateVmPrivateIp(vmID string, args *api.CreateVmPrivateIpForm) (*api.VmPrivateIpResult, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmPrivateIpResult{} + req := &api.PostHttpReq{Url: api.GetVmInstanceURI() + "/" + vmID + "/privateIp", Result: result, Body: args} + err := api.Post(c, req) + + return result, err +} + +// DeleteVmPrivateIp - delete vm private ip with the specific parameters +// +// PARAMS: +// - vmID: vm id +// - args: the args to delete vm private ip +// +// RETURNS: +// - *VmPrivateIpResult: the result of delete vm private ip +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVmPrivateIp(vmID string, args *api.DeleteVmPrivateIpForm) (*api.VmPrivateIpResult, error) { + if vmID == "" { + return nil, fmt.Errorf("please set argments") + } + + result := &api.VmPrivateIpResult{} + req := &api.PostHttpReq{Url: api.GetVmInstanceURI() + "/" + vmID + "/privateIp/release", Result: result, Body: args} + err := api.Put(c, req) + + return result, err +} diff --git a/bce-sdk-go/services/bec/vm_instance_test.go b/bce-sdk-go/services/bec/vm_instance_test.go new file mode 100644 index 0000000..4dd57e3 --- /dev/null +++ b/bce-sdk-go/services/bec/vm_instance_test.go @@ -0,0 +1,132 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +////////////////////////////////////////////// +// vmInstance API +////////////////////////////////////////////// + +func TestCreateVmServiceInstance(t *testing.T) { + // 使用vpc网络 + getReq := &api.CreateVmServiceArgs{ + Cpu: 1, Memory: 2, + NeedIpv6PublicIp: false, NeedPublicIp: true, Bandwidth: 100, + DeployInstances: &[]api.DeploymentInstance{ + { + RegionId: "cn-hangzhou-cm", + Replicas: 1, + NetworkType: "vpc", + }, + }, + ImageType: api.ImageTypeBec, + ImageId: "im-6btnw2x2", + SystemVolume: &api.SystemVolumeConfig{ + SizeInGB: 40, + VolumeType: api.DiskTypeNVME, + Name: "sys"}, + KeyConfig: &api.KeyConfig{ + Type: "bccKeyPair", + BccKeyPairIdList: []string{"k-CIg4d2cC"}, + }, + } + res, err := CLIENT.CreateVmServiceInstance("s-bu5xjidw", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCreateVmServiceInstanceTripleLine(t *testing.T) { + // 测试三线节点制定运营商 + getReq1 := &api.CreateVmServiceArgs{ + Cpu: 1, Memory: 2, + NeedIpv6PublicIp: false, NeedPublicIp: true, Bandwidth: 100, + DeployInstances: &[]api.DeploymentInstance{ + { + RegionId: "cn-changchun-ix", + Replicas: 1, + NetworkType: "vpc", + SubServiceProviders: []string{"cm"}, + }, + }, + ImageType: api.ImageTypeBec, + ImageId: "im-6btnw2x2", + SystemVolume: &api.SystemVolumeConfig{ + SizeInGB: 40, + VolumeType: api.DiskTypeNVME, + Name: "sys"}, + KeyConfig: &api.KeyConfig{ + Type: "bccKeyPair", + BccKeyPairIdList: []string{"k-CIg4d2cC"}, + }, + } + res1, err1 := CLIENT.CreateVmServiceInstance("s-bu5xjidw", getReq1) + ExpectEqual(t.Errorf, nil, err1) + t.Logf("%+v", res1) +} + +func TestGetVmInstanceList(t *testing.T) { + getReq := &api.ListRequest{ServiceId: "s-vrowm5qt"} + res, err := CLIENT.GetVmInstanceList(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetVirtualMachine(t *testing.T) { + res, err := CLIENT.GetVirtualMachine("vm-vrowm5qt-cn-baoding-ix-dvaqv") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestOperateVmDeployment(t *testing.T) { + res, err := CLIENT.OperateVmDeployment("vm-czpgb91c-cn-langfang-ct-wgbem", api.VmInstanceBatchOperateStart) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetVmInstanceMetrics(t *testing.T) { + res, err := CLIENT.GetVmInstanceMetrics("vm-2qbftgbf-cn-langfang-ct-f7p9j", "", 1660147200, 1660233600, 0, api.MetricsTypeCpu) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetVmConfig(t *testing.T) { + res, err := CLIENT.GetVmConfig("vm-czpgb91c-cn-langfang-ct-wgbem") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestReinstallVmInstance(t *testing.T) { + req := &api.ReinstallVmInstanceArg{ImageId: "im-dikfxxxx", AdminPass: "1xxAxxx@", ImageType: api.ImageTypeBec, KeyConfig: &api.KeyConfig{Type: "password", AdminPass: "1xxAxxx@"}} + res, err := CLIENT.ReinstallVmInstance("vm-pxxx", req) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateVmDeployment(t *testing.T) { + req := &api.UpdateVmInstanceArgs{Type: "resource", Cpu: 2, Memory: 4, VmName: "vm-czpgb91c-cn-langfang-ct-wgbem"} + res, err := CLIENT.UpdateVmInstance("vm-czpgb91c-cn-langfang-ct-wgbem", req) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBindSecurityGroup(t *testing.T) { + req := &api.BindSecurityGroupInstances{Instances: []api.InstancesBinding{ + api.InstancesBinding{ + InstanceId: "vm-czpgb91c-cn-langfang-ct-wgbem", + SecurityGroupIds: []string{"sg-itlgtacv", "sg-219mosrn"}, + }, + }} + // action: bind or unbind + res, err := CLIENT.BindSecurityGroup("bind", req) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteVmInstance(t *testing.T) { + res, err := CLIENT.DeleteVmInstance("vm-czpgb91c-cn-langfang-ct-wgbem") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} diff --git a/bce-sdk-go/services/bec/vm_test.go b/bce-sdk-go/services/bec/vm_test.go new file mode 100644 index 0000000..fc6fb75 --- /dev/null +++ b/bce-sdk-go/services/bec/vm_test.go @@ -0,0 +1,125 @@ +package bec + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/bec/api" +) + +// //////////////////////////////////////////// +// vmService API +// //////////////////////////////////////////// +func TestCreateVmServiceOnly(t *testing.T) { + getReq := &api.CreateVmServiceArgs{ServiceName: "wcw-test"} + res, err := CLIENT.CreateVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCreateVmService(t *testing.T) { + getReq := &api.CreateVmServiceArgs{KeyConfig: &api.KeyConfig{ + Type: "bccKeyPair", + BccKeyPairIdList: []string{"k-lVBDKoDj"}, + }, ImageId: "m-f0ZRR9qB", Bandwidth: 100, ImageType: api.ImageTypeBec, SystemVolume: &api.SystemVolumeConfig{SizeInGB: 40, VolumeType: api.DiskTypeNVME, Name: "sys"}, + NetworkConfigList: &[]api.NetworkConfig{api.NetworkConfig{NodeType: "SINGLE", NetworksList: &[]api.Networks{api.Networks{NetType: "INTERNAL_IP", NetName: "eth0"}, + api.Networks{NetType: "PUBLIC_IP", NetName: "eth1"}}}}, DeployInstances: &[]api.DeploymentInstance{api.DeploymentInstance{RegionId: "cn-langfang-ct", Replicas: 1, + NetworkType: "classic"}}, DisableIntranet: false, NeedPublicIp: true, NeedIpv6PublicIp: false, SecurityGroupIds: []string{"sg-219mosrn"}, + DnsConfig: &api.DnsConfig{ + DnsType: "DEFAULT", + }, Cpu: 2, Memory: 4, PaymentMethod: "postpay"} + res, err := CLIENT.CreateVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestUpdateVmService(t *testing.T) { + getReq := &api.UpdateVmServiceArgs{ + UpdateBecVmForm: api.UpdateBecVmForm{ + Type: api.UpdateVmReplicas, + KeyConfig: &api.KeyConfig{ + Type: "bccKeyPair", BccKeyPairIdList: []string{"k-lVBDKoDj"}, + }, + }, DeployInstances: &[]api.DeploymentInstance{ + api.DeploymentInstance{ + RegionId: "cn-jinan-cm", + Replicas: 1, + NetworkType: "vpc", + }, + }, ReplicaTemplate: api.ReplicaTemplate{ + Type: "template", + TemplateId: "tmpl-gc4maqay", + }, + } + res, err := CLIENT.UpdateVmService("s-dstkrmda", getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetVmServiceList(t *testing.T) { + getReq := &api.ListVmServiceArgs{} + res, err := CLIENT.GetVmServiceList(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetVmServiceDetail(t *testing.T) { + res, err := CLIENT.GetVmServiceDetail("s-dstkrmda") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestVmServiceAction(t *testing.T) { + res, err := CLIENT.VmServiceAction("s-dstkrmda", api.VmServiceActionStart) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGetVmServiceMetrics(t *testing.T) { + res, err := CLIENT.GetVmServiceMetrics("s-mifwgtju", "", 1660147200, 1660233600, 1, api.MetricsTypeCpu) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestCrateVmPrivateIp(t *testing.T) { + // 添加虚机辅助IP + crateVmPrivateIpReq := &api.CreateVmPrivateIpForm{SecondaryPrivateIpAddressCount: 1} + res, err := CLIENT.CreateVmPrivateIp("vm-czpgb91c-cn-langfang-ct-wgbem", crateVmPrivateIpReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteVmPrivateIp(t *testing.T) { + // 删除虚机辅助IP + deleteVmPrivateIpReq := &api.DeleteVmPrivateIpForm{PrivateIps: []string{"172.18.176.54"}} + delRes, err := CLIENT.DeleteVmPrivateIp("vm-czpgb91c-cn-langfang-ct-wgbem", deleteVmPrivateIpReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", delRes) +} + +func TestBatchOperateVmServiceStop(t *testing.T) { + getReq := &api.VmServiceBatchActionArgs{IdList: []string{"s-xxxxx-1", "s-xxxxx-2"}, + Action: api.VmServiceBatchStart} + res, err := CLIENT.BatchOperateVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBatchOperateVmServiceStart(t *testing.T) { + getReq := &api.VmServiceBatchActionArgs{IdList: []string{"s-bu5xjidw"}, Action: api.VmServiceBatchStop} + res, err := CLIENT.BatchOperateVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestDeleteVmService(t *testing.T) { + res, err := CLIENT.DeleteVmService("s-xxxx") + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestBatchDeleteVmService(t *testing.T) { + getReq := &[]string{"s-xxxx-1", "s-xxxx-2"} + res, err := CLIENT.BatchDeleteVmService(getReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} diff --git a/bce-sdk-go/services/bie/api/common.go b/bce-sdk-go/services/bie/api/common.go new file mode 100644 index 0000000..2dc95b9 --- /dev/null +++ b/bce-sdk-go/services/bie/api/common.go @@ -0,0 +1,113 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// commond.go - commmon and shared logic + +// Package api defines all APIs supported by the BIE service of BCE. +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +type PostHttpReq struct { + Url string + Body interface{} + Result interface{} + Params map[string]string +} + +type GetHttpReq struct { + Url string + Result interface{} + Params map[string]string +} + +func Post(cli bce.Client, phr *PostHttpReq) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + + return PostOrPut(cli, phr, req) +} + +func Put(cli bce.Client, phr *PostHttpReq) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + + return PostOrPut(cli, phr, req) +} + +func PostOrPut(cli bce.Client, phr *PostHttpReq, req *bce.BceRequest) error { + req.SetUri(phr.Url) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + if phr.Body != nil { + jsonBytes, jsonErr := json.Marshal(phr.Body) + if jsonErr != nil { + return jsonErr + } + // fmt.Println(string(jsonBytes)) + bodyObj, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + req.SetBody(bodyObj) + } + + if phr.Params != nil { + req.SetParams(phr.Params) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + if phr.Result != nil { + if err := resp.ParseJsonBody(phr.Result); err != nil { + return err + } + } + return nil +} + +func Get(cli bce.Client, ghr *GetHttpReq) error { + req := &bce.BceRequest{} + req.SetUri(ghr.Url) + req.SetMethod(http.GET) + + if ghr.Params != nil { + req.SetParams(ghr.Params) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + if err := resp.ParseJsonBody(ghr.Result); err != nil { + return err + } + return nil +} diff --git a/bce-sdk-go/services/bie/api/config.go b/bce-sdk-go/services/bie/api/config.go new file mode 100644 index 0000000..031dc7c --- /dev/null +++ b/bce-sdk-go/services/bie/api/config.go @@ -0,0 +1,281 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// config.go - the config related APIs definition supported by the BIE service + +// Package api defines all APIs supported by the BIE service of BCE. +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + PREFIX_V3CORE = "/v3/core" +) + +// ListConfig - list all configs +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - coreid: id of the core +// +// RETURNS: +// - *ListConfigResult: the result config list +// - error: nil if ok otherwise the specific error +func ListConfig(cli bce.Client, coreid string, lcr *ListConfigReq) (*ListConfigResult, error) { + params := map[string]string{} + + if lcr.Status != "" { + params["status"] = lcr.Status + } + params["pageNo"] = strconv.Itoa(lcr.PageNo) + params["pageSize"] = strconv.Itoa(lcr.PageSize) + + url := PREFIX_V3CORE + "/" + coreid + "/config" + result := &ListConfigResult{} + req := &GetHttpReq{Url: url, Result: result, Params: params} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// GetConfig - get a config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - coreid: id of the core +// - ver: version, e.g:$LATEST +// +// RETURNS: +// - *CfgResult: the result config +// - error: nil if ok otherwise the specific error +func GetConfig(cli bce.Client, coreid string, ver string) (*CfgResult, error) { + url := PREFIX_V3CORE + "/" + coreid + "/config/" + ver + + result := &CfgResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// PubConfig - pub a config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cpr: id of the core and version +// +// RETURNS: +// - *CfgResult: the pub result +// - error: nil if ok otherwise the specific error +func PubConfig(cli bce.Client, cpr *CoreidVersion, cpb *CfgPubBody) (*CfgResult, error) { + url := PREFIX_V3CORE + "/" + cpr.Coreid + "/config/" + cpr.Version + "/publish" + result := &CfgResult{} + req := &PostHttpReq{Url: url, Body: cpb, Result: result} + err := Post(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// DeployConfig - deploy a config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - coreid: id of the core +// - ver: version, e.g:$LATEST +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeployConfig(cli bce.Client, coreid string, ver string) error { + url := PREFIX_V3CORE + "/" + coreid + "/config/" + ver + "/deploy" + + req := &PostHttpReq{Url: url} + err := Post(cli, req) + if err != nil { + return err + } + + return nil +} + +// DownloadConfig - download a config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *CfgDownloadReq: id, version, with bin or not +// +// RETURNS: +// - *CfgDownloadResult: the result +// - error: nil if ok otherwise the specific error +func DownloadConfig(cli bce.Client, cdr *CfgDownloadReq) (*CfgDownloadResult, error) { + url := PREFIX_V3CORE + "/" + cdr.Coreid + "/config/" + cdr.Version + "/download" + params := map[string]string{"withBin": strconv.FormatBool(cdr.WithBin)} + result := &CfgDownloadResult{} + req := &GetHttpReq{Url: url, Params: params, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// CreateService - create a service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *CoreidVersion: coreid, version +// - *CreateServiceReq: request parameters +// +// RETURNS: +// - *ServiceResult: the result +// - error: nil if ok otherwise the specific error +func CreateService(cli bce.Client, cv *CoreidVersion, + sr *CreateServiceReq) (*ServiceResult, error) { + url := PREFIX_V3CORE + "/" + cv.Coreid + "/config/" + cv.Version + "/service" + + result := &ServiceResult{} + req := &PostHttpReq{Url: url, Body: sr, Result: result} + err := Post(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// GetService - get a service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *IdVerName: coreid, version and name +// +// RETURNS: +// - *ServiceResult: the result +// - error: nil if ok otherwise the specific error +func GetService(cli bce.Client, ivn *IdVerName) (*ServiceResult, error) { + url := PREFIX_V3CORE + "/" + ivn.Coreid + "/config/" + ivn.Version + "/service/" + ivn.Name + + result := &ServiceResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// EditService - edit a service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *IdVerName: coreid, version, and name +// +// RETURNS: +// - *ServiceResult: the result +// - error: nil if ok otherwise the specific error +func EditService(cli bce.Client, ivn *IdVerName, + esr *EditServiceReq) (*ServiceResult, error) { + url := PREFIX_V3CORE + "/" + ivn.Coreid + "/config/" + ivn.Version + "/service/" + ivn.Name + + result := &ServiceResult{} + req := &PostHttpReq{Url: url, Body: esr, Result: result} + err := Put(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// DeleteService - delete a service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *IdVerName: coreid, version, and name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeleteService(cli bce.Client, ivn *IdVerName) error { + url := PREFIX_V3CORE + "/" + ivn.Coreid + "/config/" + ivn.Version + "/service/" + ivn.Name + + req := &bce.BceRequest{} + req.SetUri(url) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +// ReorderService - reorder service after an other service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *IdVerName: coreid, version, and name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func ReorderService(cli bce.Client, ivn *IdVerName, after string) error { + url := PREFIX_V3CORE + "/" + ivn.Coreid + "/config/" + ivn.Version + "/service/" + ivn.Name + url += "/after/" + after + + req := &PostHttpReq{Url: url} + err := Post(cli, req) + if err != nil { + return err + } + + return nil +} + +// VolumeOp - attache of detach volumes +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *CoreidVersion: coreid, version +// - *VolumeOpReq: request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func VolumeOp(cli bce.Client, cv *CoreidVersion, vor *VolumeOpReq) error { + url := PREFIX_V3CORE + "/" + cv.Coreid + "/config/" + cv.Version + "/volume" + + req := &PostHttpReq{Url: url, Body: vor} + err := Put(cli, req) + if err != nil { + return err + } + + return nil +} diff --git a/bce-sdk-go/services/bie/api/const.go b/bce-sdk-go/services/bie/api/const.go new file mode 100644 index 0000000..f4c4f12 --- /dev/null +++ b/bce-sdk-go/services/bie/api/const.go @@ -0,0 +1,20 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// const.go - define common constants +package api + +const ( + PREFIX = "/v3/group" +) diff --git a/bce-sdk-go/services/bie/api/core.go b/bce-sdk-go/services/bie/api/core.go new file mode 100644 index 0000000..6511a2c --- /dev/null +++ b/bce-sdk-go/services/bie/api/core.go @@ -0,0 +1,111 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// core.go - the core APIs definition supported by the BIE service + +// Package api defines all APIs supported by the BIE service of BCE. +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +// ListCore - list all core of a group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - groupUuid: id of the group +// +// RETURNS: +// - *ListCoreResult: the result core list +// - error: nil if ok otherwise the specific error +func ListCore(cli bce.Client, groupUuid string) (*ListCoreResult, error) { + url := PREFIX + "/" + groupUuid + "/core" + + result := &ListCoreResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// GetCore - get a core of a group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - groupUuid: id of the group +// - coreid: id of the core +// +// RETURNS: +// - *CoreResult: the result core +// - error: nil if ok otherwise the specific error +func GetCore(cli bce.Client, groupUuid string, coreid string) (*CoreResult, error) { + url := PREFIX + "/" + groupUuid + "/core/" + coreid + + result := &CoreResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// RenewCoreAuth - renew the auth of a core +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - coreid: id of the core +// +// RETURNS: +// - *CoreInfo: the result core info +// - error: nil if ok otherwise the specific error +func RenewCoreAuth(cli bce.Client, coreid string) (*CoreInfo, error) { + url := "/v3/core/" + coreid + "/renew-auth" + + result := &CoreInfo{} + req := &PostHttpReq{Url: url, Result: result} + err := Post(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// GetCoreStatus - get the status of a core +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - coreid: id of the core +// +// RETURNS: +// - *CoreStatus: the status of the core +// - error: nil if ok otherwise the specific error +func GetCoreStatus(cli bce.Client, coreid string) (*CoreStatus, error) { + url := "/v3/core/" + coreid + "/online" + + result := &CoreStatus{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} diff --git a/bce-sdk-go/services/bie/api/group.go b/bce-sdk-go/services/bie/api/group.go new file mode 100644 index 0000000..2d9f128 --- /dev/null +++ b/bce-sdk-go/services/bie/api/group.go @@ -0,0 +1,148 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// group.go - the group APIs definition supported by the BIE service + +// Package api defines all APIs supported by the BIE service of BCE. +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListGroup - list all groups of the account +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *ListGroupReq: page no, page size, and name +// +// RETURNS: +// - *ListGroupResult: the result group list structure +// - error: nil if ok otherwise the specific error +func ListGroup(cli bce.Client, lgr *ListGroupReq) (*ListGroupResult, error) { + url := PREFIX + params := map[string]string{} + if lgr.Name != "" { + params["name"] = lgr.Name + } + if lgr.PageNo != 0 { + params["pageNo"] = strconv.Itoa(lgr.PageNo) + } + if lgr.PageSize != 0 { + params["pageSize"] = strconv.Itoa(lgr.PageSize) + } + result := &ListGroupResult{} + req := &GetHttpReq{Url: url, Result: result, Params: params} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// GetGroup - get a group of the account +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - groupUuid: id of the group +// +// RETURNS: +// - *ListGroupResult: the result group list structure +// - error: nil if ok otherwise the specific error +func GetGroup(cli bce.Client, groupUuid string) (*Group, error) { + url := PREFIX + "/" + groupUuid + + result := &Group{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// CreateGroup - create a group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cgr: parameters to create group +// +// RETURNS: +// - *CreateGroupResult: the result group +// - error: nil if ok otherwise the specific error +func CreateGroup(cli bce.Client, cgr *CreateGroupReq) (*CreateGroupResult, error) { + url := PREFIX + params := map[string]string{"withCore": "true"} + + result := &CreateGroupResult{} + req := &PostHttpReq{Url: url, Result: result, Body: cgr, Params: params} + err := Post(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// EditGroup - edit a group +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - groupId: the group to edit +// - egr: parameters to update group +// +// RETURNS: +// - *Group: the result group +// - error: nil if ok otherwise the specific error +func EditGroup(cli bce.Client, groupId string, egr *EditGroupReq) (*Group, error) { + url := PREFIX + "/" + groupId + params := map[string]string{"withCore": "true"} + + result := &Group{} + req := &PostHttpReq{Url: url, Result: result, Body: egr, Params: params} + err := Put(cli, req) + if err != nil { + return nil, err + } + + return result, nil +} + +// DeleteGroup - delete a group of the account +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - groupUuid: id of the group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeleteGroup(cli bce.Client, groupUuid string) error { + req := &bce.BceRequest{} + req.SetUri(PREFIX + "/" + groupUuid) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} diff --git a/bce-sdk-go/services/bie/api/image.go b/bce-sdk-go/services/bie/api/image.go new file mode 100644 index 0000000..1b766cf --- /dev/null +++ b/bce-sdk-go/services/bie/api/image.go @@ -0,0 +1,187 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// iamge.go - the docker image related APIs definition supported by the BIE service + +// Package api defines all APIs supported by the BIE service of BCE. +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + PREFIX_V3MODSYS = "/v3/module/system" + PREFIX_V3MODUSR = "/v3/module/user" +) + +// ListImageSys - list all system docker images +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - ListImageReq: list request parameters +// +// RETURNS: +// - *ListImageResult: the result iamge list +// - error: nil if ok otherwise the specific error +func ListImageSys(cli bce.Client, lir *ListImageReq) (*ListImageResult, error) { + url := PREFIX_V3MODSYS + result := &ListImageResult{} + params := map[string]string{} + params["pageNo"] = strconv.Itoa(lir.PageNo) + params["pageSize"] = strconv.Itoa(lir.PageSize) + if lir.Tag != "" { + params["tag"] = lir.Tag + } + req := &GetHttpReq{Url: url, Result: result, Params: params} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// GetImageSys - get a system docker images +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - uuid: the image uuid +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func GetImageSys(cli bce.Client, uuid string) (*Image, error) { + url := PREFIX_V3MODSYS + "/" + uuid + result := &Image{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// ListImageUser - list all user docker images +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - ListImageReq: list request parameters +// +// RETURNS: +// - *ListImageResult: the result iamge list +// - error: nil if ok otherwise the specific error +func ListImageUser(cli bce.Client, lir *ListImageReq) (*ListImageResult, error) { + url := PREFIX_V3MODUSR + result := &ListImageResult{} + params := map[string]string{} + params["pageNo"] = strconv.Itoa(lir.PageNo) + params["pageSize"] = strconv.Itoa(lir.PageSize) + if lir.Tag != "" { + params["tag"] = lir.Tag + } + req := &GetHttpReq{Url: url, Result: result, Params: params} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// GetImageUser - get a user docker image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - uuid: the image uuid +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func GetImageUser(cli bce.Client, uuid string) (*Image, error) { + url := PREFIX_V3MODUSR + "/" + uuid + result := &Image{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// CreateImageUser - create a user docker image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - CreateImageReq: request parameters, name, image url, description +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func CreateImageUser(cli bce.Client, cir *CreateImageReq) (*Image, error) { + url := PREFIX_V3MODUSR + result := &Image{} + req := &PostHttpReq{Url: url, Result: result, Body: cir} + err := Post(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// EditImageUser - edit a user docker image information +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - uuid: the image uuid +// - EditImageReq: request parameter: description +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func EditImageUser(cli bce.Client, uuid string, eir *EditImageReq) (*Image, error) { + url := PREFIX_V3MODUSR + "/" + uuid + result := &Image{} + req := &PostHttpReq{Url: url, Result: result, Body: eir} + err := Put(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// DeleteImageUser - delete a user docker image +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - uuid: the image uuid +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeleteImageUser(cli bce.Client, uuid string) error { + url := PREFIX_V3MODUSR + "/" + uuid + req := &bce.BceRequest{} + req.SetUri(url) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} diff --git a/bce-sdk-go/services/bie/api/model.go b/bce-sdk-go/services/bie/api/model.go new file mode 100644 index 0000000..2f87025 --- /dev/null +++ b/bce-sdk-go/services/bie/api/model.go @@ -0,0 +1,411 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +type Group struct { + GroupUuid string `json:"groupUuid"` + Name string `json:"name"` + Description string `json:"description"` + Platform string `json:"platform"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type ListGroupReq struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Name string `json:"name"` +} + +type ListGroupResult struct { + TotalCountByUser int `json:"totalCountByUser"` + TotalCount int `json:"totalCount"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Result []Group `json:"result"` +} + +type CreateGroupReq struct { + Name string `json:"name"` + Description string `json:"description"` + AuthType string `json:"authType"` + Platform string `json:"platform"` +} + +type CoreAuth struct { + AuthType string `json:"authType"` + Password string `json:"password"` + PrivateKey string `json:"privateKey"` + Certificate string `json:"certificate"` + UserName string `json:"username"` + Tcp string `json:"tcp"` + Hostname string `json:"hostname"` + Ssl string `json:"ssl"` + Wss string `json:"wss"` +} + +type CoreInfo struct { + DeviceUuid string `json:"deviceUuid"` + Name string `json:"name"` + Description string `json:"description"` + AuthType string `json:"authType"` + Platform string `json:"platform"` + BinVersion string `json:"binVersion"` + CoreAuth CoreAuth `json:"coreAuth"` + DownloadUrl string `json:"downloadUrl"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type CoreResult struct { + DeviceUuid string `json:"deviceUuid"` + Name string `json:"name"` + ConfVersion string `json:"confVersion"` + Report string `json:"report"` + AuthType string `json:"authType"` + Description string `json:"description"` + Platform string `json:"platform"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type ListCoreResult struct { + Result []CoreResult `json:"result"` +} + +type CreateGroupResult struct { + GroupInfo Group `json:"groupInfo"` + CoreInfo CoreInfo `json:"coreInfo"` +} + +type EditGroupReq struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type CoreStatus struct { + IsCoreOnline bool `json:"isCoreOnline"` +} + +type Config struct { + Uuid string `json:"uuid"` + Status string `json:"status"` + Version string `json:"version"` + Description string `json:"description"` + LastDeployTime string `json:"lastDeployTime"` + CreateTime string `json:"createTime"` +} + +type ListConfigResult struct { + TotalCount int `json:"totalCount"` + Result []Config `json:"result"` + Language string `json:"language"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Region bool `json:"region"` +} + +type ListConfigReq struct { + Status string `json:"status"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type CfgService struct { + Uuid string `json:"uuid"` + Name string `json:"name"` + ModuleUuid string `json:"moduleUuid"` + ModuleImage string `json:"moduleImage"` + ModuleName string `json:"moduleName"` + ModuleTags string `json:"moduleTags"` + ModuleCategory string `json:"moduleCategory"` + Mounts []string `json:"mounts"` + Description string `json:"description"` + CreateTime string `json:"createTime"` +} + +type CfgVolume struct { + Name string `json:"name"` + Version string `json:"version"` + HostPath string `json:"hostPath"` + Deletable bool `json:"deletable"` + CreateTime string `json:"createTime"` +} + +type CfgResult struct { + Uuid string `json:"uuid"` + Status string `json:"status"` + Version string `json:"version"` + Description string `json:"description"` + LastDeployTime string `json:"lastDeployTime"` + CreateTime string `json:"createTime"` + ConfigServices []CfgService `json:"configServices"` + ConfigVolumes []CfgVolume `json:"configVolumes"` +} + +type CoreidVersion struct { + Coreid string `json:"coreid"` + Version string `json:"version"` +} + +type CfgPubBody struct { + Description string `json:"description"` +} + +type CfgDownloadReq struct { + Coreid string `json:"coreid"` + Version string `json:"version"` + WithBin bool `json:"withBin"` +} + +type CfgDownloadResult struct { + Url string `json:"url"` + Md5 string `json:"md5"` +} + +type CfgRestart struct { + Retry map[string]interface{} `json:"restart"` +} + +type CreateServiceReq struct { + Name string `json:"name"` + ModuleUuid string `json:"moduleUuid"` + ModuleCategory string `json:"moduleCategory"` + Description string `json:"description"` + Replica int `json:"replica"` + Mounts []map[string]interface{} `json:"mounts"` + Ports []string `json:"ports"` + Args []string `json:"args"` + Env map[string]string `json:"env"` + Devs []string `json:"devs"` + Restart map[string]interface{} `json:"restart"` + Resources map[string]interface{} `json:"resources"` +} + +type ServiceResult struct { + Uuid string `json:"uuid"` + Name string `json:"name"` + ModuleImage string `json:"moduleImage"` + ModuleName string `json:"moduleName"` + ModuleTags string `json:"moduleTags"` + ModuleCategory string `json:"moduleCategory"` + Description string `json:"description"` + Mounts []map[string]interface{} `json:"mounts"` + Ports []string `json:"ports"` + Args []string `json:"args"` + Env map[string]string `json:"env"` + Devs []string `json:"devs"` + Restart map[string]interface{} `json:"restart"` + Resources map[string]interface{} `json:"resources"` + CreateTime string `json:"createTime"` +} + +type EditServiceReq struct { + Description string `json:"description"` + Replica int `json:"replica"` + Mounts []map[string]interface{} `json:"mounts"` + Ports []string `json:"ports"` + Args []string `json:"args"` + Env map[string]string `json:"env"` + Devs []string `json:"devs"` + Restart map[string]interface{} `json:"restart"` + Resources map[string]interface{} `json:"resources"` +} + +type IdVerName struct { + Coreid string `json:"coreid"` + Version string `json:"version"` + Name string `json:"name"` +} + +type NameVersion struct { + Name string `json:"name"` + Version string `json:"version"` +} + +type VolumeOpReq struct { + Attach []NameVersion `json:"attach"` + Detach []NameVersion `json:"detach"` +} + +// Volume +type VolTemplate struct { + Name string `json:"name"` + Code string `json:"code"` + Category string `json:"category"` + Tags []string `json:"tags"` +} + +type ListVolTemplate struct { + Result []VolTemplate `json:"result"` +} + +type CreateVolReq struct { + Name string `json:"name"` + TemplateCode string `json:"templateCode"` + Description string `json:"description"` + Tags []string `json:"tags"` + HostPath string `json:"hostPath"` +} + +type VolFile struct { + FileName string `json:"fileName"` + Type string `json:"type"` + Viewable bool `json:"viewable"` + Editable bool `json:"editable"` + Deletable bool `json:"deletable"` +} + +type VolumeResult struct { + Uuid string `json:"uuid"` + Name string `json:"name"` + Tags []string `json:"tags"` + HostPath string `json:"hostPath"` + Files []VolFile `json:"files"` + Description string `json:"description"` + Version string `json:"version"` + Template VolTemplate `json:"template"` + NewFile bool `json:"newFile"` + CleanFile bool `json:"cleanFile"` + CreateTime string `json:"createTime"` +} + +type ListVolumeReq struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Tag string `json:"tag"` + Name string `json:"name"` +} + +type ListVolumeResult struct { + TotalCount int `json:"totalCount"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Result []VolumeResult `json:"result"` +} + +type EditVolumeReq struct { + Description string `json:"description"` + Tags []string `json:"tags"` + HostPath string `json:"hostPath"` +} + +type ListVolumeVerResult struct { + Result []VolumeResult `json:"result"` +} + +type VolDownloadResult struct { + Url string `json:"url"` +} + +type CreateVolFileReq struct { + Content string `json:"content"` + FileName string `json:"fileName"` +} + +type GetVolFileReq struct { + Name string `json:"name"` + Version string `json:"version"` + FileName string `json:"fileName"` +} + +type Name2 struct { + Name string `json:"name"` + FileName string `json:"fileName"` +} + +type EditVolFileReq struct { + Content string `json:"content"` +} + +type ListVolCoreResult struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Result []struct { + ConfigVersion string `json:"configVersion"` + DeviceName string `json:"deviceName"` + DeviceUUID string `json:"deviceUuid"` + GroupUUID string `json:"groupUuid"` + VolumeName string `json:"volumeName"` + VolumeVersion string `json:"volumeVersion"` + } `json:"result"` + TotalCount int `json:"totalCount"` +} + +type ListVolCoreReq struct { + Name string `json:"name"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type EditCoreVolVerReq struct { + Jobs []EditCoreVolVerEntry `json:"jobs"` +} + +type EditCoreVolVerEntry struct { + DeviceUUID string `json:"deviceUuid"` + NewVersion string `json:"newVersion"` + OldVersion string `json:"oldVersion"` +} + +type ImportCfcReq struct { + Name string `json:"name"` + Version string `json:"version"` +} + +type ImportBosReq struct { + BosBucket string `json:"bosBucket"` + BosKey string `json:"bosKey"` +} + +// image +type ListImageReq struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Tag string `json:"tag"` +} + +type Image struct { + Category string `json:"category"` + CreateTime string `json:"createTime"` + Description string `json:"description"` + Image string `json:"image"` + Name string `json:"name"` + Tags string `json:"tags"` + UUID string `json:"uuid"` + Warehouse string `json:"warehouse"` + Replica struct { + Min string `json:"min"` + } `json:"replica"` +} + +type ListImageResult struct { + Result []Image `json:"result"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type CreateImageReq struct { + Description string `json:"description"` + Image string `json:"image"` + Name string `json:"name"` +} + +type EditImageReq struct { + Description string `json:"description"` +} diff --git a/bce-sdk-go/services/bie/api/volume.go b/bce-sdk-go/services/bie/api/volume.go new file mode 100644 index 0000000..9d317f6 --- /dev/null +++ b/bce-sdk-go/services/bie/api/volume.go @@ -0,0 +1,435 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// volume.go - the volume related APIs definition supported by the BIE service + +// Package api defines all APIs supported by the BIE service of BCE. +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + PREFIX_V3VOLTPL = "/v3/volumeTemplate" + PREFIX_V3VOL = "/v3/volume" +) + +// ListVolumeTpl - list all volume template +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListVolTemplate: the result volume template list +// - error: nil if ok otherwise the specific error +func ListVolumeTpl(cli bce.Client) (*ListVolTemplate, error) { + url := PREFIX_V3VOLTPL + result := &ListVolTemplate{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// CreateVolume - create a volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - CreateVolReq: the request parameters +// +// RETURNS: +// - *VolumeResult: the result volume +// - error: nil if ok otherwise the specific error +func CreateVolume(cli bce.Client, cvr *CreateVolReq) (*VolumeResult, error) { + url := PREFIX_V3VOL + result := &VolumeResult{} + req := &PostHttpReq{Url: url, Result: result, Body: cvr} + err := Post(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// ListVolume - list a bunch of volumes +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - ListVolReq: the request parameters +// +// RETURNS: +// - *ListVolumeResult: the result list +// - error: nil if ok otherwise the specific error +func ListVolume(cli bce.Client, lvr *ListVolumeReq) (*ListVolumeResult, error) { + url := PREFIX_V3VOL + result := &ListVolumeResult{} + params := map[string]string{ + "pageNo": strconv.Itoa(lvr.PageNo), + "pageSize": strconv.Itoa(lvr.PageSize)} + if lvr.Name != "" { + params["name"] = lvr.Name + } + if lvr.Tag != "" { + params["tag"] = lvr.Tag + } + + req := &GetHttpReq{Url: url, Result: result, Params: params} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// GetVolume - get a volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the requested volume name +// +// RETURNS: +// - *VolumeResult: the result vaolume +// - error: nil if ok otherwise the specific error +func GetVolume(cli bce.Client, name string) (*VolumeResult, error) { + url := PREFIX_V3VOL + "/" + name + result := &VolumeResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// EditVolume - edit a volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the requested volume name +// - *EditVolumeReq: request parameters +// +// RETURNS: +// - *VolumeResult: the result vaolume +// - error: nil if ok otherwise the specific error +func EditVolume(cli bce.Client, name string, evr *EditVolumeReq) (*VolumeResult, error) { + url := PREFIX_V3VOL + "/" + name + result := &VolumeResult{} + req := &PostHttpReq{Url: url, Result: result, Body: evr} + err := Put(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// DeleteVolume - delete a volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the requested volume name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeleteVolume(cli bce.Client, name string) error { + url := PREFIX_V3VOL + "/" + name + req := &bce.BceRequest{} + req.SetUri(url) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +// ListVolumeVer - list version list of a volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - NameVersion: the request parameters, version can be empty +// +// RETURNS: +// - *ListVolumeVerResult: the result list +// - error: nil if ok otherwise the specific error +func ListVolumeVer(cli bce.Client, nv *NameVersion) (*ListVolumeVerResult, error) { + url := PREFIX_V3VOL + "/" + nv.Name + "/version" + params := map[string]string{} + if nv.Version != "" { + params["version"] = nv.Version + } + + result := &ListVolumeVerResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// PubVolumeVer - pub version list of a volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the request volume name +// +// RETURNS: +// - *VolumeResult: the result volume +// - error: nil if ok otherwise the specific error +func PubVolumeVer(cli bce.Client, name string) (*VolumeResult, error) { + url := PREFIX_V3VOL + "/" + name + "/version" + + result := &VolumeResult{} + req := &PostHttpReq{Url: url, Result: result} + err := Post(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// DownloadVolVer - get the download address of a specific version of volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the request volume name +// - version: the request volume version +// +// RETURNS: +// - *VolDownloadResult: the result +// - error: nil if ok otherwise the specific error +func DownloadVolVer(cli bce.Client, name string, + version string) (*VolDownloadResult, error) { + url := PREFIX_V3VOL + "/" + name + "/version/" + version + "/zipfile" + + result := &VolDownloadResult{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// CreateVolFile - create a volume file +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the request volume name +// - *CreateVolFileReq: request parameters +// +// RETURNS: +// - *CreateVolFileReq: the result +// - error: nil if ok otherwise the specific error +func CreateVolFile(cli bce.Client, name string, + cvf *CreateVolFileReq) (*CreateVolFileReq, error) { + url := PREFIX_V3VOL + "/" + name + "/file" + + result := &CreateVolFileReq{} + req := &PostHttpReq{Url: url, Result: result, Body: cvf} + err := Post(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// GetVolumeFile - get a volume file +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - GetVolFileReq: volume name, version anf filename +// +// RETURNS: +// - *ListVolumeVerResult: the result list +// - error: nil if ok otherwise the specific error +func GetVolumeFile(cli bce.Client, cvfr *GetVolFileReq) (*CreateVolFileReq, error) { + url := PREFIX_V3VOL + "/" + cvfr.Name + "/version/" + cvfr.Version + "/file/" + cvfr.FileName + + result := &CreateVolFileReq{} + req := &GetHttpReq{Url: url, Result: result} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// EditVolumeFile - edit a volume file +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *Name2: the requested volume name and file name +// - *EditVolFileReq: the content, the request body +// +// RETURNS: +// - *CreateVolFileReq: the result +// - error: nil if ok otherwise the specific error +func EditVolumeFile(cli bce.Client, names *Name2, + body *EditVolFileReq) (*CreateVolFileReq, error) { + url := PREFIX_V3VOL + "/" + names.Name + "/file/" + names.FileName + + result := &CreateVolFileReq{} + req := &PostHttpReq{Url: url, Result: result, Body: body} + err := Put(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// DeleteVolFile - delete a volume file +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the requested volume name +// - filename: the requested volume filename +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeleteVolFile(cli bce.Client, name string, filename string) error { + url := PREFIX_V3VOL + "/" + name + "/file/" + filename + req := &bce.BceRequest{} + req.SetUri(url) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +// ClearVolFile - clear all volume files +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the requested volume name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func ClearVolFile(cli bce.Client, name string) error { + url := PREFIX_V3VOL + "/" + name + "/file" + req := &bce.BceRequest{} + req.SetUri(url) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +// ListVolCore - list the cores associated with the volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - *ListVolCoreReq: the request parameters +// +// RETURNS: +// - *ListVolumeVerResult: the result list +// - error: nil if ok otherwise the specific error +func ListVolCore(cli bce.Client, lvcr *ListVolCoreReq) (*ListVolCoreResult, error) { + url := PREFIX_V3VOL + "/" + lvcr.Name + "/core" + params := map[string]string{ + "pageNo": strconv.Itoa(lvcr.PageNo), + "pageSize": strconv.Itoa(lvcr.PageSize)} + + result := &ListVolCoreResult{} + req := &GetHttpReq{Url: url, Result: result, Params: params} + err := Get(cli, req) + if err != nil { + return nil, err + } + return result, nil +} + +// EditCoreVolVer - edit core version +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the volume name +// - *EditCoreVolVerReq: the request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func EditCoreVolVer(cli bce.Client, name string, + ecvr *EditCoreVolVerReq) error { + url := PREFIX_V3VOL + "/" + name + "/core" + + result := &ListVolCoreResult{} + req := &PostHttpReq{Url: url, Result: result, Body: ecvr} + err := Put(cli, req) + if err != nil { + return err + } + return nil +} + +// ImportCfc - import a CFC function into volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the volume name +// - *ImportCfcReq: the request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func ImportCfc(cli bce.Client, name string, + icr *ImportCfcReq) error { + url := PREFIX_V3VOL + "/" + name + "/cfc" + req := &PostHttpReq{Url: url, Body: icr} + err := Post(cli, req) + if err != nil { + return err + } + return nil +} + +// ImportBos - import a BOS file into volume +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: the volume name +// - *ImportBosReq: the request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func ImportBos(cli bce.Client, name string, + ibr *ImportBosReq) error { + url := PREFIX_V3VOL + "/" + name + "/bos" + req := &PostHttpReq{Url: url, Body: ibr} + err := Post(cli, req) + if err != nil { + return err + } + return nil +} diff --git a/bce-sdk-go/services/bie/client.go b/bce-sdk-go/services/bie/client.go new file mode 100644 index 0000000..8124790 --- /dev/null +++ b/bce-sdk-go/services/bie/client.go @@ -0,0 +1,628 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BIE service + +// Package bie defines the bie services of BCE. The supported APIs are all defined in sub-package +package bie + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bie/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "iotedge." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN +) + +// Client of BIE(iot edge) service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the BIE service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +////////////////////////////////////////////// +// group API +////////////////////////////////////////////// + +// ListGroup - list all groups +// +// - *ListGroupReq: page no, page size, and name +// +// RETURNS: +// - *api.ListGroupResult: the all groups +// - error: the return error if any occurs +func (c *Client) ListGroup(lgr *api.ListGroupReq) (*api.ListGroupResult, error) { + return api.ListGroup(c, lgr) +} + +// GetGroup - get a group +// +// RETURNS: +// - *api.Group: the group +// - error: the return error if any occurs +func (c *Client) GetGroup(groupUuid string) (*api.Group, error) { + return api.GetGroup(c, groupUuid) +} + +// CreateGroup - create a group +// +// PARAMS: +// - cgr: parameters to create group +// +// RETURNS: +// - *CreateGroupResult: the result group +// - error: nil if ok otherwise the specific error +func (c *Client) CreateGroup(cgr *api.CreateGroupReq) (*api.CreateGroupResult, error) { + return api.CreateGroup(c, cgr) +} + +// EditGroup - edit a group +// +// PARAMS: +// - groupId: the group to edit +// - egr: parameters to update group +// +// RETURNS: +// - *Group: the result group +// - error: nil if ok otherwise the specific error +func (c *Client) EditGroup(groupid string, egr *api.EditGroupReq) (*api.Group, error) { + return api.EditGroup(c, groupid, egr) +} + +// DeleteGroup - delete a group of the account +// +// PARAMS: +// - groupUuid: id of the group +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteGroup(groupUuid string) error { + return api.DeleteGroup(c, groupUuid) +} + +////////////////////////////////////////////// +// core API +////////////////////////////////////////////// + +// ListCore - list all core of a group +// +// PARAMS: +// - groupUuid: id of the group +// +// RETURNS: +// - *ListCoreResult: the result core list +// - error: nil if ok otherwise the specific error +func (c *Client) ListCore(groupUuid string) (*api.ListCoreResult, error) { + return api.ListCore(c, groupUuid) +} + +// GetCore - get a core of a group +// +// PARAMS: +// - groupUuid: id of the group +// - coreid: id of the core +// +// RETURNS: +// - *CoreResult: the result core +// - error: nil if ok otherwise the specific error +func (c *Client) GetCore(groupUuid string, coreid string) (*api.CoreResult, error) { + return api.GetCore(c, groupUuid, coreid) +} + +// RenewCoreAuth - renew the auth of a core +// +// PARAMS: +// - coreid: id of the core +// +// RETURNS: +// - *CoreInfo: the result core info +// - error: nil if ok otherwise the specific error +func (c *Client) RenewCoreAuth(coreid string) (*api.CoreInfo, error) { + return api.RenewCoreAuth(c, coreid) +} + +// GetCoreStatus - get the status of a core +// +// PARAMS: +// - coreid: id of the core +// +// RETURNS: +// - *CoreStatus: the status of the core +// - error: nil if ok otherwise the specific error +func (c *Client) GetCoreStatus(coreid string) (*api.CoreStatus, error) { + return api.GetCoreStatus(c, coreid) +} + +////////////////////////////////////////////// +// Config API +////////////////////////////////////////////// + +// ListConfig - list all configs +// +// PARAMS: +// - coreid: id of the core +// +// RETURNS: +// - *ListConfigResult: the result config list +// - error: nil if ok otherwise the specific error +func (c *Client) ListConfig(coreid string, + lcr *api.ListConfigReq) (*api.ListConfigResult, error) { + return api.ListConfig(c, coreid, lcr) +} + +// GetConfig - get a config +// +// PARAMS: +// - coreid: id of the core +// - ver: version, e.g:$LATEST +// +// RETURNS: +// - *CfgResult: the result config +// - error: nil if ok otherwise the specific error +func (c *Client) GetConfig(coreid string, ver string) (*api.CfgResult, error) { + return api.GetConfig(c, coreid, ver) +} + +// PubConfig - pub a config +// +// PARAMS: +// - cpr: id of the core and version +// +// RETURNS: +// - *CfgResult: the pub result +// - error: nil if ok otherwise the specific error +func (c *Client) PubConfig(cpr *api.CoreidVersion, cpb *api.CfgPubBody) (*api.CfgResult, error) { + return api.PubConfig(c, cpr, cpb) +} + +// DeployConfig - deploy a config +// +// PARAMS: +// - coreid: id of the core +// - ver: version, e.g:$LATEST +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeployConfig(coreid string, ver string) error { + return api.DeployConfig(c, coreid, ver) +} + +// DownloadConfig - download a config +// +// PARAMS: +// - *CfgDownloadReq: id, version, with bin or not +// +// RETURNS: +// - *CfgDownloadResult: the result +// - error: nil if ok otherwise the specific error +func (c *Client) DownloadConfig(cdr *api.CfgDownloadReq) (*api.CfgDownloadResult, error) { + return api.DownloadConfig(c, cdr) +} + +////////////////////////////////////////////// +// Service API +////////////////////////////////////////////// + +// CreateService - create a service +// +// PARAMS: +// - *CoreidVersion: coreid, version +// - *CreateServiceReq: request parameters +// +// RETURNS: +// - *ServiceResult: the result +// - error: nil if ok otherwise the specific error +func (c *Client) CreateService(cv *api.CoreidVersion, + sr *api.CreateServiceReq) (*api.ServiceResult, error) { + return api.CreateService(c, cv, sr) +} + +// GetService - get a service +// +// PARAMS: +// - *IdVerName: coreid, version and name +// +// RETURNS: +// - *ServiceResult: the result +// - error: nil if ok otherwise the specific error +func (c *Client) GetService(ivn *api.IdVerName) (*api.ServiceResult, error) { + return api.GetService(c, ivn) +} + +// EditService - edit a service +// +// PARAMS: +// - *IdVerName: coreid, version, and name +// +// RETURNS: +// - *ServiceResult: the result +// - error: nil if ok otherwise the specific error +func (c *Client) EditService(ivn *api.IdVerName, + esr *api.EditServiceReq) (*api.ServiceResult, error) { + return api.EditService(c, ivn, esr) +} + +// DeleteService - delete a service +// +// PARAMS: +// - *IdVerName: coreid, version, and name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteService(ivn *api.IdVerName) error { + return api.DeleteService(c, ivn) +} + +// ReorderService - reorder service after an other service +// +// PARAMS: +// - *IdVerName: coreid, version, and name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) ReorderService(ivn *api.IdVerName, after string) error { + return api.ReorderService(c, ivn, after) +} + +// VolumeOp - attache of detach volumes +// +// PARAMS: +// - *CoreidVersion: coreid, version +// - *VolumeOpReq: request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) VolumeOp(cv *api.CoreidVersion, vor *api.VolumeOpReq) error { + return api.VolumeOp(c, cv, vor) +} + +// //////////////////////////////////////////// +// Volume API +// //////////////////////////////////////////// +// ListVolumeTpl - list all volume template +// +// PARAMS: +// RETURNS: +// - *ListVolTemplate: the result volume template list +// - error: nil if ok otherwise the specific error +func (c *Client) ListVolumeTpl() (*api.ListVolTemplate, error) { + return api.ListVolumeTpl(c) +} + +// CreateVolume - create a volume +// +// PARAMS: +// - CreateVolReq: the request parameters +// +// RETURNS: +// - *VolumeResult: the result volume +// - error: nil if ok otherwise the specific error +func (c *Client) CreateVolume(cvr *api.CreateVolReq) (*api.VolumeResult, error) { + return api.CreateVolume(c, cvr) +} + +// ListVolume - list a bunch of volumes +// +// PARAMS: +// - ListVolReq: the request parameters +// +// RETURNS: +// - *ListVolumeResult: the result list +// - error: nil if ok otherwise the specific error +func (c *Client) ListVolume(lvr *api.ListVolumeReq) (*api.ListVolumeResult, error) { + return api.ListVolume(c, lvr) +} + +// GetVolume - get a volume +// +// PARAMS: +// - name: the requested volume name +// +// RETURNS: +// - *VolumeResult: the result vaolume +// - error: nil if ok otherwise the specific error +func (c *Client) GetVolume(name string) (*api.VolumeResult, error) { + return api.GetVolume(c, name) +} + +// EditVolume - edit a volume +// +// PARAMS: +// - name: the requested volume name +// - *EditVolumeReq: request parameters +// +// RETURNS: +// - *VolumeResult: the result vaolume +// - error: nil if ok otherwise the specific error +func (c *Client) EditVolume(name string, evr *api.EditVolumeReq) (*api.VolumeResult, error) { + return api.EditVolume(c, name, evr) +} + +// DeleteVolume - delete a volume +// +// PARAMS: +// - name: the requested volume name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVolume(name string) error { + return api.DeleteVolume(c, name) +} + +// ListVolumeVer - list version list of a volume +// +// PARAMS: +// - NameVersion: the request parameters, version can be empty +// +// RETURNS: +// - *ListVolumeVerResult: the result list +// - error: nil if ok otherwise the specific error +func (c *Client) ListVolumeVer(nv *api.NameVersion) (*api.ListVolumeVerResult, error) { + return api.ListVolumeVer(c, nv) +} + +// PubVolumeVer - pub version list of a volume +// +// PARAMS: +// - name: the request volume name +// +// RETURNS: +// - *VolumeResult: the result volume +// - error: nil if ok otherwise the specific error +func (c *Client) PubVolumeVer(name string) (*api.VolumeResult, error) { + return api.PubVolumeVer(c, name) +} + +// DownloadVolVer - get the download address of a specific version of volume +// +// PARAMS: +// - name: the request volume name +// - version: the request volume version +// +// RETURNS: +// - *VolDownloadResult: the result +// - error: nil if ok otherwise the specific error +func (c *Client) DownloadVolVer(name string, + version string) (*api.VolDownloadResult, error) { + return api.DownloadVolVer(c, name, version) +} + +// CreateVolFile - create a volume file +// +// PARAMS: +// - name: the request volume name +// - *CreateVolFileReq: request parameters +// +// RETURNS: +// - *CreateVolFileReq: the result +// - error: nil if ok otherwise the specific error +func (c *Client) CreateVolFile(name string, + cvf *api.CreateVolFileReq) (*api.CreateVolFileReq, error) { + return api.CreateVolFile(c, name, cvf) +} + +// GetVolumeFile - get a volume file +// +// PARAMS: +// - GetVolFileReq: volume name, version anf filename +// +// RETURNS: +// - *ListVolumeVerResult: the result list +// - error: nil if ok otherwise the specific error +func (c *Client) GetVolumeFile(cvfr *api.GetVolFileReq) (*api.CreateVolFileReq, error) { + return api.GetVolumeFile(c, cvfr) +} + +// EditVolumeFile - edit a volume file +// +// PARAMS: +// - *Name2: the requested volume name and file name +// - *EditVolFileReq: the content, the request body +// +// RETURNS: +// - *CreateVolFileReq: the result +// - error: nil if ok otherwise the specific error +func (c *Client) EditVolumeFile(names *api.Name2, + body *api.EditVolFileReq) (*api.CreateVolFileReq, error) { + return api.EditVolumeFile(c, names, body) +} + +// DeleteVolFile - delete a volume file +// +// PARAMS: +// - name: the requested volume name +// - filename: the requested volume filename +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteVolFile(name string, filename string) error { + return api.DeleteVolFile(c, name, filename) +} + +// ClearVolFile - clear all volume files +// +// PARAMS: +// - name: the requested volume name +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) ClearVolFile(name string) error { + return api.ClearVolFile(c, name) +} + +// ListVolCore - list the cores associated with the volume +// +// PARAMS: +// - *ListVolCoreReq: the request parameters +// +// RETURNS: +// - *ListVolumeVerResult: the result list +// - error: nil if ok otherwise the specific error +func (c *Client) ListVolCore(lvcr *api.ListVolCoreReq) (*api.ListVolCoreResult, error) { + return api.ListVolCore(c, lvcr) +} + +// EditCoreVolVer - edit the core version +// +// PARAMS: +// - name: the volume name +// - *EditCoreVolVerReq: the request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) EditCoreVolVer(name string, + ecvr *api.EditCoreVolVerReq) error { + return api.EditCoreVolVer(c, name, ecvr) +} + +// ImportCfc - import a CFC function into volume +// +// PARAMS: +// - name: the volume name +// - *ImportCfcReq: the request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) ImportCfc(name string, + icr *api.ImportCfcReq) error { + return api.ImportCfc(c, name, icr) +} + +// ImportBos - import a BOS file into volume +// +// PARAMS: +// - name: the volume name +// - *ImportBosReq: the request parameters +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) ImportBos(name string, + ibr *api.ImportBosReq) error { + return api.ImportBos(c, name, ibr) +} + +// //////////////////////////////////////////// +// Volume API +// //////////////////////////////////////////// +// ListImageSys - list all system docker images +// +// PARAMS: +// - ListImageReq: list request parameters +// +// RETURNS: +// - *ListImageResult: the result iamge list +// - error: nil if ok otherwise the specific error +func (c *Client) ListImageSys(lir *api.ListImageReq) (*api.ListImageResult, error) { + return api.ListImageSys(c, lir) +} + +// GetImageSys - get a system docker images +// +// PARAMS: +// - uuid: the image uuid +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func (c *Client) GetImageSys(uuid string) (*api.Image, error) { + return api.GetImageSys(c, uuid) +} + +// ListImageUser - list all user docker images +// +// PARAMS: +// - ListImageReq: list request parameters +// +// RETURNS: +// - *ListImageResult: the result iamge list +// - error: nil if ok otherwise the specific error +func (c *Client) ListImageUser(lir *api.ListImageReq) (*api.ListImageResult, error) { + return api.ListImageUser(c, lir) +} + +// GetImageUser - get a user docker image +// +// PARAMS: +// - uuid: the image uuid +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func (c *Client) GetImageUser(uuid string) (*api.Image, error) { + return api.GetImageUser(c, uuid) +} + +// CreateImageUser - create a user docker image +// +// PARAMS: +// - CreateImageReq: request parameters, name, image url, description +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func (c *Client) CreateImageUser(cir *api.CreateImageReq) (*api.Image, error) { + return api.CreateImageUser(c, cir) +} + +// EditImageUser - edit a user docker image information +// +// PARAMS: +// - uuid: the image uuid +// - EditImageReq: request parameter: description +// +// RETURNS: +// - *Image: the result iamge +// - error: nil if ok otherwise the specific error +func (c *Client) EditImageUser(uuid string, eir *api.EditImageReq) (*api.Image, error) { + return api.EditImageUser(c, uuid, eir) +} + +// DeleteImageUser - delete a user docker image +// +// PARAMS: +// - uuid: the image uuid +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteImageUser(uuid string) error { + return api.DeleteImageUser(c, uuid) +} diff --git a/bce-sdk-go/services/bie/client_test.go b/bce-sdk-go/services/bie/client_test.go new file mode 100644 index 0000000..ddd5703 --- /dev/null +++ b/bce-sdk-go/services/bie/client_test.go @@ -0,0 +1,608 @@ +package bie + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/services/bie/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var CLIENT *Client + +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + fmt.Printf("init \n") + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 6; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +////////////////////////////////////////////// +// group API +////////////////////////////////////////////// + +func TestListGroup(t *testing.T) { + listReq := &api.ListGroupReq{PageNo: 1, PageSize: 1000} + res, err := CLIENT.ListGroup(listReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) +} + +func TestGroupCRUD(t *testing.T) { + // 1, list group first + listReq := &api.ListGroupReq{PageNo: 1, PageSize: 1000} + groups, err := CLIENT.ListGroup(listReq) + ExpectEqual(t.Errorf, nil, err) + + name := "TestGroupCRUD" + deleted := 0 + + // delete core with the same name + for _, g := range groups.Result { + if g.Name == name { + CLIENT.DeleteGroup(g.GroupUuid) + deleted = 1 + break + } + } + + // 2, create a new group + createReq := &api.CreateGroupReq{ + Name: name, + Description: "descr", + AuthType: "CERT", + Platform: "Linux-amd64", + } + + createdGroup, err := CLIENT.CreateGroup(createReq) + ExpectEqual(t.Errorf, nil, err) + + groups2, err := CLIENT.ListGroup(listReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, groups2.TotalCount, groups.TotalCount+1) + + // 3, edit group + newName := name + "new" + newDesc := "descrnew" + editReq := &api.EditGroupReq{ + Name: newName, + Description: newDesc, + } + + newGroup, err := CLIENT.EditGroup(createdGroup.GroupInfo.GroupUuid, editReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, newGroup.Name, newName) + ExpectEqual(t.Errorf, newGroup.Description, newDesc) + + // 4, delete group + err = CLIENT.DeleteGroup(newGroup.GroupUuid) + ExpectEqual(t.Errorf, nil, err) + + // 5, list again + groups2, _ = CLIENT.ListGroup(listReq) + ExpectEqual(t.Errorf, groups2.TotalCount, groups.TotalCount-deleted) + +} + +func createNewGroup(cli *Client, name string) (*api.CreateGroupResult, error) { + listReq := &api.ListGroupReq{PageNo: 1, PageSize: 1000} + // 1, list group first + groups, err := cli.ListGroup(listReq) + if err != nil { + return nil, err + } + + // delete core with the same name + for _, g := range groups.Result { + if g.Name == name { + CLIENT.DeleteGroup(g.GroupUuid) + break + } + } + + // 2, create a new group + createReq := &api.CreateGroupReq{ + Name: name, + Description: "descr", + AuthType: "CERT", + Platform: "Linux-amd64", + } + + return cli.CreateGroup(createReq) +} + +// //////////////////////////////////////////// +// core API +// //////////////////////////////////////////// +func TestCoreQuery(t *testing.T) { + name := "TestCoreQuery" + createdGroup, err := createNewGroup(CLIENT, name) + ExpectEqual(t.Errorf, nil, err) + + // 3, list the core + cores, err := CLIENT.ListCore(createdGroup.GroupInfo.GroupUuid) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, len(cores.Result), 1) + + // 4, get the core + core, err := CLIENT.GetCore(createdGroup.GroupInfo.GroupUuid, cores.Result[0].DeviceUuid) + ExpectEqual(t.Errorf, nil, err) + + // 5, renew core auth + _, err = CLIENT.RenewCoreAuth(core.DeviceUuid) + ExpectEqual(t.Errorf, nil, err) + + // 6, get online status + status, err := CLIENT.GetCoreStatus(core.DeviceUuid) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, status.IsCoreOnline, false) + + // 7, delete group + CLIENT.DeleteGroup(createdGroup.GroupInfo.GroupUuid) +} + +// //////////////////////////////////////////// +// Config API +// //////////////////////////////////////////// +func TestConfigCrudAndOp(t *testing.T) { + // 1, create a group and core + name := "TestConfigCrudAndOp" + newGroup, err := createNewGroup(CLIENT, name) + ExpectEqual(t.Errorf, nil, err) + + // 2, create a config + text := []byte(`{ + "moduleUuid": "b1f91fbe6fe54d2eaf70ef0025f1c3c2", + "moduleCategory": "SYSTEM", + "name": "first016", + "description": "test", + "replica": 1, + "mounts1": [ + {"name": "open-hub-001", "version": "LATEST", "readonly": false, "target": "/etc/avr"} + ], + "ports": ["100:101", "8000:8080"], + "args": ["abc", "-v", "1.1.1"], + "env": { + "name": "wangxiaochen", + "pwd": "abcabc" + }, + "restart": { + "retry": { + "max": 1 + }, + "policy": "always", + "backoff": { + "min": "10m", + "max": "10m", + "factor": 12 + } + }, + "resources": { + "cpu": { + "cpus": 2, + "setcpus": "2" + }, + "pids": { + "limit": 20 + }, + "memory": { + "limit": "10m", + "swap": "20m" + } + }, + "devs": ["/dev/01:/dev/02", "/dev/cat1:/dev/tom1"] + }`) + + var req api.CreateServiceReq + err = json.Unmarshal(text, &req) + ExpectEqual(t.Errorf, nil, err) + + idver := &api.CoreidVersion{Coreid: newGroup.CoreInfo.DeviceUuid, Version: "LATEST"} + newConf, err := CLIENT.CreateService(idver, &req) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, newConf.Name, "first016") + + // 3, list config + listReq := &api.ListConfigReq{} + confList, err := CLIENT.ListConfig(idver.Coreid, listReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, confList.TotalCount, 2) + // 4, get config + confGot, err := CLIENT.GetConfig(idver.Coreid, idver.Version) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, confGot.ConfigServices[0].ModuleCategory, "SYSTEM") + + // 5, pub config + pubRet, err := CLIENT.PubConfig(idver, &api.CfgPubBody{Description: "test"}) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, pubRet.Status, "DONE") + + // 6, download url + _, err = CLIENT.DownloadConfig(&api.CfgDownloadReq{ + Coreid: idver.Coreid, Version: pubRet.Version, WithBin: true}) + ExpectEqual(t.Errorf, nil, err) + + // 7, deploy + err = CLIENT.DeployConfig(idver.Coreid, pubRet.Version) + ExpectEqual(t.Errorf, false, err == nil) +} + +// //////////////////////////////////////////// +// Volume API +// //////////////////////////////////////////// +func TestVolumeCrudAndOp(t *testing.T) { + // 0, list volume template + templates, err := CLIENT.ListVolumeTpl() + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(templates.Result) > 0) + + // 1, create volume + name := "TestVolumeCrudAndOp" + hostPath := "/var/local" + createReq := &api.CreateVolReq{ + Name: name, + Tags: []string{"tag1", "tag2"}, + TemplateCode: templates.Result[0].Code, + HostPath: hostPath, + Description: "desc", + } + createRet, err := CLIENT.CreateVolume(createReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, name, createRet.Name) + ExpectEqual(t.Errorf, templates.Result[0].Code, createRet.Template.Code) + + // 2, get volume + volumeGot, err := CLIENT.GetVolume(name) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, name, volumeGot.Name) + ExpectEqual(t.Errorf, templates.Result[0].Code, volumeGot.Template.Code) + + // 3, list volume + list, err := CLIENT.ListVolume(&api.ListVolumeReq{}) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, list.TotalCount > 0) + + // 4, update + newDesc := "new description" + newTags := []string{"tag3", "tag4", "tag5", "tag6"} + newHostpath := hostPath + "/new" + updateReq := &api.EditVolumeReq{ + Tags: newTags, Description: newDesc, HostPath: newHostpath} + updateRet, err := CLIENT.EditVolume(name, updateReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, newDesc, updateRet.Description) + ExpectEqual(t.Errorf, true, len(updateRet.Tags) >= 4) + + // 5, query version list + verListRet, err := CLIENT.ListVolumeVer(&api.NameVersion{Name: name, Version: updateRet.Version}) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(verListRet.Result) > 0) + + // 6, publish new version + pubRet, err := CLIENT.PubVolumeVer(name) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, false, pubRet.Version == updateRet.Version) + verListRet2, err := CLIENT.ListVolumeVer(&api.NameVersion{Name: name}) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(verListRet2.Result) > 1) + + // 7, download url + downRet, err := CLIENT.DownloadVolVer(name, pubRet.Version) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(downRet.Url) > 0) + + // 8, delete + err = CLIENT.DeleteVolume(name) + ExpectEqual(t.Errorf, nil, err) +} + +func TestVolumeFileCrud(t *testing.T) { + // 0, list volume template + templates, err := CLIENT.ListVolumeTpl() + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(templates.Result) > 0) + t.Logf("%+v", templates.Result[0]) + + var tmplate api.VolTemplate + for _, t := range templates.Result { + if t.Code == "CUSTOMIZE" { + tmplate = t + } + } + + // 1, create volume + + // 1.1 delete old volume + name := "TestVolumeFileCrud" + listVol, err := CLIENT.ListVolume(&api.ListVolumeReq{}) + for _, v := range listVol.Result { + if v.Name == name { + CLIENT.DeleteVolume(name) + } + } + + hostPath := "/var/local" + createReq := &api.CreateVolReq{ + Name: name, + Tags: []string{"tag1", "tag2"}, + TemplateCode: tmplate.Code, + HostPath: hostPath, + Description: "desc", + } + createVolRet, err := CLIENT.CreateVolume(createReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", createVolRet) + + // 2, add file + filename := "file1" + content := "{\"a\":1}" + createFileReq := &api.CreateVolFileReq{ + FileName: filename, + Content: content, + } + createFileRet, err := CLIENT.CreateVolFile(name, createFileReq) + t.Logf("%+v", createFileRet) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, filename, createFileRet.FileName) + ExpectEqual(t.Errorf, content, createFileRet.Content) + + // 3, get file + getFileReq := &api.GetVolFileReq{ + Name: name, + FileName: filename, + Version: createVolRet.Version, + } + getFileRet, err := CLIENT.GetVolumeFile(getFileReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, filename, getFileRet.FileName) + ExpectEqual(t.Errorf, content, getFileRet.Content) + + // 4, update file + newContent := content + "new" + editReq := &api.EditVolFileReq{Content: newContent} + editRet, err := CLIENT.EditVolumeFile(&api.Name2{Name: name, FileName: filename}, editReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, filename, editRet.FileName) + ExpectEqual(t.Errorf, newContent, editRet.Content) + + // 5, get file + getFileRet, err = CLIENT.GetVolumeFile(getFileReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, filename, getFileRet.FileName) + ExpectEqual(t.Errorf, newContent, getFileRet.Content) + + // 6, delete file + err = CLIENT.DeleteVolFile(name, filename) + ExpectEqual(t.Errorf, nil, err) + + // 7, delete volume + CLIENT.DeleteVolume(name) +} + +func TestVolumeMisc(t *testing.T) { + // 0, list volume template + templates, err := CLIENT.ListVolumeTpl() + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(templates.Result) > 0) + + var tmplate api.VolTemplate + for _, tmp := range templates.Result { + if tmp.Code == "CFC" { + tmplate = tmp + break + } + } + + // 1, create volume + + // 1.1 delete old volume + name := "TestVolumeMisc" + listVol, err := CLIENT.ListVolume(&api.ListVolumeReq{}) + for _, v := range listVol.Result { + if v.Name == name { + CLIENT.DeleteVolume(name) + } + } + + hostPath := "/var/local" + createReq := &api.CreateVolReq{ + Name: name, + Tags: []string{"tag1", "tag2"}, + TemplateCode: tmplate.Code, + HostPath: hostPath, + Description: "desc", + } + createVolRet, err := CLIENT.CreateVolume(createReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", createVolRet) + + // 2, import cfc + importCfcReq := &api.ImportCfcReq{ + Name: "non-exist-name", + Version: "1", + } + + err = CLIENT.ImportCfc(name, importCfcReq) + ExpectEqual(t.Errorf, true, err != nil) + fmt.Println(err) + + // 3, get core info + listCoreReq := &api.ListVolCoreReq{ + Name: name, + } + listCoreRet, err := CLIENT.ListVolCore(listCoreReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 0, listCoreRet.TotalCount) + + // 4, publish a new version and update core col version + // publish colume version + pubRet, err := CLIENT.PubVolumeVer(name) + ExpectEqual(t.Errorf, nil, err) + + entry := api.EditCoreVolVerEntry{ + DeviceUUID: "", + OldVersion: "V2", + NewVersion: pubRet.Version, + } + editCoreVerReq := &api.EditCoreVolVerReq{ + Jobs: []api.EditCoreVolVerEntry{entry}, + } + + err = CLIENT.EditCoreVolVer(name, editCoreVerReq) + ExpectEqual(t.Errorf, true, err != nil) + + // 5, delete volume + CLIENT.DeleteVolume(name) +} + +func TestVolumeImportBos(t *testing.T) { + // 0, list volume template + templates, err := CLIENT.ListVolumeTpl() + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(templates.Result) > 0) + + var tmplate api.VolTemplate + for _, tmp := range templates.Result { + if tmp.Code == "BOS" { + tmplate = tmp + break + } + } + + // 1, create volume + + // 1.1 delete old volume + name := "TestVolumeImportBos" + listVol, err := CLIENT.ListVolume(&api.ListVolumeReq{}) + for _, v := range listVol.Result { + if v.Name == name { + CLIENT.DeleteVolume(name) + } + } + + hostPath := "/var/local" + createReq := &api.CreateVolReq{ + Name: name, + Tags: []string{"tag1", "tag2"}, + TemplateCode: tmplate.Code, + HostPath: hostPath, + Description: "desc", + } + createVolRet, err := CLIENT.CreateVolume(createReq) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", createVolRet) + + // 2, import cfc + importBosReq := &api.ImportBosReq{ + BosBucket: "non-exist-bucket", + BosKey: "non-exist-key", + } + + err = CLIENT.ImportBos(name, importBosReq) + ExpectEqual(t.Errorf, true, err != nil) + fmt.Println(err) + + // 3, delete volume + CLIENT.DeleteVolume(name) +} + +func TestDockerImages(t *testing.T) { + listReq := &api.ListImageReq{PageNo: 1, PageSize: 1000} + list, err := CLIENT.ListImageSys(listReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, list.TotalCount >= 0) + _, err = CLIENT.GetImageSys("notexistimageid") + ExpectEqual(t.Errorf, true, err != nil) + resultSize := listReq.PageSize + if resultSize > list.TotalCount { + resultSize = list.TotalCount + } + ExpectEqual(t.Errorf, resultSize, len(list.Result)) + + list, err = CLIENT.ListImageUser(listReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, list.TotalCount >= 0) + cnt1 := list.TotalCount + _, err = CLIENT.GetImageUser("notexistimageid") + ExpectEqual(t.Errorf, true, err != nil) + + name := "TestDockerImages" + // 0, delete user iamge left by previous test + for _, m := range list.Result { + if name == m.Name { + CLIENT.DeleteImageUser(m.UUID) + } + } + + // 1, create a new user image + url := "hub.c.163.com/library/nginx:latest" + desc := "desc" + createReq := &api.CreateImageReq{Name: name, Description: desc, Image: url} + img, err := CLIENT.CreateImageUser(createReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, name, img.Name) + ExpectEqual(t.Errorf, desc, img.Description) + ExpectEqual(t.Errorf, url, img.Image) + + // 2, list user image again, and compare the totalCount + list, err = CLIENT.ListImageUser(listReq) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, cnt1+1, list.TotalCount) + + // 2, delete the create image + err = CLIENT.DeleteImageUser(img.UUID) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/blb/backendserver.go b/bce-sdk-go/services/blb/backendserver.go new file mode 100644 index 0000000..5b08279 --- /dev/null +++ b/bce-sdk-go/services/blb/backendserver.go @@ -0,0 +1,166 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// backendserver.go - the backendserver APIs definition supported by the BLB service + +package blb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// AddBackendServers - add backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to add backend servers +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) AddBackendServers(blbId string, args *AddBackendServersArgs) error { + + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.BackendServerList) == 0 { + return fmt.Errorf("unset backendServer list") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getBackendServerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateBackendServers - update backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update backend servers +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateBackendServers(blbId string, args *UpdateBackendServersArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.BackendServerList) == 0 { + return fmt.Errorf("unset backendServer list") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBackendServerUri(blbId)). + WithQueryParam("update", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeBackendServers - describe all backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all backend servers +// +// RETURNS: +// - *DescribeBackendServersResult: the result of describe all backend servers +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeBackendServers(blbId string, args *DescribeBackendServersArgs) (*DescribeBackendServersResult, error) { + if args == nil { + args = &DescribeBackendServersArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeBackendServersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBackendServerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + err := request.Do() + return result, err +} + +// DescribeHealthStatus - describe all backend servers health status +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all backend servers health status +// +// RETURNS: +// - *DescribeHealthStatusResult: the result of describe all backend servers health status +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeHealthStatus(blbId string, args *DescribeHealthStatusArgs) (*DescribeHealthStatusResult, error) { + if args == nil { + args = &DescribeHealthStatusArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeHealthStatusResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBackendServerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// RemoveBackendServers - remove backend servers +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to remove backend servers, a backend server list +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) RemoveBackendServers(blbId string, args *RemoveBackendServersArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.BackendServerList) == 0 { + return fmt.Errorf("unset backend server list") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBackendServerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/blb/blb.go b/bce-sdk-go/services/blb/blb.go new file mode 100644 index 0000000..e26ea56 --- /dev/null +++ b/bce-sdk-go/services/blb/blb.go @@ -0,0 +1,222 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// blb.go - the Normal BLB APIs definition supported by the BLB service + +package blb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateLoadBalancer - create a LoadBalancer +// +// PARAMS: +// - args: parameters to create LoadBalancer +// +// RETURNS: +// - *CreateLoadBalancerResult: the result of create LoadBalancer, contains new LoadBalancer's ID +// - error: nil if ok otherwise the specific error +func (c *Client) CreateLoadBalancer(args *CreateLoadBalancerArgs) (*CreateLoadBalancerResult, error) { + if args == nil || len(args.SubnetId) == 0 { + return nil, fmt.Errorf("unset subnet id") + } + + if len(args.VpcId) == 0 { + return nil, fmt.Errorf("unset vpc id") + } + + result := &CreateLoadBalancerResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getBlbUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateLoadBalancer - update a LoadBalancer +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update LoadBalancer +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateLoadBalancer(blbId string, args *UpdateLoadBalancerArgs) error { + if args == nil { + args = &UpdateLoadBalancerArgs{} + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBlbUriWithId(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeLoadBalancers - describe all LoadBalancers +// +// PARAMS: +// - args: parameters to describe all LoadBalancers +// +// RETURNS: +// - *DescribeLoadBalancersResult: the result all LoadBalancers's detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeLoadBalancers(args *DescribeLoadBalancersArgs) (*DescribeLoadBalancersResult, error) { + if args == nil { + args = &DescribeLoadBalancersArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeLoadBalancersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbUri()). + WithQueryParamFilter("address", args.Address). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("blbId", args.BlbId). + WithQueryParamFilter("bccId", args.BccId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParamFilter("type", args.Type). + WithResult(result) + + if args.ExactlyMatch { + request.WithQueryParam("exactlyMatch", "true") + } + + err := request.Do() + return result, err +} + +// DescribeLoadBalancerDetail - describe a LoadBalancer +// +// PARAMS: +// - blbId: describe LoadBalancer's ID +// +// RETURNS: +// - *DescribeLoadBalancerDetailResult: the result LoadBalancer detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeLoadBalancerDetail(blbId string) (*DescribeLoadBalancerDetailResult, error) { + result := &DescribeLoadBalancerDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbUriWithId(blbId)). + WithResult(result). + Do() + + return result, err +} + +// DeleteLoadBalancer - delete a LoadBalancer +// +// PARAMS: +// - blbId: parameters to delete LoadBalancer +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteLoadBalancer(blbId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getBlbUriWithId(blbId)). + Do() +} + +// DescribeLbClusterDetail - describe a LoadBalancer cluster +// +// PARAMS: +// - clusterId: describe LoadBalancer cluster's ID +// +// RETURNS: +// - *DescribeLbClusterDetailResult: the result LoadBalancer cluster detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeLbClusterDetail(clusterId string) (*DescribeLbClusterDetailResult, error) { + result := &DescribeLbClusterDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbClusterUriWithId(clusterId)). + WithResult(result). + Do() + + return result, err +} + +// DescribeLbClusters - describe all LoadBalancerClusters +// +// PARAMS: +// - args: parameters to describe all LoadBalancerClusters +// +// RETURNS: +// - *DescribeLbClustersResult: the result all LoadBalancerClusters's detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeLbClusters(args *DescribeLbClustersArgs) (*DescribeLbClustersResult, error) { + if args == nil { + args = &DescribeLbClustersArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeLbClustersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getBlbClusterUri()). + WithQueryParamFilter("clusterName", args.ClusterName). + WithQueryParamFilter("clusterId", args.ClusterId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ExactlyMatch { + request.WithQueryParam("exactlyMatch", "true") + } + + err := request.Do() + + return result, err +} + +// UpdateLoadBalancerAcl - update the specified LoadBalancer to support the acl feature +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update LoadBalancer acl +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateLoadBalancerAcl(blbId string, args *UpdateLoadBalancerAclArgs) error { + if args == nil || args.SupportAcl == nil { + args = &UpdateLoadBalancerAclArgs{} + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBlbAclUriWithId(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/blb/client.go b/bce-sdk-go/services/blb/client.go new file mode 100644 index 0000000..8d84413 --- /dev/null +++ b/bce-sdk-go/services/blb/client.go @@ -0,0 +1,111 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for Application LoadBalance service + +// Package blb defines the Normal BLB services of BCE. The supported APIs are all defined in sub-package +package blb + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + DEFAULT_SERVICE_DOMAIN = "blb." + bce.DEFAULT_REGION + ".baidubce.com" + URI_PREFIX = bce.URI_PREFIX + "v1" + REQUEST_BLB_URL = "/blb" + + LISTENER_URL = "/listener" + TCPLISTENER_URL = "/TCPlistener" + UDPLISTENER_URL = "/UDPlistener" + HTTPLISTENER_URL = "/HTTPlistener" + HTTPSLISTENER_URL = "/HTTPSlistener" + SSLLISTENER_URL = "/SSLlistener" + + BACKENDSERVER_URL = "/backendserver" + + REQUEST_BLB_CLUSTER_URL = "/blbcluster" + SECURITY_GROUP_URL = "/securitygroup" + ENTERPRISE_SECURITY_GROUP_URL = "/enterprise/securitygroup" +) + +// Client of APPBLB service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getBlbUri() string { + return URI_PREFIX + REQUEST_BLB_URL +} + +func getBlbUriWithId(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id +} + +func getBlbAclUriWithId(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/acl/" + id +} + +func getListenerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + LISTENER_URL +} + +func getTCPListenerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + TCPLISTENER_URL +} + +func getUDPListenerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + UDPLISTENER_URL +} + +func getHTTPListenerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + HTTPLISTENER_URL +} + +func getHTTPSListenerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + HTTPSLISTENER_URL +} + +func getSSLListenerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + SSLLISTENER_URL +} + +func getBackendServerUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + BACKENDSERVER_URL +} + +func getBlbClusterUri() string { + return URI_PREFIX + REQUEST_BLB_CLUSTER_URL +} + +func getBlbClusterUriWithId(id string) string { + return URI_PREFIX + REQUEST_BLB_CLUSTER_URL + "/" + id +} + +func getSecurityGroupUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + SECURITY_GROUP_URL +} + +func getEnterpriseSecurityGroupUri(id string) string { + return URI_PREFIX + REQUEST_BLB_URL + "/" + id + ENTERPRISE_SECURITY_GROUP_URL +} diff --git a/bce-sdk-go/services/blb/client_test.go b/bce-sdk-go/services/blb/client_test.go new file mode 100644 index 0000000..826f56f --- /dev/null +++ b/bce-sdk-go/services/blb/client_test.go @@ -0,0 +1,431 @@ +package blb + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BLB_CLIENT *Client + BLB_ID string + + // set these values before start test + VPC_TEST_ID = "" + SUBNET_TEST_ID = "" + INSTANCE_ID = "" + CERT_ID = "" + CLUSTER_ID = "" + CLUSTER_PROPERTY_TEST = "" + TEST_BLB_ID = "lb-36c64ec0" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + BLB_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateLoadBalancer(t *testing.T) { + createArgs := &CreateLoadBalancerArgs{ + ClientToken: getClientToken(), + Name: "sdkBlb", + VpcId: VPC_TEST_ID, + SubnetId: SUBNET_TEST_ID, + ClusterProperty: CLUSTER_PROPERTY_TEST, + } + + createResult, err := BLB_CLIENT.CreateLoadBalancer(createArgs) + ExpectEqual(t.Errorf, nil, err) + + BLB_ID = createResult.BlbId +} + +func TestClient_UpdateLoadBalancer(t *testing.T) { + updateArgs := &UpdateLoadBalancerArgs{ + Name: "testSdk", + Description: "test desc", + } + err := BLB_CLIENT.UpdateLoadBalancer(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeLoadBalancers(t *testing.T) { + describeArgs := &DescribeLoadBalancersArgs{} + res, err := BLB_CLIENT.DescribeLoadBalancers(describeArgs) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(time.Duration(1) * time.Second) +} + +func TestClient_DescribeLoadBalancerDetail(t *testing.T) { + res, err := BLB_CLIENT.DescribeLoadBalancerDetail(BLB_ID) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateTCPListener(t *testing.T) { + createArgs := &CreateTCPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 90, + BackendPort: 90, + Scheduler: "RoundRobin", + } + err := BLB_CLIENT.CreateTCPListener(BLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateTCPListener(t *testing.T) { + updateArgs := &UpdateTCPListenerArgs{ + ListenerPort: 90, + Scheduler: "Hash", + } + err := BLB_CLIENT.UpdateTCPListener(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeTCPListeners(t *testing.T) { + describeArgs := &DescribeListenerArgs{ + ListenerPort: 90, + } + _, err := BLB_CLIENT.DescribeTCPListeners(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateUDPListener(t *testing.T) { + createArgs := &CreateUDPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 91, + BackendPort: 91, + Scheduler: "RoundRobin", + HealthCheckString: "a", + } + err := BLB_CLIENT.CreateUDPListener(BLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateUDPListener(t *testing.T) { + updateArgs := &UpdateUDPListenerArgs{ + ListenerPort: 91, + Scheduler: "Hash", + } + err := BLB_CLIENT.UpdateUDPListener(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeUDPListeners(t *testing.T) { + describeArgs := &DescribeListenerArgs{ + ListenerPort: 91, + } + _, err := BLB_CLIENT.DescribeUDPListeners(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateHTTPListener(t *testing.T) { + createArgs := &CreateHTTPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 92, + BackendPort: 92, + Scheduler: "RoundRobin", + } + err := BLB_CLIENT.CreateHTTPListener(BLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateHTTPListener(t *testing.T) { + updateArgs := &UpdateHTTPListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 92, + Scheduler: "LeastConnection", + KeepSession: true, + } + err := BLB_CLIENT.UpdateHTTPListener(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeHTTPListeners(t *testing.T) { + describeArgs := &DescribeListenerArgs{ + ListenerPort: 92, + } + _, err := BLB_CLIENT.DescribeHTTPListeners(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateHTTPSListener(t *testing.T) { + createArgs := &CreateHTTPSListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 93, + BackendPort: 93, + Scheduler: "RoundRobin", + CertIds: []string{CERT_ID}, + } + err := BLB_CLIENT.CreateHTTPSListener(BLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateHTTPSListener(t *testing.T) { + updateArgs := &UpdateHTTPSListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 93, + Scheduler: "LeastConnection", + KeepSession: true, + CertIds: []string{CERT_ID}, + } + err := BLB_CLIENT.UpdateHTTPSListener(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeHTTPSListeners(t *testing.T) { + describeArgs := &DescribeListenerArgs{ + ListenerPort: 93, + } + _, err := BLB_CLIENT.DescribeHTTPSListeners(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateSSLListener(t *testing.T) { + createArgs := &CreateSSLListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 94, + BackendPort: 94, + Scheduler: "RoundRobin", + CertIds: []string{CERT_ID}, + } + err := BLB_CLIENT.CreateSSLListener(BLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateSSLListener(t *testing.T) { + updateArgs := &UpdateSSLListenerArgs{ + ClientToken: getClientToken(), + ListenerPort: 94, + Scheduler: "LeastConnection", + CertIds: []string{CERT_ID}, + } + err := BLB_CLIENT.UpdateSSLListener(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeSSLListeners(t *testing.T) { + describeArgs := &DescribeListenerArgs{ + ListenerPort: 94, + } + _, err := BLB_CLIENT.DescribeSSLListeners(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeAllListeners(t *testing.T) { + describeArgs := &DescribeListenerArgs{} + result, err := BLB_CLIENT.DescribeAllListeners(BLB_ID, describeArgs) + if err != nil { + fmt.Println("get all listener failed:", err) + } else { + fmt.Println("get all listener success: ", result) + } +} + +func TestClient_AddBackendServers(t *testing.T) { + createArgs := &AddBackendServersArgs{ + ClientToken: getClientToken(), + BackendServerList: []BackendServerModel{ + {InstanceId: INSTANCE_ID, Weight: 30}, + }, + } + err := BLB_CLIENT.AddBackendServers(BLB_ID, createArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateBackendServers(t *testing.T) { + updateArgs := &UpdateBackendServersArgs{ + ClientToken: getClientToken(), + BackendServerList: []BackendServerModel{ + {InstanceId: INSTANCE_ID, Weight: 50}, + }, + } + err := BLB_CLIENT.UpdateBackendServers(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeBackendServers(t *testing.T) { + describeArgs := &DescribeBackendServersArgs{} + _, err := BLB_CLIENT.DescribeBackendServers(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeHealthStatus(t *testing.T) { + describeArgs := &DescribeHealthStatusArgs{ + ListenerPort: 90, + } + _, err := BLB_CLIENT.DescribeHealthStatus(BLB_ID, describeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RemoveBackendServers(t *testing.T) { + deleteArgs := &RemoveBackendServersArgs{ + BackendServerList: []string{INSTANCE_ID}, + ClientToken: getClientToken(), + } + err := BLB_CLIENT.RemoveBackendServers(BLB_ID, deleteArgs) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteListeners(t *testing.T) { + deleteArgs := &DeleteListenersArgs{ + PortList: []uint16{90, 91, 92, 93, 94}, + ClientToken: getClientToken(), + } + err := BLB_CLIENT.DeleteListeners(BLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeletePortTypeListeners(t *testing.T) { + deleteArgs := &DeleteListenersArgs{ + PortTypeList: []PortTypeModel{ + { + Port: 80, + Type: "UDP", + }, + { + Port: 80, + Type: "HTTP", + }, + }, + ClientToken: getClientToken(), + } + err := BLB_CLIENT.DeleteListeners(BLB_ID, deleteArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteLoadBalancer(t *testing.T) { + err := BLB_CLIENT.DeleteLoadBalancer(BLB_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeLbClusters(t *testing.T) { + describeArgs := &DescribeLbClustersArgs{} + res, err := BLB_CLIENT.DescribeLbClusters(describeArgs) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeLbClusterDetail(t *testing.T) { + res, err := BLB_CLIENT.DescribeLbClusterDetail(CLUSTER_ID) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateLoadBalancerAcl(t *testing.T) { + supportAcl := new(bool) + *supportAcl = true + updateArgs := &UpdateLoadBalancerAclArgs{ + ClientToken: getClientToken(), + SupportAcl: supportAcl, + } + err := BLB_CLIENT.UpdateLoadBalancerAcl(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindSecurityGroups(t *testing.T) { + updateArgs := &UpdateSecurityGroupsArgs{ + ClientToken: getClientToken(), + SecurityGroupIds: []string{"sg-id"}, + } + err := BLB_CLIENT.BindSecurityGroups(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindSecurityGroups(t *testing.T) { + updateArgs := &UpdateSecurityGroupsArgs{ + ClientToken: getClientToken(), + SecurityGroupIds: []string{"sg-id"}, + } + err := BLB_CLIENT.UnbindSecurityGroups(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeSecurityGroups(t *testing.T) { + res, err := BLB_CLIENT.DescribeSecurityGroups(BLB_ID) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindEnterpriseSecurityGroups(t *testing.T) { + updateArgs := &UpdateEnterpriseSecurityGroupsArgs{ + ClientToken: getClientToken(), + EnterpriseSecurityGroupIds: []string{"esg-id"}, + } + err := BLB_CLIENT.BindEnterpriseSecurityGroups(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindEnterpriseSecurityGroups(t *testing.T) { + updateArgs := &UpdateEnterpriseSecurityGroupsArgs{ + ClientToken: getClientToken(), + EnterpriseSecurityGroupIds: []string{"esg-id"}, + } + err := BLB_CLIENT.UnbindEnterpriseSecurityGroups(BLB_ID, updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeEnterpriseSecurityGroups(t *testing.T) { + res, err := BLB_CLIENT.DescribeEnterpriseSecurityGroups(BLB_ID) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/blb/config.json b/bce-sdk-go/services/blb/config.json new file mode 100644 index 0000000..5a6634f --- /dev/null +++ b/bce-sdk-go/services/blb/config.json @@ -0,0 +1,5 @@ +{ + "AK":"", + "SK":"", + "Endpoint":"" +} diff --git a/bce-sdk-go/services/blb/enterprisesecuritygroups.go b/bce-sdk-go/services/blb/enterprisesecuritygroups.go new file mode 100644 index 0000000..6c58641 --- /dev/null +++ b/bce-sdk-go/services/blb/enterprisesecuritygroups.go @@ -0,0 +1,96 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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. + */ + +// enterprisesecuritygroups.go - the enterprisesecuritygroup APIs definition supported by the BLB service + +package blb + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// BindEnterpriseSecurityGroups - bind the blb enterprise security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update enterprise security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) BindEnterpriseSecurityGroups(blbId string, args *UpdateEnterpriseSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.EnterpriseSecurityGroupIds) == 0 { + return fmt.Errorf("unset enterprise security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEnterpriseSecurityGroupUri(blbId)). + WithQueryParam("bind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UnbindEnterpriseSecurityGroups - unbind the blb enterprise security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update enterprise security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UnbindEnterpriseSecurityGroups(blbId string, args *UpdateEnterpriseSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.EnterpriseSecurityGroupIds) == 0 { + return fmt.Errorf("unset enterprise security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEnterpriseSecurityGroupUri(blbId)). + WithQueryParam("unbind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeEnterpriseSecurityGroups - describe all enterprise security groups of the specified LoadBalancer (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// +// RETURNS: +// - *DescribeEnterpriseSecurityGroupsResult: the result of describe all enterprise security groups +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeEnterpriseSecurityGroups(blbId string) (*DescribeEnterpriseSecurityGroupsResult, error) { + + result := &DescribeEnterpriseSecurityGroupsResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEnterpriseSecurityGroupUri(blbId)). + WithResult(result) + + err := request.Do() + return result, err +} diff --git a/bce-sdk-go/services/blb/listener.go b/bce-sdk-go/services/blb/listener.go new file mode 100644 index 0000000..5c1937d --- /dev/null +++ b/bce-sdk-go/services/blb/listener.go @@ -0,0 +1,542 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// listener.go - the Normal BLB Listener APIs definition supported by the BLB service + +package blb + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateTCPListener - create a TCP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create TCP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateTCPListener(blbId string, args *CreateTCPListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if args.BackendPort == 0 { + return fmt.Errorf("unsupport backend port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getTCPListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateUDPListener - create a UDP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create UDP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateUDPListener(blbId string, args *CreateUDPListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if args.BackendPort == 0 { + return fmt.Errorf("unsupport backend port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.HealthCheckString) == 0 { + return fmt.Errorf("unset healthCheckString") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getUDPListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateHTTPListener - create a HTTP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create HTTP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateHTTPListener(blbId string, args *CreateHTTPListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if args.BackendPort == 0 { + return fmt.Errorf("unsupport backend port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getHTTPListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateHTTPSListener - create a HTTPS Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create HTTPS Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateHTTPSListener(blbId string, args *CreateHTTPSListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if args.BackendPort == 0 { + return fmt.Errorf("unsupport backend port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.CertIds) == 0 { + return fmt.Errorf("unset certIds") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getHTTPSListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// CreateAppSSLListener - create a SSL Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to create SSL Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) CreateSSLListener(blbId string, args *CreateSSLListenerArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.ListenerPort == 0 { + return fmt.Errorf("unsupport listener port") + } + + if args.BackendPort == 0 { + return fmt.Errorf("unsupport backend port") + } + + if len(args.Scheduler) == 0 { + return fmt.Errorf("unset scheduler") + } + + if len(args.CertIds) == 0 { + return fmt.Errorf("unset certIds") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getSSLListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateTCPListener - update a TCP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update TCP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateTCPListener(blbId string, args *UpdateTCPListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getTCPListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateUDPListener - update a UDP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update UDP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateUDPListener(blbId string, args *UpdateUDPListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUDPListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateHTTPListener - update a HTTP Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update HTTP Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateHTTPListener(blbId string, args *UpdateHTTPListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getHTTPListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateHTTPSListener - update a HTTPS Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update HTTPS Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateHTTPSListener(blbId string, args *UpdateHTTPSListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getHTTPSListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateSSLListener - update a SSL Listener +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to update SSL Listener +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateSSLListener(blbId string, args *UpdateSSLListenerArgs) error { + if args == nil || args.ListenerPort == 0 { + return fmt.Errorf("unset listener port") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getSSLListenerUri(blbId)). + WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeTCPListeners - describe all TCP Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all TCP Listeners +// +// RETURNS: +// - *DescribeTCPListenersResult: the result of describe all TCP Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeTCPListeners(blbId string, args *DescribeListenerArgs) (*DescribeTCPListenersResult, error) { + if args == nil { + args = &DescribeListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeTCPListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTCPListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeUDPListeners - describe all UDP Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all UDP Listeners +// +// RETURNS: +// - *DescribeUDPListenersResult: the result of describe all UDP Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeUDPListeners(blbId string, args *DescribeListenerArgs) (*DescribeUDPListenersResult, error) { + if args == nil { + args = &DescribeListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeUDPListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getUDPListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeHTTPListeners - describe all HTTP Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all HTTP Listeners +// +// RETURNS: +// - *DescribeHTTPListenersResult: the result of describe all HTTP Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeHTTPListeners(blbId string, args *DescribeListenerArgs) (*DescribeHTTPListenersResult, error) { + if args == nil { + args = &DescribeListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeHTTPListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getHTTPListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeHTTPSListeners - describe all HTTPS Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all HTTPS Listeners +// +// RETURNS: +// - *DescribeHTTPSListenersResult: the result of describe all HTTPS Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeHTTPSListeners(blbId string, args *DescribeListenerArgs) (*DescribeHTTPSListenersResult, error) { + if args == nil { + args = &DescribeListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeHTTPSListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getHTTPSListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeSSLListeners - describe all SSL Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all SSL Listeners +// +// RETURNS: +// - *DescribeSSLListenersResult: the result of describe all SSL Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeSSLListeners(blbId string, args *DescribeListenerArgs) (*DescribeSSLListenersResult, error) { + if args == nil { + args = &DescribeListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeSSLListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSSLListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DescribeAllListeners - describe all Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to describe all Listeners +// +// RETURNS: +// - *DescribeAllListenersResult: the result of describe all Listeners +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeAllListeners(blbId string, args *DescribeListenerArgs) (*DescribeAllListenersResult, error) { + if args == nil { + args = &DescribeListenerArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &DescribeAllListenersResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getListenerUri(blbId)). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + if args.ListenerPort != 0 { + request.WithQueryParam("listenerPort", strconv.Itoa(int(args.ListenerPort))) + } + + err := request.Do() + return result, err +} + +// DeleteListeners - delete Listeners +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: parameters to delete Listeners, a listener port list +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteListeners(blbId string, args *DeleteListenersArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.PortList) == 0 && len(args.PortTypeList) == 0 { + return fmt.Errorf("unset port list") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getListenerUri(blbId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("batchdelete", ""). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/blb/model.go b/bce-sdk-go/services/blb/model.go new file mode 100644 index 0000000..b37a5cb --- /dev/null +++ b/bce-sdk-go/services/blb/model.go @@ -0,0 +1,632 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package blb + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type BLBStatus string + +const ( + BLBStatusCreating BLBStatus = "creating" + BLBStatusAvailable BLBStatus = "available" + BLBStatusUpdating BLBStatus = "updating" + BLBStatusPaused BLBStatus = "paused" + BLBStatusUnavailable BLBStatus = "unavailable" +) + +type DescribeResultMeta struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type CreateLoadBalancerArgs struct { + ClientToken string `json:"-"` + Name string `json:"name,omitempty"` + Description string `json:"desc,omitempty"` + SubnetId string `json:"subnetId"` + VpcId string `json:"vpcId"` + ClusterProperty string `json:"clusterProperty"` + Type string `json:"type,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +type CreateLoadBalancerResult struct { + Address string `json:"address"` + Name string `json:"name"` + Description string `json:"desc"` + BlbId string `json:"blbId"` +} + +type UpdateLoadBalancerArgs struct { + ClientToken string `json:"-"` + Name string `json:"name,omitempty"` + Description string `json:"desc,omitempty"` + AllowDelete *bool `json:"allowDelete,omitempty"` +} + +type UpdateLoadBalancerAclArgs struct { + ClientToken string `json:"-"` + SupportAcl *bool `json:"supportAcl,omitempty"` +} + +type DescribeLoadBalancersArgs struct { + Address string + Name string + BlbId string + BccId string + ExactlyMatch bool + Marker string + MaxKeys int + Type string +} + +type BLBModel struct { + BlbId string `json:"blbId"` + Name string `json:"name"` + Description string `json:"desc"` + Address string `json:"address"` + Status BLBStatus `json:"status"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + PublicIp string `json:"publicIp"` + Layer4ClusterId string `json:"layer4ClusterId"` + Layer7ClusterId string `json:"layer7ClusterId"` + Tags []model.TagModel `json:"tags"` + EipRouteType string `json:"eipRouteType"` + AllowDelete bool `json:"allowDelete"` +} + +type DescribeLoadBalancersResult struct { + BlbList []BLBModel `json:"blbList"` + DescribeResultMeta +} + +type ListenerModel struct { + Port string `json:"port"` + Type string `json:"type"` +} + +type PortTypeModel struct { + Port int `json:"port"` + Type string `json:"type"` +} + +type DescribeLoadBalancerDetailResult struct { + BlbId string `json:"blbId"` + Status BLBStatus `json:"status"` + Name string `json:"name"` + Description string `json:"desc"` + Address string `json:"address"` + PublicIp string `json:"publicIp"` + Cidr string `json:"cidr"` + VpcName string `json:"vpcName"` + CreateTime string `json:"createTime"` + Layer4ClusterId string `json:"layer4ClusterId"` + Layer7ClusterId string `json:"layer7ClusterId"` + Listener []ListenerModel `json:"listener"` + Tags []model.TagModel `json:"tags"` + EipRouteType string `json:"eipRouteType"` + Ipv6 string `json:"ipv6,omitempty"` +} + +type CreateTCPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` +} + +type CreateUDPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + UdpSessionTimeout int `json:"udpSessionTimeout,omitempty"` + HealthCheckString string `json:"healthCheckString"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` +} + +type CreateHTTPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionDuration int `json:"keepSessionDuration,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + HealthCheckType string `json:"healthCheckType,omitempty"` + HealthCheckPort uint16 `json:"healthCheckPort,omitempty"` + HealthCheckURI string `json:"healthCheckURI,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + RedirectPort uint16 `json:"redirectPort,omitempty"` +} + +type CreateHTTPSListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + CertIds []string `json:"certIds"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionDuration int `json:"keepSessionDuration,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + HealthCheckType string `json:"healthCheckType,omitempty"` + HealthCheckPort uint16 `json:"healthCheckPort,omitempty"` + HealthCheckURI string `json:"healthCheckURI,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + RedirectPort uint16 `json:"redirectPort,omitempty"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type CreateSSLListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + CertIds []string `json:"certIds"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type UpdateListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + Scheduler string `json:"scheduler,omitempty"` + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` +} + +type UpdateTCPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + BackendPort uint16 `json:"backendPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + TcpSessionTimeout int `json:"tcpSessionTimeout,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` +} + +type UpdateUDPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + BackendPort uint16 `json:"backendPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + UdpSessionTimeout int `json:"udpSessionTimeout,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + HealthCheckString string `json:"healthCheckString,omitempty"` +} + +type UpdateHTTPListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + BackendPort uint16 `json:"backendPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionDuration int `json:"keepSessionDuration,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + HealthCheckType string `json:"healthCheckType,omitempty"` + HealthCheckPort uint16 `json:"healthCheckPort,omitempty"` + HealthCheckURI string `json:"healthCheckURI,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + RedirectPort uint16 `json:"redirectPort,omitempty"` +} + +type UpdateHTTPSListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + KeepSession bool `json:"keepSession,omitempty"` + KeepSessionType string `json:"keepSessionType,omitempty"` + KeepSessionDuration int `json:"keepSessionDuration,omitempty"` + KeepSessionCookieName string `json:"keepSessionCookieName,omitempty"` + XForwardedFor bool `json:"xForwardedFor,omitempty"` + HealthCheckType string `json:"healthCheckType,omitempty"` + HealthCheckPort uint16 `json:"healthCheckPort,omitempty"` + HealthCheckURI string `json:"healthCheckURI,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus,omitempty"` + ServerTimeout int `json:"serverTimeout,omitempty"` + CertIds []string `json:"certIds,omitempty"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` +} + +type UpdateSSLListenerArgs struct { + ClientToken string `json:"-"` + ListenerPort uint16 `json:"-"` + BackendPort uint16 `json:"backendPort,omitempty"` + Scheduler string `json:"scheduler,omitempty"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval,omitempty"` + UnhealthyThreshold int `json:"unhealthyThreshold,omitempty"` + HealthyThreshold int `json:"healthyThreshold,omitempty"` + CertIds []string `json:"certIds,omitempty"` + EncryptionType string `json:"encryptionType,omitempty"` + EncryptionProtocols []string `json:"encryptionProtocols,omitempty"` + AppliedCiphers string `json:"appliedCiphers,omitempty"` + DualAuth bool `json:"dualAuth,omitempty"` + ClientCertIds []string `json:"clientCertIds,omitempty"` +} + +type TCPListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckInterval int `json:"healthCheckInterval"` + UnhealthyThreshold int `json:"unhealthyThreshold"` + HealthyThreshold int `json:"healthyThreshold"` + GetBlbIp bool `json:"getBlbIp"` + TcpSessionTimeout int `json:"tcpSessionTimeout"` +} + +type UDPListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + UdpSessionTimeout int `json:"udpSessionTimeout"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckInterval int `json:"healthCheckInterval"` + UnhealthyThreshold int `json:"unhealthyThreshold"` + HealthyThreshold int `json:"healthyThreshold"` + GetBlbIp bool `json:"getBlbIp"` + HealthCheckString string `json:"healthCheckString"` +} + +type HTTPListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession"` + KeepSessionType string `json:"keepSessionType"` + KeepSessionDuration int `json:"keepSessionDuration"` + KeepSessionCookieName string `json:"keepSessionCookieName"` + XForwardedFor bool `json:"xForwardedFor"` + HealthCheckType string `json:"healthCheckType"` + HealthCheckPort uint16 `json:"healthCheckPort"` + HealthCheckURI string `json:"healthCheckURI"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckInterval int `json:"healthCheckInterval"` + UnhealthyThreshold int `json:"unhealthyThreshold"` + HealthyThreshold int `json:"healthyThreshold"` + GetBlbIp bool `json:"getBlbIp"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` + ServerTimeout int `json:"serverTimeout"` + RedirectPort int `json:"redirectPort"` +} + +type HTTPSListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + KeepSession bool `json:"keepSession"` + KeepSessionType string `json:"keepSessionType"` + KeepSessionDuration int `json:"keepSessionDuration"` + KeepSessionCookieName string `json:"keepSessionCookieName"` + XForwardedFor bool `json:"xForwardedFor"` + HealthCheckType string `json:"healthCheckType"` + HealthCheckPort uint16 `json:"healthCheckPort"` + HealthCheckURI string `json:"healthCheckURI"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckInterval int `json:"healthCheckInterval"` + UnhealthyThreshold int `json:"unhealthyThreshold"` + HealthyThreshold int `json:"healthyThreshold"` + GetBlbIp bool `json:"getBlbIp"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` + ServerTimeout int `json:"serverTimeout"` + CertIds []string `json:"certIds"` + DualAuth bool `json:"dualAuth"` + ClientCertIds []string `json:"clientCertIds"` + EncryptionType string `json:"encryptionType"` + EncryptionProtocols []string `json:"encryptionProtocols"` + AppliedCiphers string `json:"appliedCiphers"` +} + +type SSLListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckInterval int `json:"healthCheckInterval"` + UnhealthyThreshold int `json:"unhealthyThreshold"` + HealthyThreshold int `json:"healthyThreshold"` + GetBlbIp bool `json:"getBlbIp"` + CertIds []string `json:"certIds"` + EncryptionType string `json:"encryptionType"` + EncryptionProtocols []string `json:"encryptionProtocols"` + AppliedCiphers string `json:"appliedCiphers"` + DualAuth bool `json:"dualAuth"` + ClientCertIds []string `json:"clientCertIds"` + ServerTimeout int `json:"serverTimeout"` +} + +type AllListenerModel struct { + ListenerPort uint16 `json:"listenerPort"` + ListenerType string `json:"listenerType"` + BackendPort uint16 `json:"backendPort"` + Scheduler string `json:"scheduler"` + GetBlbIp bool `json:"getBlbIp"` + TcpSessionTimeout int `json:"tcpSessionTimeout"` + UdpSessionTimeout int `json:"udpSessionTimeout"` + HealthCheckString string `json:"healthCheckString"` + KeepSession bool `json:"keepSession"` + KeepSessionType string `json:"keepSessionType"` + KeepSessionDuration int `json:"keepSessionDuration"` + KeepSessionCookieName string `json:"keepSessionCookieName"` + XForwardedFor bool `json:"xForwardedFor"` + HealthCheckType string `json:"healthCheckType"` + HealthCheckPort uint16 `json:"healthCheckPort"` + HealthCheckURI string `json:"healthCheckURI"` + HealthCheckTimeoutInSecond int `json:"healthCheckTimeoutInSecond"` + HealthCheckInterval int `json:"healthCheckInterval"` + UnhealthyThreshold int `json:"unhealthyThreshold"` + HealthyThreshold int `json:"healthyThreshold"` + HealthCheckNormalStatus string `json:"healthCheckNormalStatus"` + HealthCheckHost string `json:"healthCheckHost"` + ServerTimeout int `json:"serverTimeout"` + RedirectPort int `json:"redirectPort"` + CertIds []string `json:"certIds"` + DualAuth bool `json:"dualAuth"` + ClientCertIds []string `json:"clientCertIds"` + EncryptionType string `json:"encryptionType"` + EncryptionProtocols []string `json:"encryptionProtocols"` + AppliedCiphers string `json:"appliedCiphers"` +} + +type DescribeListenerArgs struct { + ListenerPort uint16 + Marker string + MaxKeys int +} + +type DescribeTCPListenersResult struct { + ListenerList []TCPListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeUDPListenersResult struct { + ListenerList []UDPListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeHTTPListenersResult struct { + ListenerList []HTTPListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeHTTPSListenersResult struct { + ListenerList []HTTPSListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeSSLListenersResult struct { + ListenerList []SSLListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DescribeAllListenersResult struct { + AllListenerList []AllListenerModel `json:"listenerList"` + DescribeResultMeta +} + +type DeleteListenersArgs struct { + ClientToken string `json:"-"` + PortList []uint16 `json:"portList"` + PortTypeList []PortTypeModel `json:"portTypeList"` +} + +type AddBackendServersArgs struct { + ClientToken string `json:"-"` + BackendServerList []BackendServerModel `json:"backendServerList"` +} + +type BackendServerModel struct { + InstanceId string `json:"instanceId"` + Weight int `json:"weight"` + PrivateIp string `json:"privateIp,omitempty"` +} + +type BackendServerStatus struct { + InstanceId string `json:"instanceId"` + Weight int `json:"weight"` + Status string `json:"status"` + PrivateIp string `json:"privateIp"` +} + +type UpdateBackendServersArgs struct { + ClientToken string `json:"-"` + BackendServerList []BackendServerModel `json:"backendServerList"` +} + +type DescribeBackendServersArgs struct { + Marker string + MaxKeys int +} + +type DescribeBackendServersResult struct { + BackendServerList []BackendServerModel `json:"backendServerList"` + DescribeResultMeta +} + +type DescribeHealthStatusArgs struct { + ListenerPort uint16 + Marker string + MaxKeys int +} + +type DescribeHealthStatusResult struct { + BackendServerList []BackendServerStatus `json:"backendServerList"` + Type string `json:"type"` + ListenerPort uint16 `json:"listenerPort"` + BackendPort uint16 `json:"backendPort"` + DescribeResultMeta +} + +type RemoveBackendServersArgs struct { + ClientToken string `json:"-"` + BackendServerList []string `json:"backendServerList"` +} + +type DescribeLbClusterDetailResult struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + ClusterType string `json:"clusterType"` + ClusterRegion string `json:"clusterRegion"` + ClusterAz string `json:"clusterAz"` + TotalConnectCount uint64 `json:"totalConnectCount"` + NewConnectCps uint64 `json:"newConnectCps"` + NetworkInBps uint64 `json:"networkInBps"` + NetworkOutBps uint64 `json:"networkOutBps"` + NetworkInPps uint64 `json:"networkInPps"` + NetworkOutPps uint64 `json:"networkOutPps"` + HttpsQps uint64 `json:"httpsQps"` + HttpQps uint64 `json:"httpQps"` + HttpNewConnectCps uint64 `json:"httpNewConnectCps"` + HttpsNewConnectCps uint64 `json:"httpsNewConnectCps"` +} + +type DescribeLbClustersArgs struct { + ClusterName string + ClusterId string + ExactlyMatch bool + Marker string + MaxKeys int +} + +type DescribeLbClustersResult struct { + ClusterList []ClusterModel `json:"clusterList"` + DescribeResultMeta +} + +type ClusterModel struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + ClusterType string `json:"clusterType"` + ClusterRegion string `json:"clusterRegion"` + ClusterAz string `json:"clusterAz"` +} + +type UpdateSecurityGroupsArgs struct { + ClientToken string `json:"-"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type UpdateEnterpriseSecurityGroupsArgs struct { + ClientToken string `json:"-"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` +} + +type DescribeSecurityGroupsResult struct { + BlbSecurityGroups []BlbSecurityGroupModel `json:"blbSecurityGroups"` +} + +type DescribeEnterpriseSecurityGroupsResult struct { + BlbEnterpriseSecurityGroups []BlbEnterpriseSecurityGroupModel `json:"enterpriseSecurityGroups"` +} + +type BlbSecurityGroupModel struct { + SecurityGroupId string `json:"securityGroupId"` + SecurityGroupName string `json:"securityGroupName"` + SecurityGroupDesc string `json:"securityGroupDesc"` + VpcName string `json:"vpcName"` + SecurityGroupRules []BlbSecurityGroupRuleModel `json:"securityGroupRules"` +} + +type BlbEnterpriseSecurityGroupModel struct { + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId"` + EnterpriseSecurityGroupName string `json:"enterpriseSecurityGroupName"` + EnterpriseSecurityGroupDesc string `json:"enterpriseSecurityGroupDesc"` + EnterpriseSecurityGroupRules []BlbEnterpriseSecurityGroupRuleModel `json:"enterpriseSecurityGroupRules"` +} + +type BlbSecurityGroupRuleModel struct { + SecurityGroupRuleId string `json:"securityGroupRuleId"` + Direction string `json:"direction"` + Ethertype string `json:"ethertype,omitempty"` + PortRange string `json:"portRange,omitempty"` + Protocol string `json:"protocol,omitempty"` + SourceGroupId string `json:"sourceGroupId,omitempty"` + SourceIp string `json:"sourceIp,omitempty"` + DestGroupId string `json:"destGroupId,omitempty"` + DestIp string `json:"destIp,omitempty"` +} + +type BlbEnterpriseSecurityGroupRuleModel struct { + EnterpriseSecurityGroupRuleId string `json:"enterpriseSecurityGroupRuleId"` + Direction string `json:"direction"` + Action string `json:"action"` + Priority int `json:"priority"` + Remark string `json:"remark"` + Ethertype string `json:"ethertype,omitempty"` + PortRange string `json:"portRange,omitempty"` + Protocol string `json:"protocol,omitempty"` + SourceIp string `json:"sourceIp,omitempty"` + DestIp string `json:"destIp,omitempty"` +} diff --git a/bce-sdk-go/services/blb/securitygroup.go b/bce-sdk-go/services/blb/securitygroup.go new file mode 100644 index 0000000..d41e799 --- /dev/null +++ b/bce-sdk-go/services/blb/securitygroup.go @@ -0,0 +1,95 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// securitygroup.go - the securitygroup APIs definition supported by the BLB service + +package blb + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// BindSecurityGroups - bind the blb security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) BindSecurityGroups(blbId string, args *UpdateSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.SecurityGroupIds) == 0 { + return fmt.Errorf("unset security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getSecurityGroupUri(blbId)). + WithQueryParam("bind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UnbindSecurityGroups - unbind the blb security groups (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// - args: the parameter to update security groups +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UnbindSecurityGroups(blbId string, args *UpdateSecurityGroupsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if len(args.SecurityGroupIds) == 0 { + return fmt.Errorf("unset security group ids") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getSecurityGroupUri(blbId)). + WithQueryParam("unbind", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DescribeSecurityGroups - describe all security groups of the specified LoadBalancer (normal/application/ipv6 LoadBalancer) +// +// PARAMS: +// - blbId: LoadBalancer's ID +// +// RETURNS: +// - *DescribeSecurityGroupsResult: the result of describe all security groups +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeSecurityGroups(blbId string) (*DescribeSecurityGroupsResult, error) { + + result := &DescribeSecurityGroupsResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupUri(blbId)). + WithResult(result) + + err := request.Do() + return result, err +} diff --git a/bce-sdk-go/services/bls/api/fastquery.go b/bce-sdk-go/services/bls/api/fastquery.go new file mode 100644 index 0000000..532a3c9 --- /dev/null +++ b/bce-sdk-go/services/bls/api/fastquery.go @@ -0,0 +1,168 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// fastquery.go - the fastQuery APIs definition supported by the BLS service + +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateFastQuery - create a fastQuery +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: the fastQuery body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CreateFastQuery(cli bce.Client, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(FASTQUERY_PREFIX) + req.SetMethod(http.POST) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// DescribeFastQuery - get specific fastQuery info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - fastQueryName: fastQuery name to get +// +// RETURNS: +// - *FastQuery: target fastQuery info +// - error: nil if success otherwise the specific error +func DescribeFastQuery(cli bce.Client, fastQueryName string) (*FastQuery, error) { + req := &bce.BceRequest{} + req.SetUri(getFastQueryUri(fastQueryName)) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &FastQuery{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// UpdateFastQuery - update specific fastQuery info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: update fastQuery body +// - fastQueryName: fastQuery to update +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateFastQuery(cli bce.Client, body *bce.Body, fastQueryName string) error { + req := &bce.BceRequest{} + req.SetUri(getFastQueryUri(fastQueryName)) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteFastQuery - delete specific fastQuery +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - fastQueryName: fastQuery name to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteFastQuery(cli bce.Client, fastQueryName string) error { + req := &bce.BceRequest{} + req.SetUri(getFastQueryUri(fastQueryName)) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// ListFastQuery - get all fastQuery info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: query args to get pattern-match fastQuery +// +// RETURNS: +// - *ListFastQueryResult: pattern-match fastQuery result +// - error: nil if success otherwise the specific error +func ListFastQuery(cli bce.Client, args *QueryConditions) (*ListFastQueryResult, error) { + req := &bce.BceRequest{} + req.SetUri(FASTQUERY_PREFIX) + req.SetMethod(http.GET) + // Set optional args + if args != nil { + if args.NamePattern != "" { + req.SetParam("namePattern", args.NamePattern) + } + if args.Order != "" { + req.SetParam("order", args.Order) + } + if args.OrderBy != "" { + req.SetParam("orderBy", args.OrderBy) + } + if args.PageNo > 0 { + req.SetParam("pageNo", strconv.Itoa(args.PageNo)) + } + if args.PageSize > 0 { + req.SetParam("pageSize", strconv.Itoa(args.PageSize)) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListFastQueryResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bls/api/index.go b/bce-sdk-go/services/bls/api/index.go new file mode 100644 index 0000000..5a3b92c --- /dev/null +++ b/bce-sdk-go/services/bls/api/index.go @@ -0,0 +1,122 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// index.go - the Index APIs definition supported by the BLS service + +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateIndex - create index for logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStoreName: logStore needs to be indexed +// - body: index mappings body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CreateIndex(cli bce.Client, logStoreName string, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getIndexUri(logStoreName)) + req.SetMethod(http.POST) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// UpdateIndex - update index info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStoreName: logStore needs to be updated +// - body: index mappings body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateIndex(cli bce.Client, logStoreName string, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getIndexUri(logStoreName)) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteIndex - delete index for logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStoreName: logStore to be deleted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteIndex(cli bce.Client, logStoreName string) error { + req := &bce.BceRequest{} + req.SetUri(getIndexUri(logStoreName)) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// DescribeIndex - get specific logStore index info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStoreName: logStore needs to be get +// +// RETURNS: +// - *IndexFields: index mappings info +// - error: nil if success otherwise the specific error +func DescribeIndex(cli bce.Client, logStoreName string) (*IndexFields, error) { + req := &bce.BceRequest{} + req.SetUri(getIndexUri(logStoreName)) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &IndexFields{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bls/api/logrecord.go b/bce-sdk-go/services/bls/api/logrecord.go new file mode 100644 index 0000000..24aded2 --- /dev/null +++ b/bce-sdk-go/services/bls/api/logrecord.go @@ -0,0 +1,131 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// logrecord.go - the logRecord APIs definition supported by the BLS service + +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// PushLogRecord - push logRecords into logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: target logStore to store logRecords +// - body: logRecord body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PushLogRecord(cli bce.Client, logStore string, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getLogRecordUri(logStore)) + req.SetMethod(http.POST) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PullLogRecord - get logRecords from logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: target logStore to get logRecords +// - args: pull logRecords limitation args +// +// RETURNS: +// - *PullLogRecordResult: pull logRecord result set +// - error: nil if success otherwise the specific error +func PullLogRecord(cli bce.Client, logStore string, args *PullLogRecordArgs) (*PullLogRecordResult, error) { + req := &bce.BceRequest{} + req.SetUri(getLogRecordUri(logStore)) + req.SetMethod(http.GET) + if args != nil { + if args.LogStreamName != "" { + req.SetParam("logStreamName", args.LogStreamName) + } + if len(args.StartDateTime) != 0 { + req.SetParam("startDateTime", string(args.StartDateTime)) + } + if len(args.EndDateTime) != 0 { + req.SetParam("endDateTime", string(args.EndDateTime)) + } + if args.Limit > 0 && args.Limit <= 1000 { + req.SetParam("limit", strconv.Itoa(args.Limit)) + } + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &PullLogRecordResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// QueryLogRecord - retrieve logRecords from logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: target logStore to retrieve logRecords +// - args: query logRecords conditions args +// +// RETURNS: +// - *QueryLogResult: query logRecord result set +// - error: nil if success otherwise the specific error +func QueryLogRecord(cli bce.Client, logStore string, args *QueryLogRecordArgs) (*QueryLogResult, error) { + req := &bce.BceRequest{} + req.SetUri(getLogRecordUri(logStore)) + req.SetMethod(http.GET) + if args != nil { + req.SetParam("logStreamName", args.LogStreamName) + req.SetParam("query", args.Query) + req.SetParam("startDateTime", string(args.StartDateTime)) + req.SetParam("endDateTime", string(args.EndDateTime)) + if args.Limit > 0 { + req.SetParam("limit", strconv.Itoa(args.Limit)) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &QueryLogResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bls/api/logshipper.go b/bce-sdk-go/services/bls/api/logshipper.go new file mode 100644 index 0000000..34dc542 --- /dev/null +++ b/bce-sdk-go/services/bls/api/logshipper.go @@ -0,0 +1,297 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// logshipper.go - the logShipper APIs definition supported by the BLS service + +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateLogShipper - create logShipper +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: logShipper parameters body +// +// RETURNS: +// - string: snowflake base64 id for logShipper, empty string if creation fail +// - error: nil if success otherwise the specific error +func CreateLogShipper(cli bce.Client, body *bce.Body) (string, error) { + req := &bce.BceRequest{} + req.SetUri(LOGSHIPPER_PREFIX) + req.SetMethod(http.POST) + if body != nil { + req.SetBody(body) + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + result := &CreateLogShipperResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return "", err + } + return result.LogShipperID, nil +} + +// UpdateLogShipper - update logShipper name and destConfig +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logShipperID: logShipperID to update +// - body: logShipper parameters body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateLogShipper(cli bce.Client, body *bce.Body, logShipperID string) error { + req := &bce.BceRequest{} + req.SetUri(getLogShipperUri(logShipperID)) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetLogShipper - get logShipper info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logShipperID: logShipper to get +// +// RETURNS: +// - *LogShipper: logShipper info +// - error: nil if success otherwise the specific error +func GetLogShipper(cli bce.Client, logShipperID string) (*LogShipper, error) { + req := &bce.BceRequest{} + req.SetUri(getLogShipperUri(logShipperID)) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &LogShipper{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// ListLogShipper - get all pattern-match logShipper info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: conditions logShipper should match +// +// RETURNS: +// - *ListShipperResult: logShipper result set +// - error: nil if success otherwise the specific error +func ListLogShipper(cli bce.Client, args *ListLogShipperCondition) (*ListShipperResult, error) { + req := &bce.BceRequest{} + req.SetUri(LOGSHIPPER_PREFIX) + req.SetMethod(http.GET) + if args != nil { + if args.LogShipperID != "" { + req.SetParam("logShipperID", args.LogShipperID) + } + if args.LogShipperName != "" { + req.SetParam("logShipperName", args.LogShipperName) + } + if args.LogShipperName != "" { + req.SetParam("logShipperName", args.LogShipperName) + } + if args.DestType != "" { + req.SetParam("destType", args.DestType) + } + if args.Status != "" { + req.SetParam("status", args.Status) + } + if args.Order != "" { + req.SetParam("order", args.Order) + } + if args.OrderBy != "" { + req.SetParam("orderBy", args.OrderBy) + } + if args.PageNo > 0 { + req.SetParam("pageNo", strconv.Itoa(args.PageNo)) + } + if args.PageSize > 0 { + req.SetParam("pageSize", strconv.Itoa(args.PageSize)) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListShipperResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// ListLogShipperRecord - get logShipper's execution records +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logShipperID: logShipper to get +// - args: conditions records should match +// +// RETURNS: +// - *ListShipperRecordResult: logShipper records result set +// - error: nil if success otherwise the specific error +func ListLogShipperRecord(cli bce.Client, logShipperID string, args *ListShipperRecordCondition) (*ListShipperRecordResult, error) { + req := &bce.BceRequest{} + req.SetUri(getLogShipperRecordUri(logShipperID)) + req.SetMethod(http.GET) + if args != nil { + if args.SinceHours > 0 { + req.SetParam("sinceHours", strconv.Itoa(args.SinceHours)) + } + if args.PageNo > 0 { + req.SetParam("pageNo", strconv.Itoa(args.PageNo)) + } + if args.PageSize > 0 { + req.SetParam("pageSize", strconv.Itoa(args.PageSize)) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListShipperRecordResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteSingleLogShipper - delete logShipper by id +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logShipperID: logShipper to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteSingleLogShipper(cli bce.Client, logShipperID string) error { + req := &bce.BceRequest{} + req.SetUri(getLogShipperUri(logShipperID)) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// BulkDeleteLogShipper - bulk delete logShipper by id +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: bulkDeleteLogShipper parameters body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BulkDeleteLogShipper(cli bce.Client, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(LOGSHIPPER_PREFIX) + req.SetMethod(http.DELETE) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// SetSingleLogShipperStatus - set logShipper status by id +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logShipperID: logShipper to set +// - body: setSingleLogShipperStatus parameters body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetSingleLogShipperStatus(cli bce.Client, logShipperID string, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getLogShipperStatusUri(logShipperID)) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// BulkSetLogShipperStatus - bulk set logShipper status by id +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: bulkSetLogShipperStatus parameters body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func BulkSetLogShipperStatus(cli bce.Client, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getBulkSetLogShipperStatusUri()) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} diff --git a/bce-sdk-go/services/bls/api/logstore.go b/bce-sdk-go/services/bls/api/logstore.go new file mode 100644 index 0000000..eba5078 --- /dev/null +++ b/bce-sdk-go/services/bls/api/logstore.go @@ -0,0 +1,170 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// logstore.go - the logStore APIs definition supported by the BLS service + +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateLogStore - create logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: logStore parameters body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func CreateLogStore(cli bce.Client, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(LOGSTORE_PREFIX) + req.SetMethod(http.POST) + if body != nil { + req.SetBody(body) + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// UpdateLogStore - update logStore retention +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: logStore to update +// - body: logStore parameters body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func UpdateLogStore(cli bce.Client, logStore string, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getLogStoreUri(logStore)) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// DescribeLogStore - get logStore info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: logStore to get +// +// RETURNS: +// - *LogStore: logStore info +// - error: nil if success otherwise the specific error +func DescribeLogStore(cli bce.Client, logStore string) (*LogStore, error) { + req := &bce.BceRequest{} + req.SetUri(getLogStoreUri(logStore)) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &LogStore{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteLogStore - delete logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: logStore to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteLogStore(cli bce.Client, logStore string) error { + req := &bce.BceRequest{} + req.SetUri(getLogStoreUri(logStore)) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// ListLogStore - get all pattern-match logStore info +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: conditions logStore should match +// +// RETURNS: +// - *ListLogStoreResult: logStore result set +// - error: nil if success otherwise the specific error +func ListLogStore(cli bce.Client, args *QueryConditions) (*ListLogStoreResult, error) { + req := &bce.BceRequest{} + req.SetUri(LOGSTORE_PREFIX) + req.SetMethod(http.GET) + // Set optional args + if args != nil { + if args.NamePattern != "" { + req.SetParam("namePattern", args.NamePattern) + } + if args.Order != "" { + req.SetParam("order", args.Order) + } + if args.OrderBy != "" { + req.SetParam("orderBy", args.OrderBy) + } + if args.PageNo > 0 { + req.SetParam("pageNo", strconv.Itoa(args.PageNo)) + } + if args.PageSize > 0 { + req.SetParam("pageSize", strconv.Itoa(args.PageSize)) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListLogStoreResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bls/api/logstream.go b/bce-sdk-go/services/bls/api/logstream.go new file mode 100644 index 0000000..f66ee45 --- /dev/null +++ b/bce-sdk-go/services/bls/api/logstream.go @@ -0,0 +1,70 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// logstream.go - the logStream APIs definition supported by the BLS service + +package api + +import ( + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListLogStream - get all pattern-match logStream in logStore +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - logStore: logStore to parse +// - args: conditions logStream should match +// +// RETURNS: +// - *ListLogStreamResult: pattern-match logStream result set +// - error: nil if success otherwise the specific error +func ListLogStream(cli bce.Client, logStore string, args *QueryConditions) (*ListLogStreamResult, error) { + req := &bce.BceRequest{} + req.SetUri(getLogStreamName(logStore)) + req.SetMethod(http.GET) + // Set optional args + if args != nil { + if args.NamePattern != "" { + req.SetParam("namePattern", args.NamePattern) + } + if args.Order != "" { + req.SetParam("order", args.Order) + } + if args.OrderBy != "" { + req.SetParam("orderBy", args.OrderBy) + } + if args.PageNo > 0 { + req.SetParam("pageNo", strconv.Itoa(args.PageNo)) + } + if args.PageSize > 0 { + req.SetParam("pageSize", strconv.Itoa(args.PageSize)) + } + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListLogStreamResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bls/api/model.go b/bce-sdk-go/services/bls/api/model.go new file mode 100644 index 0000000..cc3356a --- /dev/null +++ b/bce-sdk-go/services/bls/api/model.go @@ -0,0 +1,266 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +type DateTime string + +type LogRecord struct { + Message string `json:"message"` + Timestamp int64 `json:"timestamp"` + Sequence int `json:"sequence"` +} + +type LogStream struct { + CreationDateTime DateTime `json:"creationDateTime"` + LogStreamName string `json:"logStreamName"` +} + +type LogStore struct { + CreationDateTime DateTime `json:"creationDateTime"` + LastModifiedTime DateTime `json:"lastModifiedTime"` + LogStoreName string `json:"logStoreName"` + Retention int `json:"retention"` +} + +type LogShipper struct { + Status string `json:"status"` + LogShipperName string `json:"logShipperName"` + LogStoreName string `json:"logStoreName"` + StartTime string `json:"startTime"` + DestType string `json:"destType"` + DestConfig *ShipperDestConfig `json:"destConfig"` +} + +type QueryConditions struct { + NamePattern string `json:"namePattern"` + Order string `json:"order"` + OrderBy string `json:"orderBy"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type PushLogRecordBody struct { + LogStreamName string `json:"logStreamName"` + Type string `json:"type"` + LogRecords []LogRecord `json:"logRecords"` +} + +type QueryLogRecordArgs struct { + LogStreamName string `json:"logStreamName"` + Query string `json:"query"` + StartDateTime DateTime `json:"startDatetime"` + EndDateTime DateTime `json:"endDateTime"` + Limit int `json:"limit"` +} + +type PullLogRecordArgs struct { + LogStreamName string `json:"logStreamName"` + StartDateTime DateTime `json:"startDatetime"` + EndDateTime DateTime `json:"endDateTime"` + Limit int `json:"limit"` + Marker string `json:"marker"` +} + +type PullLogRecordResult struct { + Result []LogRecord `json:"result"` + IsTruncated bool `json:"isTruncated"` + Marker string `json:"marker"` + NextMarker string `json:"nextMarker"` +} + +type Histogram struct { + Interval int `json:"interval"` + StartDateTime DateTime `json:"startDatetime"` + EndDateTime DateTime `json:"endDateTime"` + Counts []int `json:"counts"` +} + +type Statistics struct { + ExecutionTimeInMs int `json:"executionTimeInMs"` + ScanCount int `json:"scanCount"` + Histogram *Histogram `json:"histogram"` +} + +type DataSetScanInfo struct { + IsTruncated bool `json:"isTruncated"` + TruncatedReason string `json:"truncatedReason"` + Statistics *Statistics `json:"statistics"` +} + +type ResultSet struct { + Columns []string `json:"columns"` + Rows [][]interface{} `json:"rows"` + IsTruncated bool `json:"isTruncated"` + TruncatedReason string `json:"truncatedReason"` +} + +type QueryLogResult struct { + ResultSet *ResultSet `json:"resultSet"` + DataSetScanInfo *DataSetScanInfo `json:"dataScanInfo"` +} + +type ListLogStreamResult struct { + Order string `json:"order"` + OrderBy string `json:"orderBy"` + PageNumber int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []LogStream `json:"result"` +} + +type ListLogStoreResult struct { + Order string `json:"order"` + OrderBy string `json:"orderBy"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []LogStore `json:"result"` +} + +type FastQuery struct { + CreationDateTime DateTime `json:"creationDateTime"` + LastModifiedTime DateTime `json:"lastModifiedTime"` + FastQueryName string `json:"fastQueryName"` + Description string `json:"description"` + Query string `json:"query"` + LogStoreName string `json:"logStoreName"` + LogStreamName string `json:"logStreamName"` +} + +type CreateFastQueryBody struct { + FastQueryName string `json:"fastQueryName"` + Query string `json:"query"` + Description string `json:"description"` + LogStoreName string `json:"logStoreName"` + LogStreamName string `json:"logStreamName"` +} + +type UpdateFastQueryBody struct { + Query string `json:"query"` + Description string `json:"description"` + LogStoreName string `json:"logStoreName"` + LogStreamName string `json:"logStreamName"` +} + +type ListFastQueryResult struct { + Order string `json:"order"` + OrderBy string `json:"orderBy"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []FastQuery `json:"result"` +} + +type LogField struct { + Type string `json:"type"` + Fields map[string]LogField `json:"fields,omitempty"` +} + +type IndexFields struct { + FullText bool `json:"fulltext"` + Fields map[string]LogField `json:"fields"` +} + +type CreateLogShipperBody struct { + LogShipperName string `json:"logShipperName"` + LogStoreName string `json:"logStoreName"` + StartTime string `json:"startTime"` + DestType string `json:"destType"` + DestConfig *ShipperDestConfig `json:"destConfig"` +} + +type CreateLogShipperResponse struct { + LogShipperID string `json:"logShipperID"` +} + +type ShipperDestConfig struct { + BOSPath string `json:"BOSPath"` + PartitionFormatTS string `json:"partitionFormatTS"` + PartitionFormatLogStream bool `json:"partitionFormatLogStream"` + MaxObjectSize int64 `json:"maxObjectSize"` + CompressType string `json:"compressType"` + DeliverInterval int64 `json:"deliverInterval"` + StorageFormat string `json:"storageFormat"` + CsvHeadline bool `json:"csvHeadline"` + CsvDelimiter string `json:"csvDelimiter"` + CsvQuote string `json:"csvQuote"` + NullIdentifier string `json:"nullIdentifier"` + SelectedColumnName string `json:"selectedColumnName"` + SelectedColumnType string `json:"selectedColumnType"` +} + +type ListShipperRecordCondition struct { + SinceHours int `json:"sinceHours"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type ListShipperRecordResult struct { + TotalCount int `json:"totalCount"` + Result []LogShipperRecord `json:"result"` +} + +type LogShipperRecord struct { + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + FinishedCount int `json:"finishedCount"` +} + +type ListShipperResult struct { + TotalCount int `json:"totalCount"` + Result []ShipperSummary `json:"result"` +} + +type ShipperSummary struct { + LogShipperID string `json:"logShipperID"` + LogShipperName string `json:"logShipperName"` + LogStoreName string `json:"logStoreName"` + DestType string `json:"destType"` + Status string `json:"status"` + ErrMessage string `json:"errMessage"` + CreateDateTime string `json:"createDateTime"` +} + +type ListLogShipperCondition struct { + LogShipperID string `json:"logShipperID"` + LogShipperName string `json:"logShipperName"` + LogStoreName string `json:"logStoreName"` + DestType string `json:"destType"` + Status string `json:"status"` + Order string `json:"order"` + OrderBy string `json:"orderBy"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type UpdateLogShipperBody struct { + LogShipperName string `json:"logShipperName"` + DestConfig *ShipperDestConfig `json:"destConfig"` +} + +type BulkDeleteShipperCondition struct { + LogShipperIDs []string `json:"logShipperIDs"` +} + +type SetSingleShipperStatusCondition struct { + DesiredStatus string `json:"desiredStatus"` +} + +type BulkSetShipperStatusCondition struct { + LogShipperIDs []string `json:"logShipperIDs"` + DesiredStatus string `json:"desiredStatus"` +} diff --git a/bce-sdk-go/services/bls/api/utils.go b/bce-sdk-go/services/bls/api/utils.go new file mode 100644 index 0000000..323b2ea --- /dev/null +++ b/bce-sdk-go/services/bls/api/utils.go @@ -0,0 +1,63 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BLS service + +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + LOGSTORE_PREFIX = bce.URI_PREFIX + "v1" + bce.URI_PREFIX + "logstore" + FASTQUERY_PREFIX = bce.URI_PREFIX + "v1" + bce.URI_PREFIX + "fastquery" + LOGSHIPPER_PREFIX = bce.URI_PREFIX + "v1" + bce.URI_PREFIX + "logshipper" +) + +func getLogStoreUri(logStoreName string) string { + return LOGSTORE_PREFIX + bce.URI_PREFIX + logStoreName +} + +func getLogStreamName(logStoreName string) string { + return getLogStoreUri(logStoreName) + bce.URI_PREFIX + "logstream" +} + +func getLogRecordUri(logStoreName string) string { + return getLogStoreUri(logStoreName) + bce.URI_PREFIX + "logrecord" +} + +func getFastQueryUri(fastQuery string) string { + return FASTQUERY_PREFIX + bce.URI_PREFIX + fastQuery +} + +func getIndexUri(logStoreName string) string { + return getLogStoreUri(logStoreName) + bce.URI_PREFIX + "index" +} + +func getLogShipperUri(logShipperID string) string { + return LOGSHIPPER_PREFIX + bce.URI_PREFIX + logShipperID +} + +func getLogShipperRecordUri(logShipperID string) string { + return getLogShipperUri(logShipperID) + bce.URI_PREFIX + "record" +} + +func getLogShipperStatusUri(logShipperID string) string { + return getLogShipperUri(logShipperID) + bce.URI_PREFIX + "status" +} + +func getBulkSetLogShipperStatusUri() string { + return LOGSHIPPER_PREFIX + bce.URI_PREFIX + "status" + bce.URI_PREFIX + "batch" +} diff --git a/bce-sdk-go/services/bls/client.go b/bce-sdk-go/services/bls/client.go new file mode 100644 index 0000000..28715a9 --- /dev/null +++ b/bce-sdk-go/services/bls/client.go @@ -0,0 +1,286 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BLS service + +// Package bls defines the BLS services of BCE. The supported APIs are all defined in sub-package +// model with five types: 5 LogStore APIs, 1 LogStream API, 3 logRecord APIs, 5 FastQuery APIs +// and 3 index APIs. + +package bls + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bls/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "bls-log.bj.baidubce.com" +) + +type Client struct { + *bce.BceClient +} + +type BlsClientConfiguration struct { + Ak string + Sk string + Endpoint string +} + +func NewClient(ak, sk, endpoint string) (*Client, error) { + return NewClientWithConfig(&BlsClientConfiguration{ + Ak: ak, + Sk: sk, + Endpoint: endpoint, + }) +} + +func NewClientWithConfig(config *BlsClientConfiguration) (*Client, error) { + ak, sk, endpoint := config.Ak, config.Sk, config.Endpoint + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + client, _ := bce.NewBceClientWithAkSk(ak, sk, endpoint) + return &Client{client}, nil +} + +// LogStore opts +func (c *Client) CreateLogStore(logStore string, retention int) error { + params, jsonErr := json.Marshal(&api.LogStore{ + LogStoreName: logStore, + Retention: retention, + }) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return err + } + return api.CreateLogStore(c, body) +} + +func (c *Client) UpdateLogStore(logStore string, retention int) error { + param, jsonErr := json.Marshal(&api.LogStore{ + Retention: retention, + }) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(param)) + if err != nil { + return err + } + return api.UpdateLogStore(c, logStore, body) +} + +func (c *Client) DescribeLogStore(logStore string) (*api.LogStore, error) { + return api.DescribeLogStore(c, logStore) +} + +func (c *Client) DeleteLogStore(logStore string) error { + return api.DeleteLogStore(c, logStore) +} + +func (c *Client) ListLogStore(args *api.QueryConditions) (*api.ListLogStoreResult, error) { + return api.ListLogStore(c, args) +} + +// LogStream opt +func (c *Client) ListLogStream(logStore string, args *api.QueryConditions) (*api.ListLogStreamResult, error) { + return api.ListLogStream(c, logStore, args) +} + +// LogRecord opts +func (c *Client) PushLogRecord(logStore string, logStream string, logType string, logRecords []api.LogRecord) error { + params, jsonErr := json.Marshal(&api.PushLogRecordBody{ + LogStreamName: logStream, + Type: logType, + LogRecords: logRecords, + }) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return err + } + return api.PushLogRecord(c, logStore, body) +} + +func (c *Client) PullLogRecord(logStore string, args *api.PullLogRecordArgs) (*api.PullLogRecordResult, error) { + return api.PullLogRecord(c, logStore, args) +} + +func (c *Client) QueryLogRecord(logStore string, args *api.QueryLogRecordArgs) (*api.QueryLogResult, error) { + return api.QueryLogRecord(c, logStore, args) +} + +// FastQuery opts +func (c *Client) CreateFastQuery(args *api.CreateFastQueryBody) error { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return nil + } + return api.CreateFastQuery(c, body) +} + +func (c *Client) DescribeFastQuery(fastQueryName string) (*api.FastQuery, error) { + return api.DescribeFastQuery(c, fastQueryName) +} + +func (c *Client) UpdateFastQuery(fastQueryName string, args *api.UpdateFastQueryBody) error { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return nil + } + return api.UpdateFastQuery(c, body, fastQueryName) +} + +func (c *Client) DeleteFastQuery(fastQueryName string) error { + return api.DeleteFastQuery(c, fastQueryName) +} + +func (c *Client) ListFastQuery(args *api.QueryConditions) (*api.ListFastQueryResult, error) { + return api.ListFastQuery(c, args) +} + +// Index opts +func (c *Client) CreateIndex(logStore string, fulltext bool, fields map[string]api.LogField) error { + params, jsonErr := json.Marshal(&api.IndexFields{ + FullText: fulltext, + Fields: fields, + }) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return err + } + return api.CreateIndex(c, logStore, body) +} + +func (c *Client) UpdateIndex(logStore string, fulltext bool, fields map[string]api.LogField) error { + params, jsonErr := json.Marshal(&api.IndexFields{ + FullText: fulltext, + Fields: fields, + }) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return err + } + return api.UpdateIndex(c, logStore, body) +} + +func (c *Client) DeleteIndex(logStore string) error { + return api.DeleteIndex(c, logStore) +} + +func (c *Client) DescribeIndex(logStore string) (*api.IndexFields, error) { + return api.DescribeIndex(c, logStore) +} + +// LogShipper opts +func (c *Client) ListLogShipper(args *api.ListLogShipperCondition) (*api.ListShipperResult, error) { + return api.ListLogShipper(c, args) +} + +func (c *Client) CreateLogShipper(args *api.CreateLogShipperBody) (string, error) { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + + return "", jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + + return "", nil + } + return api.CreateLogShipper(c, body) +} + +func (c *Client) UpdateLogShipper(logShipperID string, args *api.UpdateLogShipperBody) error { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return nil + } + return api.UpdateLogShipper(c, body, logShipperID) +} + +func (c *Client) GetLogShipper(logShipperID string) (*api.LogShipper, error) { + return api.GetLogShipper(c, logShipperID) +} + +func (c *Client) ListLogShipperRecord(logShipperID string, args *api.ListShipperRecordCondition) (*api.ListShipperRecordResult, error) { + return api.ListLogShipperRecord(c, logShipperID, args) +} + +func (c *Client) DeleteSingleLogShipper(logShipperID string) error { + return api.DeleteSingleLogShipper(c, logShipperID) +} + +func (c *Client) BulkDeleteLogShipper(args *api.BulkDeleteShipperCondition) error { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return nil + } + return api.BulkDeleteLogShipper(c, body) +} + +func (c *Client) SetSingleLogShipperStatus(logShipperID string, args *api.SetSingleShipperStatusCondition) error { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return nil + } + return api.SetSingleLogShipperStatus(c, logShipperID, body) +} + +func (c *Client) BulkSetLogShipperStatus(args *api.BulkSetShipperStatusCondition) error { + params, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromString(string(params)) + if err != nil { + return nil + } + return api.BulkSetLogShipperStatus(c, body) +} diff --git a/bce-sdk-go/services/bls/client_test.go b/bce-sdk-go/services/bls/client_test.go new file mode 100644 index 0000000..a98465c --- /dev/null +++ b/bce-sdk-go/services/bls/client_test.go @@ -0,0 +1,549 @@ +package bls + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bls/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BLS_CLIENT *Client + EXIST_LOGSTORE = "bls-rd-wzy" + LOGSTREAM_PATTERN = "wzy" + JSON_LOGSTREAM = LOGSTREAM_PATTERN + "-JSON" + TEXT_LOGSTREAM = LOGSTREAM_PATTERN + "-TEXT" + FASTQUERY_NAME = "speedo" + LOGSHIPPER_NAME = "test-bls-sdk" + TEST_STARTTIME = "2021-07-06T19:01:00Z" + LOGSHIPPER_ID = "MjI3NDY5OTE5MTk3MzE1MDcy" + DEAFAULT_LOGSTORE = "ng-log" + DEAFAULT_BOSPATH = "/bls-test/bls-sdk/" + DEFAULT_TEST_DOMAIN = "10.132.106.242" +) + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given: %+v\n", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &BlsClientConfiguration{} + err = decoder.Decode(confObj) + if err != nil { + fmt.Println(err) + return + } + // default use http protocol + BLS_CLIENT, _ = NewClient(confObj.Ak, confObj.Sk, DEFAULT_TEST_DOMAIN) + // log.SetLogHandler(log.STDERR | log.FILE) + // log.SetRotateType(log.ROTATE_SIZE) + log.SetLogLevel(log.WARN) + // log.SetLogHandler(log.STDERR) + // log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + actual interface{}, expected interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +// LogStore test +func TestCreateLogStore(t *testing.T) { + err := BLS_CLIENT.CreateLogStore(EXIST_LOGSTORE, 3) + ExpectEqual(t.Errorf, err, nil) + err = BLS_CLIENT.CreateLogStore(EXIST_LOGSTORE, 36) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusConflict) + } + res, err := BLS_CLIENT.DescribeLogStore(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.LogStoreName, EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res.Retention, 3) +} + +func TestUpdateLogStore(t *testing.T) { + err := BLS_CLIENT.UpdateLogStore(EXIST_LOGSTORE, 8) + ExpectEqual(t.Errorf, err, nil) + res, err := BLS_CLIENT.DescribeLogStore(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.LogStoreName, EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res.Retention, 8) + err = BLS_CLIENT.UpdateLogStore("not"+EXIST_LOGSTORE, 22) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestDescribeLogStore(t *testing.T) { + res, err := BLS_CLIENT.DescribeLogStore(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.LogStoreName, EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res.Retention, 8) + res, err = BLS_CLIENT.DescribeLogStore("not" + EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res, nil) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestListLogStore(t *testing.T) { + args := &api.QueryConditions{ + NamePattern: "bls-rd", + Order: "asc", + OrderBy: "creationDateTime", + PageNo: 1, + PageSize: 10} + res, err := BLS_CLIENT.ListLogStore(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, len(res.Result) > 0, true) +} + +// LogRecord test +func TestPushLogRecord(t *testing.T) { + jsonRecords := []api.LogRecord{ + { + Message: "{\"body_bytes_sent\":184,\"bytes_sent\":398,\"client_ip\":\"120.193.204.39\",\"connection\":915958195,\"hit\":1,\"host\":\"cdbb.wonter.net\"}", + Timestamp: time.Now().UnixNano() / 1e6, + Sequence: 1, + }, + { + Message: "{\"body_bytes_sent\":14,\"bytes_sent\":408,\"client_ip\":\"120.193.222.39\",\"connection\":91567195,\"hit\":1,\"host\":\"cdbb.wonter.net\"}", + Timestamp: time.Now().UnixNano() / 1e6, + Sequence: 2, + }, + } + err := BLS_CLIENT.PushLogRecord(EXIST_LOGSTORE, JSON_LOGSTREAM, "JSON", jsonRecords) + ExpectEqual(t.Errorf, err, nil) + textRecords := []api.LogRecord{ + { + Message: "You know, for test", + Timestamp: time.Now().UnixNano() / 1e6, + Sequence: 3, + }, + { + Message: "Baidu Log Service", + Timestamp: time.Now().UnixNano() / 1e6, + Sequence: 4, + }, + } + err = BLS_CLIENT.PushLogRecord(EXIST_LOGSTORE, TEXT_LOGSTREAM, "TEXT", textRecords) + ExpectEqual(t.Errorf, err, nil) + tooNewRecord := []api.LogRecord{ + { + "LogRecord from future", + time.Now().UnixNano() / 1e4, + 12, + }, + } + err = BLS_CLIENT.PushLogRecord(EXIST_LOGSTORE, TEXT_LOGSTREAM, "TEXT", tooNewRecord) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusBadRequest) + } + err = BLS_CLIENT.PushLogRecord("not"+EXIST_LOGSTORE, TEXT_LOGSTREAM, "TEXT", textRecords) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestPullLogRecord(t *testing.T) { + args := &api.PullLogRecordArgs{ + LogStreamName: JSON_LOGSTREAM, + StartDateTime: "2021-01-01T10:11:44Z", + EndDateTime: "2021-12-10T16:11:44Z", + Limit: 500, + Marker: "", + } + res, err := BLS_CLIENT.PullLogRecord(EXIST_LOGSTORE, args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, len(res.Result) >= 2, true) + res, err = BLS_CLIENT.PullLogRecord("not"+EXIST_LOGSTORE, args) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + ExpectEqual(t.Errorf, res, nil) + } +} + +func TestQueryLogRecord(t *testing.T) { + args := &api.QueryLogRecordArgs{ + LogStreamName: JSON_LOGSTREAM, + Query: "select count(*)", + StartDateTime: "2021-01-01T10:11:44Z", + EndDateTime: "2021-12-10T16:11:44Z", + } + res, err := BLS_CLIENT.QueryLogRecord(EXIST_LOGSTORE, args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.ResultSet.Columns[0], "count(*)") +} + +// LogStream test +func TestListLogStream(t *testing.T) { + args := &api.QueryConditions{ + NamePattern: LOGSTREAM_PATTERN, + Order: "asc", + OrderBy: "creationDateTime", + PageNo: 1, + PageSize: 23, + } + res, err := BLS_CLIENT.ListLogStream(EXIST_LOGSTORE, args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.PageSize, 23) + res, err = BLS_CLIENT.ListLogStream("not"+EXIST_LOGSTORE, args) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + ExpectEqual(t.Errorf, res, nil) + } +} + +// FastQuery test +func TestCreateFastQuery(t *testing.T) { + args := &api.CreateFastQueryBody{ + FastQueryName: FASTQUERY_NAME, + Query: "select count(*)", + Description: "calculate record number", + LogStoreName: EXIST_LOGSTORE, + LogStreamName: JSON_LOGSTREAM, + } + err := BLS_CLIENT.CreateFastQuery(args) + ExpectEqual(t.Errorf, err, nil) + // Not specify logStream + err = BLS_CLIENT.CreateFastQuery(&api.CreateFastQueryBody{ + FastQueryName: FASTQUERY_NAME, + Query: "select count(*)", + Description: "duplicate", + LogStoreName: EXIST_LOGSTORE, + LogStreamName: "", + }) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusConflict) + } +} + +func TestDescribeFastQuery(t *testing.T) { + res, err := BLS_CLIENT.DescribeFastQuery(FASTQUERY_NAME) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.FastQueryName, FASTQUERY_NAME) + res, err = BLS_CLIENT.DescribeFastQuery("not" + FASTQUERY_NAME) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + ExpectEqual(t.Errorf, res, nil) + } +} + +func TestUpdateFastQuery(t *testing.T) { + args := &api.UpdateFastQueryBody{ + Query: "select * limit 3", + Description: "Top 3", + LogStoreName: EXIST_LOGSTORE, + LogStreamName: JSON_LOGSTREAM, + } + err := BLS_CLIENT.UpdateFastQuery(FASTQUERY_NAME, args) + ExpectEqual(t.Errorf, err, nil) + res, err := BLS_CLIENT.DescribeFastQuery(FASTQUERY_NAME) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Query, "select * limit 3") + err = BLS_CLIENT.UpdateFastQuery("not"+FASTQUERY_NAME, &api.UpdateFastQueryBody{ + Query: "select * limit 3", + Description: "return top 3 records", + LogStoreName: EXIST_LOGSTORE, + LogStreamName: "", + }) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestListFastQuery(t *testing.T) { + args := &api.QueryConditions{ + NamePattern: "s", + } + res, err := BLS_CLIENT.ListFastQuery(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, len(res.Result) >= 1, true) +} + +func TestDeleteFastQuery(t *testing.T) { + err := BLS_CLIENT.DeleteFastQuery(FASTQUERY_NAME) + ExpectEqual(t.Errorf, err, nil) + res, err := BLS_CLIENT.DescribeFastQuery(FASTQUERY_NAME) + ExpectEqual(t.Errorf, res, nil) + err = BLS_CLIENT.DeleteFastQuery("not" + FASTQUERY_NAME) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +// Index test +func TestCreateIndex(t *testing.T) { + fields := map[string]api.LogField{ + "age": { + Type: "long", + }, + "salary": { + Type: "text", + }, + "name": { + Type: "object", + Fields: map[string]api.LogField{ + "firstName": { + Type: "text", + }, + "lastName": { + Type: "text", + }, + }, + }, + } + err := BLS_CLIENT.CreateIndex(EXIST_LOGSTORE, true, fields) + ExpectEqual(t.Errorf, err, nil) + err = BLS_CLIENT.CreateIndex(EXIST_LOGSTORE, true, fields) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusConflict) + } +} + +func TestUpdateIndex(t *testing.T) { + fields := map[string]api.LogField{ + "age": { + Type: "long", + }, + "wage": { + Type: "float", + }, + "name": { + Type: "object", + Fields: map[string]api.LogField{ + "firstName": { + Type: "text", + }, + "midName": { + Type: "text", + }, + "lastName": { + Type: "text", + }, + }, + }, + } + err := BLS_CLIENT.UpdateIndex(EXIST_LOGSTORE, false, fields) + ExpectEqual(t.Errorf, err, nil) + err = BLS_CLIENT.UpdateIndex("not"+EXIST_LOGSTORE, false, fields) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestDescribeIndex(t *testing.T) { + res, err := BLS_CLIENT.DescribeIndex(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Fields["name"].Fields["midName"].Type, "text") + ExpectEqual(t.Errorf, res.Fields["wage"].Type, "float") + res, err = BLS_CLIENT.DescribeIndex("not" + EXIST_LOGSTORE) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + ExpectEqual(t.Errorf, res, nil) + } +} + +func TestDeleteIndex(t *testing.T) { + err := BLS_CLIENT.DeleteIndex(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + res, _ := BLS_CLIENT.DescribeIndex(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res, nil) + err = BLS_CLIENT.DeleteIndex(EXIST_LOGSTORE) // delete twice + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestDeleteLogStore(t *testing.T) { + res, err := BLS_CLIENT.DescribeLogStore(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.LogStoreName, EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res.Retention, 8) + err = BLS_CLIENT.DeleteLogStore(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, err, nil) + res, err = BLS_CLIENT.DescribeLogStore(EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res, nil) + res, err = BLS_CLIENT.DescribeLogStore("not" + EXIST_LOGSTORE) + ExpectEqual(t.Errorf, res, nil) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestClient_CreateLogShipper(t *testing.T) { + args := &api.CreateLogShipperBody{ + LogShipperName: LOGSHIPPER_NAME, + LogStoreName: DEAFAULT_LOGSTORE, + StartTime: TEST_STARTTIME, + DestConfig: &api.ShipperDestConfig{ + BOSPath: DEAFAULT_BOSPATH, + }, + } + id, err := BLS_CLIENT.CreateLogShipper(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, len(id) > 0, true) + args = &api.CreateLogShipperBody{ + LogShipperName: "invalid", + LogStoreName: "not-exist", + DestConfig: &api.ShipperDestConfig{}, + } + id, err = BLS_CLIENT.CreateLogShipper(args) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusBadRequest) + ExpectEqual(t.Errorf, id, "") + } +} + +func TestClient_UpdateLogShipper(t *testing.T) { + args := &api.UpdateLogShipperBody{ + LogShipperName: "shipper-sdk", + DestConfig: &api.ShipperDestConfig{ + PartitionFormatLogStream: true, + MaxObjectSize: 50, + CompressType: "snappy", + DeliverInterval: 30, + StorageFormat: "json", + }, + } + err := BLS_CLIENT.UpdateLogShipper(LOGSHIPPER_ID, args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestClient_GetLogShipper(t *testing.T) { + logShipper, err := BLS_CLIENT.GetLogShipper(LOGSHIPPER_ID) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, logShipper.LogStoreName, DEAFAULT_LOGSTORE) + ExpectEqual(t.Errorf, logShipper.DestConfig.BOSPath, DEAFAULT_BOSPATH) +} + +func TestClient_ListLogShipper(t *testing.T) { + args := &api.ListLogShipperCondition{ + LogShipperID: LOGSHIPPER_ID, + LogStoreName: DEAFAULT_LOGSTORE, + Status: "Running", + } + shipperInfo, err := BLS_CLIENT.ListLogShipper(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, shipperInfo.TotalCount, 1) +} + +func TestClient_ListLogShipperRecord(t *testing.T) { + args := &api.ListShipperRecordCondition{ + SinceHours: 20 * 24, + } + records, err := BLS_CLIENT.ListLogShipperRecord(LOGSHIPPER_ID, args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, records.TotalCount > 0, true) + ExpectEqual(t.Errorf, records.Result[0].FinishedCount > 0, true) +} + +func TestClient_SetSingleLogShipperStatus(t *testing.T) { + args := &api.SetSingleShipperStatusCondition{DesiredStatus: "Paused"} + err := BLS_CLIENT.SetSingleLogShipperStatus(LOGSHIPPER_ID, args) + ExpectEqual(t.Errorf, err, nil) + logShipper, err := BLS_CLIENT.GetLogShipper(LOGSHIPPER_ID) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, logShipper.Status, "Paused") +} + +func TestClient_BulkSetLogShipperStatus(t *testing.T) { + args := &api.BulkSetShipperStatusCondition{ + LogShipperIDs: []string{LOGSHIPPER_ID}, + DesiredStatus: "Running", + } + err := BLS_CLIENT.BulkSetLogShipperStatus(args) + ExpectEqual(t.Errorf, err, nil) + logShipper, err := BLS_CLIENT.GetLogShipper(LOGSHIPPER_ID) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, logShipper.Status, "Running") +} + +func TestClient_DeleteSingleLogShipper(t *testing.T) { + args := &api.CreateLogShipperBody{ + LogShipperName: LOGSHIPPER_NAME, + LogStoreName: DEAFAULT_LOGSTORE, + StartTime: TEST_STARTTIME, + DestConfig: &api.ShipperDestConfig{ + BOSPath: DEAFAULT_BOSPATH, + }, + } + id, err := BLS_CLIENT.CreateLogShipper(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, len(id) > 0, true) + time.Sleep(2 * time.Second) + err = BLS_CLIENT.DeleteSingleLogShipper(id) + ExpectEqual(t.Errorf, err, nil) + logShipper, err := BLS_CLIENT.GetLogShipper(id) + ExpectEqual(t.Errorf, logShipper, nil) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } +} + +func TestClient_BulkDeleteLogShipper(t *testing.T) { + var ids []string + for i := 0; i < 3; i++ { + args := &api.CreateLogShipperBody{ + LogShipperName: LOGSHIPPER_NAME, + LogStoreName: DEAFAULT_LOGSTORE, + StartTime: TEST_STARTTIME, + DestConfig: &api.ShipperDestConfig{ + BOSPath: DEAFAULT_BOSPATH, + }, + } + id, err := BLS_CLIENT.CreateLogShipper(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, len(id) > 0, true) + ids = append(ids, id) + } + time.Sleep(time.Second * 2) + args := &api.BulkDeleteShipperCondition{LogShipperIDs: ids} + err := BLS_CLIENT.BulkDeleteLogShipper(args) + ExpectEqual(t.Errorf, err, nil) + for _, id := range ids { + logShipper, err := BLS_CLIENT.GetLogShipper(id) + ExpectEqual(t.Errorf, logShipper, nil) + if realErr, ok := err.(*bce.BceServiceError); ok { + ExpectEqual(t.Errorf, realErr.StatusCode, http.StatusNotFound) + } + } +} diff --git a/bce-sdk-go/services/bos/api/bucket.go b/bce-sdk-go/services/bos/api/bucket.go new file mode 100644 index 0000000..e3fd6a1 --- /dev/null +++ b/bce-sdk-go/services/bos/api/bucket.go @@ -0,0 +1,1241 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// bucket.go - the bucket APIs definition supported by the BOS service + +// Package api defines all APIs supported by the BOS service of BCE. +package api + +import ( + "encoding/json" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListBuckets - list all buckets of the account +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *ListBucketsResult: the result bucket list structure +// - error: nil if ok otherwise the specific error +func ListBuckets(cli bce.Client) (*ListBucketsResult, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListBucketsResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// ListObjects - list all objects of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - args: the optional arguments to list objects +// +// RETURNS: +// - *ListObjectsResult: the result object list structure +// - error: nil if ok otherwise the specific error +func ListObjects(cli bce.Client, bucket string, + args *ListObjectsArgs) (*ListObjectsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + if len(args.Delimiter) != 0 { + req.SetParam("delimiter", args.Delimiter) + } + if len(args.Marker) != 0 { + req.SetParam("marker", args.Marker) + } + if args.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(args.MaxKeys)) + } + if len(args.Prefix) != 0 { + req.SetParam("prefix", args.Prefix) + } + } + if args == nil || args.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send the request and get result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListObjectsResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return result, nil +} + +// HeadBucket - test the given bucket existed and access authority +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if exists and have authority otherwise the specific error +func HeadBucket(cli bce.Client, bucket string) (error, *bce.BceResponse) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.HEAD) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err, resp + } + if resp.IsFail() { + return resp.ServiceError(), resp + } + defer func() { resp.Body().Close() }() + return nil, resp +} + +// PutBucket - create a new bucket with the given name +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the new bucket name +// +// RETURNS: +// - string: the location of the new bucket if create success +// - error: nil if create success otherwise the specific error +func PutBucket(cli bce.Client, bucket string) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return resp.Header(http.LOCATION), nil +} + +// DeleteBucket - delete an empty bucket by given name +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name to be deleted +// +// RETURNS: +// - error: nil if delete success otherwise the specific error +func DeleteBucket(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketLocation - get the location of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - string: the location of the bucket +// - error: nil if delete success otherwise the specific error +func GetBucketLocation(cli bce.Client, bucket string) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("location", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + result := &LocationType{} + if err := resp.ParseJsonBody(result); err != nil { + return "", err + } + defer func() { resp.Body().Close() }() + return result.LocationConstraint, nil +} + +// PutBucketAcl - set the acl of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - cannedAcl: support private, public-read, public-read-write +// - aclBody: the acl file body +// +// RETURNS: +// - error: nil if delete success otherwise the specific error +func PutBucketAcl(cli bce.Client, bucket, cannedAcl string, aclBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("acl", "") + + // The acl setting + if len(cannedAcl) != 0 && aclBody != nil { + return bce.NewBceClientError("BOS does not support cannedAcl and acl file at the same time") + } + if validCannedAcl(cannedAcl) { + req.SetHeader(http.BCE_ACL, cannedAcl) + } + if aclBody != nil { + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(aclBody) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketAcl - get the acl of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - *GetBucketAclResult: the result of the bucket acl +// - error: nil if success otherwise the specific error +func GetBucketAcl(cli bce.Client, bucket string) (*GetBucketAclResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("acl", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketAclResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return result, nil +} + +// PutBucketLogging - set the logging prefix of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - logging: the logging prefix json string body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketLogging(cli bce.Client, bucket string, logging *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("logging", "") + req.SetBody(logging) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketLogging - get the logging config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - *GetBucketLoggingResult: the logging setting of the bucket +// - error: nil if success otherwise the specific error +func GetBucketLogging(cli bce.Client, bucket string) (*GetBucketLoggingResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("logging", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketLoggingResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteBucketLogging - delete the logging setting of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketLogging(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("logging", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutBucketLifecycle - set the lifecycle rule of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - lifecycle: the lifecycle rule json string body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketLifecycle(cli bce.Client, bucket string, lifecycle *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("lifecycle", "") + req.SetBody(lifecycle) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketLifecycle - get the lifecycle rule of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - *GetBucketLifecycleResult: the lifecycle rule of the bucket +// - error: nil if success otherwise the specific error +func GetBucketLifecycle(cli bce.Client, bucket string) (*GetBucketLifecycleResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("lifecycle", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketLifecycleResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteBucketLifecycle - delete the lifecycle rule of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketLifecycle(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("lifecycle", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutBucketStorageclass - set the storage class of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - storageClass: the storage class string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketStorageclass(cli bce.Client, bucket, storageClass string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("storageClass", "") + + obj := &StorageClassType{storageClass} + jsonBytes, jsonErr := json.Marshal(obj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketStorageclass - get the storage class of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - string: the storage class of the bucket +// - error: nil if success otherwise the specific error +func GetBucketStorageclass(cli bce.Client, bucket string) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("storageClass", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + result := &StorageClassType{} + if err := resp.ParseJsonBody(result); err != nil { + return "", err + } + return result.StorageClass, nil +} + +// PutBucketReplication - set the bucket replication of different region +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - replicationConf: the replication config body stream +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketReplication(cli bce.Client, bucket string, replicationConf *bce.Body, replicationRuleId string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("replication", "") + if len(replicationRuleId) > 0 { + req.SetParam("id", replicationRuleId) + } + + if replicationConf != nil { + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(replicationConf) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketReplication - get the bucket replication config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - *GetBucketReplicationResult: the result of the bucket replication config +// - error: nil if success otherwise the specific error +func GetBucketReplication(cli bce.Client, bucket string, replicationRuleId string) (*GetBucketReplicationResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("replication", "") + if len(replicationRuleId) > 0 { + req.SetParam("id", replicationRuleId) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketReplicationResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// ListBucketReplication - list all replication config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func ListBucketReplication(cli bce.Client, bucket string) (*ListBucketReplicationResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("replication", "") + req.SetParam("list", "") + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListBucketReplicationResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteBucketReplication - delete the bucket replication config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketReplication(cli bce.Client, bucket string, replicationRuleId string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("replication", "") + if len(replicationRuleId) > 0 { + req.SetParam("id", replicationRuleId) + } + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketReplicationProgress - get the bucket replication process of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - *GetBucketReplicationProgressResult: the result of the bucket replication process +// - error: nil if success otherwise the specific error +func GetBucketReplicationProgress(cli bce.Client, bucket string, replicationRuleId string) ( + *GetBucketReplicationProgressResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("replicationProgress", "") + if len(replicationRuleId) > 0 { + req.SetParam("id", replicationRuleId) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketReplicationProgressResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// PutBucketEncryption - set the bucket encrpytion config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - algorithm: the encryption algorithm +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketEncryption(cli bce.Client, bucket, algorithm string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("encryption", "") + + obj := &BucketEncryptionType{algorithm} + jsonBytes, jsonErr := json.Marshal(obj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketEncryption - get the encryption config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - algorithm: the bucket encryption algorithm +// - error: nil if success otherwise the specific error +func GetBucketEncryption(cli bce.Client, bucket string) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("encryption", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + result := &BucketEncryptionType{} + if err := resp.ParseJsonBody(result); err != nil { + return "", err + } + return result.EncryptionAlgorithm, nil +} + +// DeleteBucketEncryption - delete the encryption config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketEncryption(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("encryption", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutBucketStaticWebsite - set the bucket static website config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - confBody: the static website config body stream +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketStaticWebsite(cli bce.Client, bucket string, confBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("website", "") + if confBody != nil { + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(confBody) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketStaticWebsite - get the static website config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - result: the bucket static website config result object +// - error: nil if success otherwise the specific error +func GetBucketStaticWebsite(cli bce.Client, bucket string) ( + *GetBucketStaticWebsiteResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("website", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketStaticWebsiteResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteBucketStaticWebsite - delete the static website config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketStaticWebsite(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("website", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutBucketCors - set the bucket CORS config +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - confBody: the CORS config body stream +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketCors(cli bce.Client, bucket string, confBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("cors", "") + if confBody != nil { + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(confBody) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketCors - get the CORS config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - result: the bucket CORS config result object +// - error: nil if success otherwise the specific error +func GetBucketCors(cli bce.Client, bucket string) ( + *GetBucketCorsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("cors", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketCorsResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteBucketCors - delete the CORS config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketCors(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("cors", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutBucketCopyrightProtection - set the copyright protection config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - resources: the resource items in the bucket to be protected +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketCopyrightProtection(cli bce.Client, bucket string, resources ...string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("copyrightProtection", "") + if len(resources) == 0 { + return bce.NewBceClientError("the resource to set copyright protection is empty") + } + arg := &CopyrightProtectionType{resources} + jsonBytes, jsonErr := json.Marshal(arg) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetBucketCopyrightProtection - get the copyright protection config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - result: the bucket copyright protection resources array +// - error: nil if success otherwise the specific error +func GetBucketCopyrightProtection(cli bce.Client, bucket string) ([]string, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("copyrightProtection", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CopyrightProtectionType{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result.Resource, nil +} + +// DeleteBucketCopyrightProtection - delete the copyright protection config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteBucketCopyrightProtection(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("copyrightProtection", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutBucketTrash - put the trash setting of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - trashDir: the trash dir name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutBucketTrash(cli bce.Client, bucket string, trashReq PutBucketTrashReq) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("trash", "") + reqByte, _ := json.Marshal(trashReq) + body, err := bce.NewBodyFromString(string(reqByte)) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func GetBucketTrash(cli bce.Client, bucket string) (*GetBucketTrashResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("trash", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetBucketTrashResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func DeleteBucketTrash(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("trash", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func PutBucketNotification(cli bce.Client, bucket string, putBucketNotificationReq PutBucketNotificationReq) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("notification", "") + reqByte, _ := json.Marshal(putBucketNotificationReq) + body, err := bce.NewBodyFromString(string(reqByte)) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func GetBucketNotification(cli bce.Client, bucket string) (*PutBucketNotificationReq, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("notification", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &PutBucketNotificationReq{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func DeleteBucketNotification(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("notification", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func PutBucketMirror(cli bce.Client, bucket string, putBucketMirrorArgs *PutBucketMirrorArgs) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("mirroring", "") + reqByte, _ := json.Marshal(putBucketMirrorArgs) + body, err := bce.NewBodyFromString(string(reqByte)) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func GetBucketMirror(cli bce.Client, bucket string) (*PutBucketMirrorArgs, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("mirroring", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &PutBucketMirrorArgs{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func DeleteBucketMirror(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("mirroring", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func PutBucketTag(cli bce.Client, bucket string, putBucketTagArgs *PutBucketTagArgs) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.PUT) + req.SetParam("tagging", "") + reqByte, _ := json.Marshal(putBucketTagArgs) + body, err := bce.NewBodyFromString(string(reqByte)) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func GetBucketTag(cli bce.Client, bucket string) (*PutBucketTagArgs, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("tagging", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &PutBucketTagArgs{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func DeleteBucketTag(cli bce.Client, bucket string) error { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.DELETE) + req.SetParam("tagging", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} diff --git a/bce-sdk-go/services/bos/api/model.go b/bce-sdk-go/services/bos/api/model.go new file mode 100644 index 0000000..8c37ee4 --- /dev/null +++ b/bce-sdk-go/services/bos/api/model.go @@ -0,0 +1,622 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +import ( + "io" +) + +type OwnerType struct { + Id string `json:"id"` + DisplayName string `json:"displayName"` +} + +type BucketSummaryType struct { + Name string `json:"name"` + Location string `json:"location"` + CreationDate string `json:"creationDate"` +} + +// ListBucketsResult defines the result structure of ListBuckets api. +type ListBucketsResult struct { + Owner OwnerType `json:"owner"` + Buckets []BucketSummaryType `json:"buckets"` +} + +// ListObjectsArgs defines the optional arguments for ListObjects api. +type ListObjectsArgs struct { + Delimiter string `json:"delimiter"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + Prefix string `json:"prefix"` +} + +type ObjectSummaryType struct { + Key string `json:"key"` + LastModified string `json:"lastModified"` + ETag string `json:"eTag"` + Size int `json:"size"` + StorageClass string `json:"storageClass"` + Owner OwnerType `json:"owner"` +} + +type PrefixType struct { + Prefix string `json:"prefix"` +} + +// ListObjectsResult defines the result structure of ListObjects api. +type ListObjectsResult struct { + Name string `json:"name"` + Prefix string `json:"prefix"` + Delimiter string `json:"delimiter"` + Marker string `json:"marker"` + NextMarker string `json:"nextMarker,omitempty"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + Contents []ObjectSummaryType `json:"contents"` + CommonPrefixes []PrefixType `json:"commonPrefixes"` +} + +type LocationType struct { + LocationConstraint string `json:"locationConstraint"` +} + +// AclOwnerType defines the owner struct in ACL setting +type AclOwnerType struct { + Id string `json:"id"` +} + +// GranteeType defines the grantee struct in ACL setting +type GranteeType struct { + Id string `json:"id"` +} + +type AclRefererType struct { + StringLike []string `json:"stringLike"` + StringEquals []string `json:"stringEquals"` +} + +type AclCondType struct { + IpAddress []string `json:"ipAddress"` + Referer AclRefererType `json:"referer"` +} + +// GrantType defines the grant struct in ACL setting +type GrantType struct { + Grantee []GranteeType `json:"grantee"` + Permission []string `json:"permission"` + Resource []string `json:"resource,omitempty"` + NotResource []string `json:"notResource,omitempty"` + Condition AclCondType `json:"condition,omitempty"` + Effect string `json:"effect,omitempty"` +} + +// PutBucketAclArgs defines the input args structure for putting bucket acl. +type PutBucketAclArgs struct { + AccessControlList []GrantType `json:"accessControlList"` +} + +// GetBucketAclResult defines the result structure of getting bucket acl. +type GetBucketAclResult struct { + AccessControlList []GrantType `json:"accessControlList"` + Owner AclOwnerType `json:"owner"` +} + +// PutBucketLoggingArgs defines the input args structure for putting bucket logging. +type PutBucketLoggingArgs struct { + TargetBucket string `json:"targetBucket"` + TargetPrefix string `json:"targetPrefix"` +} + +// GetBucketLoggingResult defines the result structure for getting bucket logging. +type GetBucketLoggingResult struct { + Status string `json:"status"` + TargetBucket string `json:"targetBucket,omitempty"` + TargetPrefix string `json:"targetPrefix,omitempty"` +} + +// LifecycleConditionTimeType defines the structure of time condition +type LifecycleConditionTimeType struct { + DateGreaterThan string `json:"dateGreaterThan"` +} + +// LifecycleConditionType defines the structure of condition +type LifecycleConditionType struct { + Time LifecycleConditionTimeType `json:"time"` +} + +// LifecycleActionType defines the structure of lifecycle action +type LifecycleActionType struct { + Name string `json:"name"` + StorageClass string `json:"storageClass,omitempty"` +} + +// LifecycleRuleType defines the structure of a single lifecycle rule +type LifecycleRuleType struct { + Id string `json:"id"` + Status string `json:"status"` + Resource []string `json:"resource"` + Condition LifecycleConditionType `json:"condition"` + Action LifecycleActionType `json:"action"` +} + +// GetBucketLifecycleResult defines the lifecycle argument structure for putting +type PutBucketLifecycleArgs struct { + Rule []LifecycleRuleType `json:"rule"` +} + +// GetBucketLifecycleResult defines the lifecycle result structure for getting +type GetBucketLifecycleResult struct { + Rule []LifecycleRuleType `json:"rule"` +} + +type StorageClassType struct { + StorageClass string `json:"storageClass"` +} + +// BucketReplicationDescriptor defines the description data structure +type BucketReplicationDescriptor struct { + Bucket string `json:"bucket,omitempty"` + StorageClass string `json:"storageClass,omitempty"` +} + +// BucketReplicationType defines the data structure for Put and Get of bucket replication +type BucketReplicationType struct { + Id string `json:"id"` + Status string `json:"status"` + Resource []string `json:"resource"` + ReplicateDeletes string `json:"replicateDeletes"` + Destination *BucketReplicationDescriptor `json:"destination,omitempty"` + ReplicateHistory *BucketReplicationDescriptor `json:"replicateHistory,omitempty"` + CreateTime int64 `json:"createTime"` + DestRegion string `json:"destRegion"` +} + +type PutBucketReplicationArgs BucketReplicationType +type GetBucketReplicationResult BucketReplicationType + +// ListBucketReplicationResult defines output result for replication conf list +type ListBucketReplicationResult struct { + Rules []BucketReplicationType `json:"rules"` +} + +// GetBucketReplicationProgressResult defines output result for replication process +type GetBucketReplicationProgressResult struct { + Status string `json:"status"` + HistoryReplicationPercent float64 `json:"historyReplicationPercent"` + LatestReplicationTime string `json:"latestReplicationTime"` +} + +// BucketEncryptionType defines the data structure for Put and Get of bucket encryption +type BucketEncryptionType struct { + EncryptionAlgorithm string `json:"encryptionAlgorithm"` +} + +// BucketStaticWebsiteType defines the data structure for Put and Get of bucket static website +type BucketStaticWebsiteType struct { + Index string `json:"index"` + NotFound string `json:"notFound"` +} + +type PutBucketStaticWebsiteArgs BucketStaticWebsiteType +type GetBucketStaticWebsiteResult BucketStaticWebsiteType + +type BucketCORSType struct { + AllowedOrigins []string `json:"allowedOrigins"` + AllowedMethods []string `json:"allowedMethods"` + AllowedHeaders []string `json:"allowedHeaders,omitempty"` + AllowedExposeHeaders []string `json:"allowedExposeHeaders,omitempty"` + MaxAgeSeconds int64 `json:"maxAgeSeconds,omitempty"` +} + +// PutBucketCorsArgs defines the request argument for bucket CORS setting +type PutBucketCorsArgs struct { + CorsConfiguration []BucketCORSType `json:"corsConfiguration"` +} + +// GetBucketCorsResult defines the data structure of getting bucket CORS result +type GetBucketCorsResult struct { + CorsConfiguration []BucketCORSType `json:"corsConfiguration"` +} + +// CopyrightProtectionType defines the data structure for Put and Get copyright protection API +type CopyrightProtectionType struct { + Resource []string `json:"resource"` +} + +// ObjectAclType defines the data structure for Put and Get object acl API +type ObjectAclType struct { + AccessControlList []GrantType `json:"accessControlList"` +} + +type PutObjectAclArgs ObjectAclType +type GetObjectAclResult ObjectAclType + +// PutObjectArgs defines the optional args structure for the put object api. +type PutObjectArgs struct { + CacheControl string + ContentDisposition string + ContentMD5 string + ContentType string + ContentLength int64 + Expires string + UserMeta map[string]string + ContentSha256 string + ContentCrc32 string + StorageClass string + Process string + TrafficLimit int64 +} + +// CopyObjectArgs defines the optional args structure for the copy object api. +type CopyObjectArgs struct { + ObjectMeta + MetadataDirective string + IfMatch string + IfNoneMatch string + IfModifiedSince string + IfUnmodifiedSince string + TrafficLimit int64 + CannedAcl string +} + +type MultiCopyObjectArgs struct { + StorageClass string +} + +// CopyObjectResult defines the result json structure for the copy object api. +type CopyObjectResult struct { + LastModified string `json:"lastModified"` + ETag string `json:"eTag"` +} + +type ObjectMeta struct { + CacheControl string + ContentDisposition string + ContentEncoding string + ContentLength int64 + ContentRange string + ContentType string + ContentMD5 string + ContentSha256 string + ContentCrc32 string + Expires string + LastModified string + ETag string + UserMeta map[string]string + StorageClass string + NextAppendOffset string + ObjectType string + BceRestore string + BceObjectType string +} + +// GetObjectResult defines the result data of the get object api. +type GetObjectResult struct { + ObjectMeta + ContentLanguage string + Body io.ReadCloser +} + +// GetObjectMetaResult defines the result data of the get object meta api. +type GetObjectMetaResult struct { + ObjectMeta +} + +// SelectObjectResult defines the result data of the select object api. +type SelectObjectResult struct { + Body io.ReadCloser +} + +// selectObject request args +type SelectObjectArgs struct { + SelectType string `json:"-"` + SelectRequest *SelectObjectRequest `json:"selectRequest"` +} + +type SelectObjectRequest struct { + Expression string `json:"expression"` + ExpressionType string `json:"expressionType"` // SQL + InputSerialization *SelectObjectInput `json:"inputSerialization"` + OutputSerialization *SelectObjectOutput `json:"outputSerialization"` + RequestProgress *SelectObjectProgress `json:"requestProgress"` +} + +type SelectObjectInput struct { + CompressionType string `json:"compressionType"` + CsvParams map[string]string `json:"csv"` + JsonParams map[string]string `json:"json"` +} +type SelectObjectOutput struct { + OutputHeader bool `json:"outputHeader"` + CsvParams map[string]string `json:"csv"` + JsonParams map[string]string `json:"json"` +} +type SelectObjectProgress struct { + Enabled bool `json:"enabled"` +} + +type Prelude struct { + TotalLen uint32 + HeadersLen uint32 +} + +// selectObject response msg +type CommonMessage struct { + Prelude + Headers map[string]string // message-type/content-type…… + Crc32 uint32 // crc32 of RecordsMessage +} +type RecordsMessage struct { + CommonMessage + Records []string // csv/json seleted data, one or more records +} +type ContinuationMessage struct { + CommonMessage + BytesScanned uint64 + BytesReturned uint64 +} +type EndMessage struct { + CommonMessage +} + +// FetchObjectArgs defines the optional arguments structure for the fetch object api. +type FetchObjectArgs struct { + FetchMode string + StorageClass string +} + +// FetchObjectResult defines the result json structure for the fetch object api. +type FetchObjectResult struct { + Code string `json:"code"` + Message string `json:"message"` + RequestId string `json:"requestId"` + JobId string `json:"jobId"` +} + +// AppendObjectArgs defines the optional arguments structure for appending object. +type AppendObjectArgs struct { + Offset int64 + CacheControl string + ContentDisposition string + ContentMD5 string + ContentType string + Expires string + UserMeta map[string]string + ContentSha256 string + ContentCrc32 string + StorageClass string + TrafficLimit int64 +} + +// AppendObjectResult defines the result data structure for appending object. +type AppendObjectResult struct { + ContentMD5 string + NextAppendOffset int64 + ContentCrc32 string + ETag string +} + +// DeleteObjectArgs defines the input args structure for a single object. +type DeleteObjectArgs struct { + Key string `json:"key"` +} + +// DeleteMultipleObjectsResult defines the input args structure for deleting multiple objects. +type DeleteMultipleObjectsArgs struct { + Objects []DeleteObjectArgs `json:"objects"` +} + +// DeleteObjectResult defines the result structure for deleting a single object. +type DeleteObjectResult struct { + Key string `json:"key"` + Code string `json:"code"` + Message string `json:"message"` +} + +// DeleteMultipleObjectsResult defines the result structure for deleting multiple objects. +type DeleteMultipleObjectsResult struct { + Errors []DeleteObjectResult `json:"errors"` +} + +// InitiateMultipartUploadArgs defines the input arguments to initiate a multipart upload. +type InitiateMultipartUploadArgs struct { + CacheControl string + ContentDisposition string + Expires string + StorageClass string +} + +// InitiateMultipartUploadResult defines the result structure to initiate a multipart upload. +type InitiateMultipartUploadResult struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + UploadId string `json:"uploadId"` +} + +// UploadPartArgs defines the optinoal argumets for uploading part. +type UploadPartArgs struct { + ContentMD5 string + ContentSha256 string + ContentCrc32 string + TrafficLimit int64 +} + +// UploadPartCopyArgs defines the optional arguments of UploadPartCopy. +type UploadPartCopyArgs struct { + SourceRange string + IfMatch string + IfNoneMatch string + IfModifiedSince string + IfUnmodifiedSince string + TrafficLimit int64 +} + +type PutSymlinkArgs struct { + ForbidOverwrite string + StorageClass string + UserMeta map[string]string + SymlinkBucket string +} + +// UploadInfoType defines an uploaded part info structure. +type UploadInfoType struct { + PartNumber int `json:"partNumber"` + ETag string `json:"eTag"` +} + +// CompleteMultipartUploadArgs defines the input arguments structure of CompleteMultipartUpload. +type CompleteMultipartUploadArgs struct { + Parts []UploadInfoType `json:"parts"` + UserMeta map[string]string `json:"-"` + Process string `json:"-"` + ContentCrc32 string `json:"-"` +} + +// CompleteMultipartUploadResult defines the result structure of CompleteMultipartUpload. +type CompleteMultipartUploadResult struct { + Location string `json:"location"` + Bucket string `json:"bucket"` + Key string `json:"key"` + ETag string `json:"eTag"` + ContentCrc32 string `json:"-"` +} + +// ListPartsArgs defines the input optional arguments of listing parts information. +type ListPartsArgs struct { + MaxParts int + PartNumberMarker string +} + +type ListPartType struct { + PartNumber int `json:"partNumber"` + LastModified string `json:"lastModified"` + ETag string `json:"eTag"` + Size int `json:"size"` +} + +// ListPartsResult defines the parts info result from ListParts. +type ListPartsResult struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + UploadId string `json:"uploadId"` + Initiated string `json:"initiated"` + Owner OwnerType `json:"owner"` + StorageClass string `json:"storageClass"` + PartNumberMarker int `json:"partNumberMarker"` + NextPartNumberMarker int `json:"nextPartNumberMarker"` + MaxParts int `json:"maxParts"` + IsTruncated bool `json:"isTruncated"` + Parts []ListPartType `json:"parts"` +} + +// ListMultipartUploadsArgs defines the optional arguments for ListMultipartUploads. +type ListMultipartUploadsArgs struct { + Delimiter string + KeyMarker string + MaxUploads int + Prefix string +} + +type ListMultipartUploadsType struct { + Key string `json:"key"` + UploadId string `json:"uploadId"` + Owner OwnerType `json:"owner"` + Initiated string `json:"initiated"` + StorageClass string `json:"storageClass,omitempty"` +} + +// ListMultipartUploadsResult defines the multipart uploads result structure. +type ListMultipartUploadsResult struct { + Bucket string `json:"bucket"` + CommonPrefixes []PrefixType `json:"commonPrefixes"` + Delimiter string `json:"delimiter"` + Prefix string `json:"prefix"` + IsTruncated bool `json:"isTruncated"` + KeyMarker string `json:"keyMarker"` + MaxUploads int `json:"maxUploads"` + NextKeyMarker string `json:"nextKeyMarker"` + Uploads []ListMultipartUploadsType `json:"uploads"` +} + +type ArchiveRestoreArgs struct { + RestoreTier string + RestoreDays int +} + +type GetBucketTrashResult struct { + TrashDir string `json:"trashDir"` +} + +type PutBucketTrashReq struct { + TrashDir string `json:"trashDir"` +} + +type PutBucketNotificationReq struct { + Notifications []PutBucketNotificationSt `json:"notifications"` +} + +type PutBucketNotificationSt struct { + Id string `json:"id"` + Name string `json:"name"` + AppId string `json:"appId"` + Status string `json:"status"` + Resources []string `json:"resources"` + Events []string `json:"events"` + Apps []PutBucketNotificationAppsSt `json:"apps"` +} + +type PutBucketNotificationAppsSt struct { + Id string `json:"id"` + EventUrl string `json:"eventUrl"` + XVars string `json:"xVars"` +} + +type MirrorConfigurationRule struct { + Prefix string `json:"prefix,omitempty"` + SourceUrl string `json:"sourceUrl"` + PassQueryString bool `json:"passQuerystring"` + Mode string `json:"mode"` + StorageClass string `json:"storageClass"` + PassHeaders []string `json:"passHeaders"` + IgnoreHeaders []string `json:"ignoreHeaders"` + CustomHeaders []HeaderPair `json:"customHeaders"` + BackSourceUrl string `json:"backSourceUrl"` + Resource string `json:"resource"` + Suffix string `json:"suffix"` + FixedKey string `json:"fixedKey"` + PrefixReplace string `json:"prefixReplace"` + Version string `json:"version"` +} + +type HeaderPair struct { + HeaderName string `json:"headerName"` + HeaderValue string `json:"headerValue"` +} + +type PutBucketMirrorArgs struct { + BucketMirroringConfiguration []MirrorConfigurationRule `json:"bucketMirroringConfiguration"` +} + +type PutBucketTagArgs struct { + Tags []Tag `json:"tags"` +} + +type Tag struct { + TagKey string `json:"tagKey"` + TagValue string `json:"tagValue"` +} diff --git a/bce-sdk-go/services/bos/api/multipart.go b/bce-sdk-go/services/bos/api/multipart.go new file mode 100644 index 0000000..5e7dee5 --- /dev/null +++ b/bce-sdk-go/services/bos/api/multipart.go @@ -0,0 +1,452 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// multipart.go - the multipart-related APIs definition supported by the BOS service + +package api + +import ( + "bytes" + "fmt" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +// InitiateMultipartUpload - initiate a multipart upload to get a upload ID +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// - contentType: the content type of the object to be uploaded which should be specified, +// otherwise use the default(application/octet-stream) +// - args: the optional arguments +// +// RETURNS: +// - *InitiateMultipartUploadResult: the result data structure +// - error: nil if ok otherwise the specific error +func InitiateMultipartUpload(cli bce.Client, bucket, object, contentType string, + args *InitiateMultipartUploadArgs) (*InitiateMultipartUploadResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.POST) + req.SetParam("uploads", "") + if len(contentType) == 0 { + contentType = RAW_CONTENT_TYPE + } + req.SetHeader(http.CONTENT_TYPE, contentType) + + // Optional arguments settings + if args != nil { + setOptionalNullHeaders(req, map[string]string{ + http.CACHE_CONTROL: args.CacheControl, + http.CONTENT_DISPOSITION: args.ContentDisposition, + http.EXPIRES: args.Expires, + }) + + if validStorageClass(args.StorageClass) { + req.SetHeader(http.BCE_STORAGE_CLASS, args.StorageClass) + } else { + if len(args.StorageClass) != 0 { + return nil, bce.NewBceClientError("invalid storage class value: " + + args.StorageClass) + } + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &InitiateMultipartUploadResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return result, nil +} + +// UploadPart - upload the single part in the multipart upload process +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - content: the uploaded part content +// - args: the optional arguments +// +// RETURNS: +// - string: the etag of the uploaded part +// - error: nil if ok otherwise the specific error +func UploadPart(cli bce.Client, bucket, object, uploadId string, partNumber int, + content *bce.Body, args *UploadPartArgs) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.PUT) + req.SetParam("uploadId", uploadId) + req.SetParam("partNumber", fmt.Sprintf("%d", partNumber)) + if content == nil { + return "", bce.NewBceClientError("upload part content should not be empty") + } + if content.Size() >= THRESHOLD_100_CONTINUE { + req.SetHeader("Expect", "100-continue") + } + req.SetBody(content) + + // Optional arguments settings + if args != nil { + setOptionalNullHeaders(req, map[string]string{ + http.CONTENT_MD5: args.ContentMD5, + http.BCE_CONTENT_SHA256: args.ContentSha256, + http.BCE_CONTENT_CRC32: args.ContentCrc32, + }) + //set traffic-limit + if args.TrafficLimit > 0 { + if args.TrafficLimit > TRAFFIC_LIMIT_MAX || args.TrafficLimit < TRAFFIC_LIMIT_MIN { + return "", bce.NewBceClientError(fmt.Sprintf("TrafficLimit must between %d ~ %d, current value:%d", TRAFFIC_LIMIT_MIN, TRAFFIC_LIMIT_MAX, args.TrafficLimit)) + } + req.SetHeader(http.BCE_TRAFFIC_LIMIT, fmt.Sprintf("%d", args.TrafficLimit)) + } + + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return strings.Trim(resp.Header(http.ETAG), "\""), nil +} + +// UploadPartFromBytes - upload the single part in the multipart upload process +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - content: the uploaded part content +// - args: the optional arguments +// +// RETURNS: +// - string: the etag of the uploaded part +// - error: nil if ok otherwise the specific error +func UploadPartFromBytes(cli bce.Client, bucket, object, uploadId string, partNumber int, + content []byte, args *UploadPartArgs) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.PUT) + req.SetParam("uploadId", uploadId) + req.SetParam("partNumber", fmt.Sprintf("%d", partNumber)) + if content == nil { + return "", bce.NewBceClientError("upload part content should not be empty") + } + size := len(content) + if size >= THRESHOLD_100_CONTINUE { + req.SetHeader("Expect", "100-continue") + } + // set md5 and content-length + req.SetLength(int64(size)) + if size > 0 { + // calc md5 + if args == nil || args.ContentMD5 == "" { + buf := bytes.NewBuffer(content) + contentMD5, err := util.CalculateContentMD5(buf, int64(size)) + if err != nil { + return "", err + } + req.SetHeader(http.CONTENT_MD5, contentMD5) + } + req.SetHeader(http.CONTENT_LENGTH, fmt.Sprintf("%d", size)) + } + // Optional arguments settings + if args != nil { + setOptionalNullHeaders(req, map[string]string{ + http.CONTENT_MD5: args.ContentMD5, + http.BCE_CONTENT_SHA256: args.ContentSha256, + http.BCE_CONTENT_CRC32: args.ContentCrc32, + }) + //set traffic-limit + if args.TrafficLimit > 0 { + if args.TrafficLimit > TRAFFIC_LIMIT_MAX || args.TrafficLimit < TRAFFIC_LIMIT_MIN { + return "", bce.NewBceClientError(fmt.Sprintf("TrafficLimit must between %d ~ %d, current value:%d", + TRAFFIC_LIMIT_MIN, TRAFFIC_LIMIT_MAX, args.TrafficLimit)) + } + req.SetHeader(http.BCE_TRAFFIC_LIMIT, fmt.Sprintf("%d", args.TrafficLimit)) + } + } + // Send request and get the result + resp := &bce.BceResponse{} + if err := cli.SendRequestFromBytes(req, resp, content); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return strings.Trim(resp.Header(http.ETAG), "\""), nil +} + +// UploadPartCopy - copy the multipart data +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the destination bucket name +// - object: the destination object name +// - source: the copy source uri +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - args: the optional arguments +// +// RETURNS: +// - *CopyObjectResult: the lastModified and eTag of the part +// - error: nil if ok otherwise the specific error +func UploadPartCopy(cli bce.Client, bucket, object, source, uploadId string, partNumber int, + args *UploadPartCopyArgs) (*CopyObjectResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.PUT) + req.SetParam("uploadId", uploadId) + req.SetParam("partNumber", fmt.Sprintf("%d", partNumber)) + if len(source) == 0 { + return nil, bce.NewBceClientError("upload part copy source should not be empty") + } + req.SetHeader(http.BCE_COPY_SOURCE, util.UriEncode(source, false)) + + // Optional arguments settings + if args != nil { + setOptionalNullHeaders(req, map[string]string{ + http.BCE_COPY_SOURCE_RANGE: args.SourceRange, + http.BCE_COPY_SOURCE_IF_MATCH: args.IfMatch, + http.BCE_COPY_SOURCE_IF_NONE_MATCH: args.IfNoneMatch, + http.BCE_COPY_SOURCE_IF_MODIFIED_SINCE: args.IfModifiedSince, + http.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE: args.IfUnmodifiedSince, + }) + //set traffic-limit + if args.TrafficLimit > 0 { + if args.TrafficLimit > TRAFFIC_LIMIT_MAX || args.TrafficLimit < TRAFFIC_LIMIT_MIN { + return nil, bce.NewBceClientError(fmt.Sprintf("TrafficLimit must between %d ~ %d, current value:%d", TRAFFIC_LIMIT_MIN, TRAFFIC_LIMIT_MAX, args.TrafficLimit)) + } + req.SetHeader(http.BCE_TRAFFIC_LIMIT, fmt.Sprintf("%d", args.TrafficLimit)) + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CopyObjectResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// CompleteMultipartUpload - finish a multipart upload operation +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// - parts: all parts info stream +// - meta: user defined meta data +// +// RETURNS: +// - *CompleteMultipartUploadResult: the result data +// - error: nil if ok otherwise the specific error +func CompleteMultipartUpload(cli bce.Client, bucket, object, uploadId string, + body *bce.Body, args *CompleteMultipartUploadArgs) (*CompleteMultipartUploadResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.POST) + req.SetParam("uploadId", uploadId) + if body == nil { + return nil, bce.NewBceClientError("upload body info should not be emtpy") + } + if body.Size() >= THRESHOLD_100_CONTINUE { + req.SetHeader("Expect", "100-continue") + } + req.SetBody(body) + + // Optional arguments settings + if args.UserMeta != nil { + if err := setUserMetadata(req, args.UserMeta); err != nil { + return nil, err + } + } + if len(args.Process) != 0 { + req.SetHeader(http.BCE_PROCESS, args.Process) + } + if len(args.ContentCrc32) != 0 { + req.SetHeader(http.BCE_CONTENT_CRC32, args.ContentCrc32) + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CompleteMultipartUploadResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + headers := resp.Headers() + if val, ok := headers[toHttpHeaderKey(http.BCE_CONTENT_CRC32)]; ok { + result.ContentCrc32 = val + } + return result, nil +} + +// AbortMultipartUpload - abort a multipart upload operation +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func AbortMultipartUpload(cli bce.Client, bucket, object, uploadId string) error { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.DELETE) + req.SetParam("uploadId", uploadId) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// ListParts - list the successfully uploaded parts info by upload id +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// - args: the optional arguments +// partNumberMarker: return parts after this marker +// maxParts: the max number of return parts, default and maximum is 1000 +// +// RETURNS: +// - *ListPartsResult: the uploaded parts info result +// - error: nil if ok otherwise the specific error +func ListParts(cli bce.Client, bucket, object, uploadId string, + args *ListPartsArgs) (*ListPartsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.GET) + req.SetParam("uploadId", uploadId) + + // Optional arguments settings + if args != nil { + if len(args.PartNumberMarker) > 0 { + req.SetParam("partNumberMarker", args.PartNumberMarker) + } + if args.MaxParts > 0 { + req.SetParam("maxParts", fmt.Sprintf("%d", args.MaxParts)) + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListPartsResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// ListMultipartUploads - list the unfinished uploaded parts of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the destination bucket name +// - args: the optional arguments +// +// RETURNS: +// - *ListMultipartUploadsResult: the unfinished uploaded parts info result +// - error: nil if ok otherwise the specific error +func ListMultipartUploads(cli bce.Client, bucket string, + args *ListMultipartUploadsArgs) (*ListMultipartUploadsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.GET) + req.SetParam("uploads", "") + + // Optional arguments settings + if args != nil { + if len(args.Delimiter) > 0 { + req.SetParam("delimiter", args.Delimiter) + } + if len(args.KeyMarker) > 0 { + req.SetParam("keyMarker", args.KeyMarker) + } + if args.MaxUploads > 0 { + req.SetParam("maxUploads", fmt.Sprintf("%d", args.MaxUploads)) + } + if len(args.Prefix) > 0 { + req.SetParam("prefix", args.Prefix) + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListMultipartUploadsResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bos/api/object.go b/bce-sdk-go/services/bos/api/object.go new file mode 100644 index 0000000..30b3b01 --- /dev/null +++ b/bce-sdk-go/services/bos/api/object.go @@ -0,0 +1,1016 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// object.go - the object APIs definition supported by the BOS service + +package api + +import ( + "encoding/json" + "fmt" + "net" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +// PutObject - put the object from the string or the stream +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - object: the name of the object +// - body: the input content of the object +// - args: the optional arguments of this api +// +// RETURNS: +// - string: the etag of the object +// - error: nil if ok otherwise the specific error +func PutObject(cli bce.Client, bucket, object string, body *bce.Body, + args *PutObjectArgs) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.PUT) + if body == nil { + return "", bce.NewBceClientError("PutObject body should not be emtpy") + } + if body.Size() >= THRESHOLD_100_CONTINUE { + req.SetHeader("Expect", "100-continue") + } + req.SetBody(body) + + // Optional arguments settings + if args != nil { + setOptionalNullHeaders(req, map[string]string{ + http.CACHE_CONTROL: args.CacheControl, + http.CONTENT_DISPOSITION: args.ContentDisposition, + http.CONTENT_TYPE: args.ContentType, + http.EXPIRES: args.Expires, + http.BCE_CONTENT_SHA256: args.ContentSha256, + http.BCE_CONTENT_CRC32: args.ContentCrc32, + }) + if args.ContentLength > 0 { + // User specified Content-Length can be smaller than the body size, so the body should + // be reset. The `net/http.Client' does not support the Content-Length bigger than the + // body size. + if args.ContentLength > body.Size() { + return "", bce.NewBceClientError(fmt.Sprintf("ContentLength %d is bigger than body size %d", args.ContentLength, body.Size())) + } + body, err := bce.NewBodyFromSizedReader(body.Stream(), args.ContentLength) + if err != nil { + return "", bce.NewBceClientError(err.Error()) + } + req.SetHeader(http.CONTENT_LENGTH, fmt.Sprintf("%d", args.ContentLength)) + req.SetBody(body) // re-assign body + } + + //set traffic-limit + if args.TrafficLimit > 0 { + if args.TrafficLimit > TRAFFIC_LIMIT_MAX || args.TrafficLimit < TRAFFIC_LIMIT_MIN { + return "", bce.NewBceClientError(fmt.Sprintf("TrafficLimit must between %d ~ %d, current value:%d", TRAFFIC_LIMIT_MIN, TRAFFIC_LIMIT_MAX, args.TrafficLimit)) + } + req.SetHeader(http.BCE_TRAFFIC_LIMIT, fmt.Sprintf("%d", args.TrafficLimit)) + } + + // Reset the contentMD5 if set by user + if len(args.ContentMD5) != 0 { + req.SetHeader(http.CONTENT_MD5, args.ContentMD5) + } + + if validStorageClass(args.StorageClass) { + req.SetHeader(http.BCE_STORAGE_CLASS, args.StorageClass) + } else { + if len(args.StorageClass) != 0 { + return "", bce.NewBceClientError("invalid storage class value: " + + args.StorageClass) + } + } + + if err := setUserMetadata(req, args.UserMeta); err != nil { + return "", err + } + + if len(args.Process) != 0 { + req.SetHeader(http.BCE_PROCESS, args.Process) + } + } + // add content-type if not assigned by user + if req.Header(http.CONTENT_TYPE) == "" { + req.SetHeader(http.CONTENT_TYPE, getDefaultContentType(object)) + } + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return strings.Trim(resp.Header(http.ETAG), "\""), nil +} + +// CopyObject - copy one object to a new object with new bucket and/or name. It can alse set the +// metadata of the object with the same source and target. +// +// PARAMS: +// - cli: the client object which can perform sending request +// - bucket: the bucket name of the target object +// - object: the name of the target object +// - source: the source object uri +// - *CopyObjectArgs: the optional input args for copying object +// +// RETURNS: +// - *CopyObjectResult: the result object which contains etag and lastmodified +// - error: nil if ok otherwise the specific error +func CopyObject(cli bce.Client, bucket, object, source string, + args *CopyObjectArgs) (*CopyObjectResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.PUT) + if len(source) == 0 { + return nil, bce.NewBceClientError("copy source should not be null") + } + req.SetHeader(http.BCE_COPY_SOURCE, util.UriEncode(source, false)) + + // Optional arguments settings + if args != nil { + setOptionalNullHeaders(req, map[string]string{ + http.CACHE_CONTROL: args.CacheControl, + http.CONTENT_DISPOSITION: args.ContentDisposition, + http.CONTENT_ENCODING: args.ContentEncoding, + http.CONTENT_RANGE: args.ContentRange, + http.CONTENT_TYPE: args.ContentType, + http.EXPIRES: args.Expires, + http.LAST_MODIFIED: args.LastModified, + http.ETAG: args.ETag, + http.CONTENT_MD5: args.ContentMD5, + http.BCE_CONTENT_SHA256: args.ContentSha256, + http.BCE_OBJECT_TYPE: args.ObjectType, + http.BCE_NEXT_APPEND_OFFSET: args.NextAppendOffset, + http.BCE_COPY_SOURCE_IF_MATCH: args.IfMatch, + http.BCE_COPY_SOURCE_IF_NONE_MATCH: args.IfNoneMatch, + http.BCE_COPY_SOURCE_IF_MODIFIED_SINCE: args.IfModifiedSince, + http.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE: args.IfUnmodifiedSince, + }) + if args.ContentLength != 0 { + req.SetHeader(http.CONTENT_LENGTH, fmt.Sprintf("%d", args.ContentLength)) + } + if validMetadataDirective(args.MetadataDirective) { + req.SetHeader(http.BCE_COPY_METADATA_DIRECTIVE, args.MetadataDirective) + } else { + if len(args.MetadataDirective) != 0 { + return nil, bce.NewBceClientError( + "invalid metadata directive value: " + args.MetadataDirective) + } + } + if validStorageClass(args.StorageClass) { + req.SetHeader(http.BCE_STORAGE_CLASS, args.StorageClass) + } else { + if len(args.StorageClass) != 0 { + return nil, bce.NewBceClientError("invalid storage class value: " + + args.StorageClass) + } + } + + //set traffic-limit + if args.TrafficLimit > 0 { + if args.TrafficLimit > TRAFFIC_LIMIT_MAX || args.TrafficLimit < TRAFFIC_LIMIT_MIN { + return nil, bce.NewBceClientError(fmt.Sprintf("TrafficLimit must between %d ~ %d, current value:%d", TRAFFIC_LIMIT_MIN, TRAFFIC_LIMIT_MAX, args.TrafficLimit)) + } + req.SetHeader(http.BCE_TRAFFIC_LIMIT, fmt.Sprintf("%d", args.TrafficLimit)) + } + + if validCannedAcl(args.CannedAcl) { + req.SetHeader(http.BCE_ACL, args.CannedAcl) + } + + if err := setUserMetadata(req, args.UserMeta); err != nil { + return nil, err + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &CopyObjectResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetObject - get the object content with range and response-headers-specified support +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - object: the name of the object +// - args: the optional args in querysring +// - ranges: the optional range start and end to get the given object +// +// RETURNS: +// - *GetObjectResult: the output content result of the object +// - error: nil if ok otherwise the specific error +func GetObject(cli bce.Client, bucket, object string, args map[string]string, // nolint:gocyclo + ranges ...int64) (*GetObjectResult, error) { + + if object == "" { + err := fmt.Errorf("Get Object don't accept \"\" as a parameter") + return nil, err + } + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.GET) + + // Optional arguments settings + if args != nil { + for k, v := range args { + if _, ok := GET_OBJECT_ALLOWED_RESPONSE_HEADERS[k]; ok { + req.SetParam("response"+k, v) + } + if strings.HasPrefix(k, http.BCE_PREFIX) { + req.SetParam(k, v) + } + } + } + if len(ranges) != 0 { + rangeStr := "bytes=" + if len(ranges) == 1 { + rangeStr += fmt.Sprintf("%d", ranges[0]) + "-" + } else { + rangeStr += fmt.Sprintf("%d", ranges[0]) + "-" + fmt.Sprintf("%d", ranges[1]) + } + req.SetHeader("Range", rangeStr) + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + headers := resp.Headers() + result := &GetObjectResult{} + if val, ok := headers[http.CACHE_CONTROL]; ok { + result.CacheControl = val + } + if val, ok := headers[http.CONTENT_DISPOSITION]; ok { + result.ContentDisposition = val + } + if val, ok := headers[http.CONTENT_LENGTH]; ok { + if length, err := strconv.ParseInt(val, 10, 64); err == nil { + result.ContentLength = length + } + } + if val, ok := headers[http.CONTENT_RANGE]; ok { + result.ContentRange = val + } + if val, ok := headers[http.CONTENT_TYPE]; ok { + result.ContentType = val + } + if val, ok := headers[http.CONTENT_MD5]; ok { + result.ContentMD5 = val + } + if val, ok := headers[http.EXPIRES]; ok { + result.Expires = val + } + if val, ok := headers[http.LAST_MODIFIED]; ok { + result.LastModified = val + } + if val, ok := headers[http.ETAG]; ok { + result.ETag = strings.Trim(val, "\"") + } + if val, ok := headers[http.CONTENT_LANGUAGE]; ok { + result.ContentLanguage = val + } + if val, ok := headers[http.CONTENT_ENCODING]; ok { + result.ContentEncoding = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_CONTENT_SHA256)]; ok { + result.ContentSha256 = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_CONTENT_CRC32)]; ok { + result.ContentCrc32 = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_STORAGE_CLASS)]; ok { + result.StorageClass = val + } + bcePrefix := toHttpHeaderKey(http.BCE_USER_METADATA_PREFIX) + for k, v := range headers { + if strings.Index(k, bcePrefix) == 0 { + if result.UserMeta == nil { + result.UserMeta = make(map[string]string) + } + result.UserMeta[k[len(bcePrefix):]] = v + } + } + if val, ok := headers[toHttpHeaderKey(http.BCE_OBJECT_TYPE)]; ok { + result.ObjectType = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_NEXT_APPEND_OFFSET)]; ok { + result.NextAppendOffset = val + } + result.Body = resp.Body() + return result, nil +} + +// GetObjectMeta - get the meta data of the given object +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - object: the name of the object +// +// RETURNS: +// - *GetObjectMetaResult: the result of this api +// - error: nil if ok otherwise the specific error +func GetObjectMeta(cli bce.Client, bucket, object string) (*GetObjectMetaResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.HEAD) + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + headers := resp.Headers() + result := &GetObjectMetaResult{} + if val, ok := headers[http.CACHE_CONTROL]; ok { + result.CacheControl = val + } + if val, ok := headers[http.CONTENT_DISPOSITION]; ok { + result.ContentDisposition = val + } + if val, ok := headers[http.CONTENT_LENGTH]; ok { + if length, err := strconv.ParseInt(val, 10, 64); err == nil { + result.ContentLength = length + } + } + if val, ok := headers[http.CONTENT_RANGE]; ok { + result.ContentRange = val + } + if val, ok := headers[http.CONTENT_TYPE]; ok { + result.ContentType = val + } + if val, ok := headers[http.CONTENT_MD5]; ok { + result.ContentMD5 = val + } + if val, ok := headers[http.EXPIRES]; ok { + result.Expires = val + } + if val, ok := headers[http.LAST_MODIFIED]; ok { + result.LastModified = val + } + if val, ok := headers[http.ETAG]; ok { + result.ETag = strings.Trim(val, "\"") + } + if val, ok := headers[http.CONTENT_ENCODING]; ok { + result.ContentEncoding = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_CONTENT_SHA256)]; ok { + result.ContentSha256 = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_CONTENT_CRC32)]; ok { + result.ContentCrc32 = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_STORAGE_CLASS)]; ok { + result.StorageClass = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_RESTORE)]; ok { + result.BceRestore = val + } + if val, ok := headers[http.BCE_OBJECT_TYPE]; ok { + result.BceObjectType = val + } + bcePrefix := toHttpHeaderKey(http.BCE_USER_METADATA_PREFIX) + for k, v := range headers { + if strings.Index(k, bcePrefix) == 0 { + if result.UserMeta == nil { + result.UserMeta = make(map[string]string) + } + result.UserMeta[k[len(bcePrefix):]] = v + } + } + if val, ok := headers[toHttpHeaderKey(http.BCE_OBJECT_TYPE)]; ok { + result.ObjectType = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_NEXT_APPEND_OFFSET)]; ok { + result.NextAppendOffset = val + } + defer func() { resp.Body().Close() }() + return result, nil +} + +// SelectObject - select the object content +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - object: the name of the object +// - args: the optional arguments to perform the select operation +// +// RETURNS: +// - *SelectObjectResult: the output select content result of the object +// - error: nil if ok otherwise the specific error +func SelectObject(cli bce.Client, bucket, object string, args *SelectObjectArgs) (*SelectObjectResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.POST) + req.SetParam("select", "") + req.SetParam("type", args.SelectType) + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + result := &SelectObjectResult{} + + result.Body = resp.Body() + return result, nil +} + +// FetchObject - fetch the object by the given url and store it to a bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name to store the object +// - object: the name of the object to be stored +// - source: the source url to fetch +// - args: the optional arguments to perform the fetch operation +// +// RETURNS: +// - *FetchObjectArgs: the result of this api +// - error: nil if ok otherwise the specific error +func FetchObject(cli bce.Client, bucket, object, source string, + args *FetchObjectArgs) (*FetchObjectResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.POST) + req.SetParam("fetch", "") + if len(source) == 0 { + return nil, bce.NewBceClientError("invalid fetch source value: " + source) + } + req.SetHeader(http.BCE_PREFIX+"fetch-source", source) + + // Optional arguments settings + if args != nil { + if validFetchMode(args.FetchMode) { + req.SetHeader(http.BCE_PREFIX+"fetch-mode", args.FetchMode) + } else { + if len(args.FetchMode) != 0 { + return nil, bce.NewBceClientError("invalid fetch mode value: " + args.FetchMode) + } + } + if validStorageClass(args.StorageClass) { + req.SetHeader(http.BCE_STORAGE_CLASS, args.StorageClass) + } else { + if len(args.StorageClass) != 0 { + return nil, bce.NewBceClientError("invalid storage class value: " + + args.StorageClass) + } + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &FetchObjectResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// AppendObject - append the given content to a new or existed object which is appendable +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - object: the name of the object +// - content: the content to be appended +// - args: the optional arguments to perform the append operation +// +// RETURNS: +// - *AppendObjectResult: the result status for this api +// - error: nil if ok otherwise the specific error +func AppendObject(cli bce.Client, bucket, object string, content *bce.Body, + args *AppendObjectArgs) (*AppendObjectResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.POST) + req.SetParam("append", "") + if content == nil { + return nil, bce.NewBceClientError("AppendObject body should not be emtpy") + } + if content.Size() >= THRESHOLD_100_CONTINUE { + req.SetHeader("Expect", "100-continue") + } + req.SetBody(content) + + // Optional arguments settings + if args != nil { + if args.Offset < 0 { + return nil, bce.NewBceClientError( + fmt.Sprintf("invalid append offset value: %d", args.Offset)) + } + if args.Offset > 0 { + req.SetParam("offset", fmt.Sprintf("%d", args.Offset)) + } + setOptionalNullHeaders(req, map[string]string{ + http.CACHE_CONTROL: args.CacheControl, + http.CONTENT_DISPOSITION: args.ContentDisposition, + http.CONTENT_MD5: args.ContentMD5, + http.CONTENT_TYPE: args.ContentType, + http.EXPIRES: args.Expires, + http.BCE_CONTENT_SHA256: args.ContentSha256, + http.BCE_CONTENT_CRC32: args.ContentCrc32, + }) + + if validStorageClass(args.StorageClass) { + req.SetHeader(http.BCE_STORAGE_CLASS, args.StorageClass) + } else { + if len(args.StorageClass) != 0 { + return nil, bce.NewBceClientError("invalid storage class value: " + + args.StorageClass) + } + } + if err := setUserMetadata(req, args.UserMeta); err != nil { + return nil, err + } + //set traffic-limit + if args.TrafficLimit > 0 { + if args.TrafficLimit > TRAFFIC_LIMIT_MAX || args.TrafficLimit < TRAFFIC_LIMIT_MIN { + return nil, bce.NewBceClientError(fmt.Sprintf("TrafficLimit must between %d ~ %d, current value:%d", TRAFFIC_LIMIT_MIN, TRAFFIC_LIMIT_MAX, args.TrafficLimit)) + } + req.SetHeader(http.BCE_TRAFFIC_LIMIT, fmt.Sprintf("%d", args.TrafficLimit)) + } + } + + // Send request and get the result + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + headers := resp.Headers() + result := &AppendObjectResult{} + if val, ok := headers[http.CONTENT_MD5]; ok { + result.ContentMD5 = val + } + if val, ok := headers[toHttpHeaderKey(http.BCE_NEXT_APPEND_OFFSET)]; ok { + nextOffset, offsetErr := strconv.ParseInt(val, 10, 64) + if offsetErr != nil { + nextOffset = content.Size() + } + result.NextAppendOffset = nextOffset + } else { + result.NextAppendOffset = content.Size() + } + if val, ok := headers[toHttpHeaderKey(http.BCE_CONTENT_CRC32)]; ok { + result.ContentCrc32 = val + } + if val, ok := headers[http.ETAG]; ok { + result.ETag = strings.Trim(val, "\"") + } + defer func() { resp.Body().Close() }() + return result, nil +} + +// DeleteObject - delete the given object +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object to be deleted +// - object: the name of the object +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func DeleteObject(cli bce.Client, bucket, object string) error { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// DeleteMultipleObjects - delete the given objects within a single http request +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the objects to be deleted +// - objectListStream: the objects list to be delete with json format +// +// RETURNS: +// - *DeleteMultipleObjectsResult: the objects failed to delete +// - error: nil if ok otherwise the specific error +func DeleteMultipleObjects(cli bce.Client, bucket string, + objectListStream *bce.Body) (*DeleteMultipleObjectsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getBucketUri(bucket)) + req.SetMethod(http.POST) + req.SetParam("delete", "") + req.SetHeader(http.CONTENT_TYPE, "application/json; charset=utf-8") + if objectListStream == nil { + return nil, bce.NewBceClientError("DeleteMultipleObjects body should not be emtpy") + } + if objectListStream.Size() >= THRESHOLD_100_CONTINUE { + req.SetHeader("Expect", "100-continue") + } + req.SetBody(objectListStream) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &DeleteMultipleObjectsResult{} + + if resp.Header(http.CONTENT_LENGTH) == "0" { + resp.Body().Close() + return jsonBody, nil + } + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GeneratePresignedUrl - generate an authorization url with expire time and optional arguments +// +// PARAMS: +// - conf: the client configuration +// - signer: the client signer object to generate the authorization string +// - bucket: the target bucket name +// - object: the target object name +// - expire: expire time in seconds +// - method: optional sign method, default is GET +// - headers: optional sign headers, default just set the Host +// - params: optional sign params, default is empty +// RETURNS: +// - string: the presigned url with authorization string + +func GeneratePresignedUrl(conf *bce.BceClientConfiguration, signer auth.Signer, bucket, + object string, expire int, method string, headers, params map[string]string) string { + return GeneratePresignedUrlInternal(conf, signer, bucket, object, expire, method, headers, params, false) +} +func GeneratePresignedUrlPathStyle(conf *bce.BceClientConfiguration, signer auth.Signer, bucket, + object string, expire int, method string, headers, params map[string]string) string { + return GeneratePresignedUrlInternal(conf, signer, bucket, object, expire, method, headers, params, true) +} + +func GeneratePresignedUrlInternal(conf *bce.BceClientConfiguration, signer auth.Signer, bucket, + object string, expire int, method string, headers, params map[string]string, path_style bool) string { + req := &bce.BceRequest{} + // Set basic arguments + if len(method) == 0 { + method = http.GET + } + req.SetMethod(method) + req.SetEndpoint(conf.Endpoint) + if req.Protocol() == "" { + req.SetProtocol(bce.DEFAULT_PROTOCOL) + } + domain := req.Host() + if pos := strings.Index(domain, ":"); pos != -1 { + domain = domain[:pos] + } + if path_style { + req.SetUri(getObjectUri(bucket, object)) + if conf.CnameEnabled || isCnameLikeHost(conf.Endpoint) { + req.SetUri(getCnameUri(req.Uri())) + } + } else { + if len(bucket) != 0 && net.ParseIP(domain) == nil { // not use an IP as the endpoint by client + req.SetUri(bce.URI_PREFIX + object) + if !conf.CnameEnabled && !isCnameLikeHost(conf.Endpoint) { + req.SetHost(bucket + "." + req.Host()) + } + } else { + req.SetUri(getObjectUri(bucket, object)) + if conf.CnameEnabled || isCnameLikeHost(conf.Endpoint) { + req.SetUri(getCnameUri(req.Uri())) + } + } + } + // Set headers and params if given. + req.SetHeader(http.HOST, req.Host()) + if headers != nil { + for k, v := range headers { + req.SetHeader(k, v) + } + } + if params != nil { + for k, v := range params { + req.SetParam(k, v) + } + } + // Copy one SignOptions object to rewrite it. + option := *conf.SignOption + if expire != 0 { + option.ExpireSeconds = expire + } + + if conf.Credentials.SessionToken != "" { + req.SetParam(http.BCE_SECURITY_TOKEN, conf.Credentials.SessionToken) + } + + // Generate the authorization string and return the signed url. + signer.Sign(&req.Request, conf.Credentials, &option) + req.SetParam("authorization", req.Header(http.AUTHORIZATION)) + return fmt.Sprintf("%s://%s%s?%s", req.Protocol(), req.Host(), + util.UriEncode(req.Uri(), false), req.QueryString()) +} + +// PutObjectAcl - set the ACL of the given object +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// - cannedAcl: support private and public-read +// - grantRead: user id list +// - grantFullControl: user id list +// - aclBody: the acl file body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func PutObjectAcl(cli bce.Client, bucket, object, cannedAcl string, + grantRead, grantFullControl []string, aclBody *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.PUT) + req.SetParam("acl", "") + + // Joiner for generate the user id list string for grant acl header + joiner := func(ids []string) string { + for i := range ids { + ids[i] = "id=\"" + ids[i] + "\"" + } + return strings.Join(ids, ",") + } + + // Choose a acl setting method + methods := 0 + if len(cannedAcl) != 0 { + methods += 1 + if validCannedAcl(cannedAcl) { + req.SetHeader(http.BCE_ACL, cannedAcl) + } + } + if len(grantRead) != 0 { + methods += 1 + req.SetHeader(http.BCE_GRANT_READ, joiner(grantRead)) + } + if len(grantFullControl) != 0 { + methods += 1 + req.SetHeader(http.BCE_GRANT_FULL_CONTROL, joiner(grantFullControl)) + } + if aclBody != nil { + methods += 1 + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(aclBody) + } + if methods != 1 { + return bce.NewBceClientError("BOS only support one acl setting method at the same time") + } + + // Do sending request + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetObjectAcl - get the ACL of the given object +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// +// RETURNS: +// - result: the object acl result object +// - error: nil if success otherwise the specific error +func GetObjectAcl(cli bce.Client, bucket, object string) (*GetObjectAclResult, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.GET) + req.SetParam("acl", "") + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetObjectAclResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteObjectAcl - delete the ACL of the given object +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteObjectAcl(cli bce.Client, bucket, object string) error { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetMethod(http.DELETE) + req.SetParam("acl", "") + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// RestoreObject - restore the archive object +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - object: the object name +// - args: the restore args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func RestoreObject(cli bce.Client, bucket string, object string, args ArchiveRestoreArgs) error { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, object)) + req.SetParam("restore", "") + req.SetMethod(http.POST) + req.SetHeader(http.BCE_RESTORE_DAYS, strconv.Itoa(args.RestoreDays)) + req.SetHeader(http.BCE_RESTORE_TIER, args.RestoreTier) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +// PutObjectSymlink - put the object from the string or the stream +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - object: the name of the object +// - symlinkKey: the name of the symlink +// - symlinkArgs: the optional arguments of this api +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func PutObjectSymlink(cli bce.Client, bucket string, object string, symlinkKey string, symlinkArgs *PutSymlinkArgs) error { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, symlinkKey)) + req.SetParam("symlink", "") + req.SetMethod(http.PUT) + if symlinkArgs != nil { + if len(symlinkArgs.ForbidOverwrite) != 0 { + if !validForbidOverwrite(symlinkArgs.ForbidOverwrite) { + return bce.NewBceClientError("invalid forbid overwrite val," + symlinkArgs.ForbidOverwrite) + } + req.SetHeader(http.BCE_FORBID_OVERWRITE, symlinkArgs.ForbidOverwrite) + } + + if len(symlinkArgs.StorageClass) != 0 { + if !validStorageClass(symlinkArgs.StorageClass) { + return bce.NewBceClientError("invalid storage class val," + symlinkArgs.StorageClass) + } + if symlinkArgs.StorageClass == STORAGE_CLASS_ARCHIVE { + return bce.NewBceClientError("archive storage class not support") + } + req.SetHeader(http.BCE_STORAGE_CLASS, symlinkArgs.StorageClass) + } + + if len(symlinkArgs.UserMeta) != 0 { + if err := setUserMetadata(req, symlinkArgs.UserMeta); err != nil { + return err + } + } + if len(symlinkArgs.SymlinkBucket) != 0 { + req.SetHeader(http.BCE_SYMLINK_BUCKET, symlinkArgs.SymlinkBucket) + } + } + req.SetHeader(http.BCE_SYMLINK_TARGET, object) + + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// PutObjectSymlink - put the object from the string or the stream +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name of the object +// - symlinkKey: the name of the symlink +// +// RETURNS: +// - string: the name of the target object +// - error: nil if ok otherwise the specific error +func GetObjectSymlink(cli bce.Client, bucket string, symlinkKey string) (string, error) { + req := &bce.BceRequest{} + req.SetUri(getObjectUri(bucket, symlinkKey)) + req.SetParam("symlink", "") + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := SendRequest(cli, req, resp); err != nil { + return "", err + } + if resp.IsFail() { + return "", resp.ServiceError() + } + defer func() { resp.Body().Close() }() + if resp.Header(http.BCE_SYMLINK_BUCKET) != "" { + result := BOS_CONFIG_PREFIX + resp.Header(http.BCE_SYMLINK_BUCKET) + "/" + resp.Header(http.BCE_SYMLINK_TARGET) + return result, nil + } + return resp.Header(http.BCE_SYMLINK_TARGET), nil +} diff --git a/bce-sdk-go/services/bos/api/util.go b/bce-sdk-go/services/bos/api/util.go new file mode 100644 index 0000000..dd5d533 --- /dev/null +++ b/bce-sdk-go/services/bos/api/util.go @@ -0,0 +1,295 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BOS service + +package api + +import ( + "bytes" + net_http "net/http" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +const ( + METADATA_DIRECTIVE_COPY = "copy" + METADATA_DIRECTIVE_REPLACE = "replace" + + STORAGE_CLASS_STANDARD = "STANDARD" + STORAGE_CLASS_STANDARD_IA = "STANDARD_IA" + STORAGE_CLASS_COLD = "COLD" + STORAGE_CLASS_ARCHIVE = "ARCHIVE" + + FETCH_MODE_SYNC = "sync" + FETCH_MODE_ASYNC = "async" + + CANNED_ACL_PRIVATE = "private" + CANNED_ACL_PUBLIC_READ = "public-read" + CANNED_ACL_PUBLIC_READ_WRITE = "public-read-write" + + RAW_CONTENT_TYPE = "application/octet-stream" + + THRESHOLD_100_CONTINUE = 1 << 20 // add 100 continue header if body size bigger than 1MB + + TRAFFIC_LIMIT_MAX = 8 * (100 << 20) // 100M bit = 838860800 + TRAFFIC_LIMIT_MIN = 8 * (100 << 10) // 100K bit = 819200 + + STATUS_ENABLED = "enabled" + STATUS_DISABLED = "disabled" + + ENCRYPTION_AES256 = "AES256" + + RESTORE_TIER_STANDARD = "Standard" //标准取回对象 + RESTORE_TIER_EXPEDITED = "Expedited" //快速取回对象 + + FORBID_OVERWRITE_FALSE = "false" + FORBID_OVERWRITE_TRUE = "true" + + NAMESPACE_BUCKET = "namespace" + BOS_CONFIG_PREFIX = "bos://" +) + +var DEFAULT_CNAME_LIKE_LIST = []string{ + ".cdn.bcebos.com", +} + +var VALID_STORAGE_CLASS_TYPE = map[string]int{ + STORAGE_CLASS_STANDARD: 0, + STORAGE_CLASS_STANDARD_IA: 1, + STORAGE_CLASS_COLD: 2, + STORAGE_CLASS_ARCHIVE: 3, +} + +var VALID_RESTORE_TIER = map[string]int{ + RESTORE_TIER_STANDARD: 1, + RESTORE_TIER_EXPEDITED: 1, +} + +var VALID_FORBID_OVERWRITE = map[string]int{ + FORBID_OVERWRITE_FALSE: 1, + FORBID_OVERWRITE_TRUE: 1, +} + +var ( + GET_OBJECT_ALLOWED_RESPONSE_HEADERS = map[string]struct{}{ + "ContentDisposition": {}, + "ContentType": {}, + "ContentLanguage": {}, + "Expires": {}, + "CacheControl": {}, + "ContentEncoding": {}, + } +) + +func getBucketUri(bucketName string) string { + return bce.URI_PREFIX + bucketName +} + +func getObjectUri(bucketName, objectName string) string { + return bce.URI_PREFIX + bucketName + "/" + objectName +} + +func getCnameUri(uri string) string { + if len(uri) <= 0 { + return uri + } + slash_index := strings.Index(uri[1:], "/") + if slash_index == -1 { + return bce.URI_PREFIX + } else { + return uri[slash_index+1:] + } +} + +func validMetadataDirective(val string) bool { + if val == METADATA_DIRECTIVE_COPY || val == METADATA_DIRECTIVE_REPLACE { + return true + } + return false +} + +func validForbidOverwrite(val string) bool { + if _, ok := VALID_FORBID_OVERWRITE[val]; ok { + return true + } + return false +} + +func validStorageClass(val string) bool { + if _, ok := VALID_STORAGE_CLASS_TYPE[val]; ok { + return true + } + return false +} + +func validFetchMode(val string) bool { + if val == FETCH_MODE_SYNC || val == FETCH_MODE_ASYNC { + return true + } + return false +} + +func validCannedAcl(val string) bool { + if val == CANNED_ACL_PRIVATE || + val == CANNED_ACL_PUBLIC_READ || + val == CANNED_ACL_PUBLIC_READ_WRITE { + return true + } + return false +} + +func toHttpHeaderKey(key string) string { + var result bytes.Buffer + needToUpper := true + for _, c := range []byte(key) { + if needToUpper && (c >= 'a' && c <= 'z') { + result.WriteByte(c - 32) + needToUpper = false + } else if c == '-' { + result.WriteByte(c) + needToUpper = true + } else { + result.WriteByte(c) + } + } + return result.String() +} + +func setOptionalNullHeaders(req *bce.BceRequest, args map[string]string) { + for k, v := range args { + if len(v) == 0 { + continue + } + switch k { + case http.CACHE_CONTROL: + fallthrough + case http.CONTENT_DISPOSITION: + fallthrough + case http.CONTENT_ENCODING: + fallthrough + case http.CONTENT_RANGE: + fallthrough + case http.CONTENT_MD5: + fallthrough + case http.CONTENT_TYPE: + fallthrough + case http.EXPIRES: + fallthrough + case http.LAST_MODIFIED: + fallthrough + case http.ETAG: + fallthrough + case http.BCE_OBJECT_TYPE: + fallthrough + case http.BCE_NEXT_APPEND_OFFSET: + fallthrough + case http.BCE_CONTENT_SHA256: + fallthrough + case http.BCE_CONTENT_CRC32: + fallthrough + case http.BCE_COPY_SOURCE_RANGE: + fallthrough + case http.BCE_COPY_SOURCE_IF_MATCH: + fallthrough + case http.BCE_COPY_SOURCE_IF_NONE_MATCH: + fallthrough + case http.BCE_COPY_SOURCE_IF_MODIFIED_SINCE: + fallthrough + case http.BCE_COPY_SOURCE_IF_UNMODIFIED_SINCE: + req.SetHeader(k, v) + } + } +} + +func setUserMetadata(req *bce.BceRequest, meta map[string]string) error { + if meta == nil { + return nil + } + for k, v := range meta { + if len(k) == 0 { + continue + } + if len(k)+len(v) > 32*1024 { + return bce.NewBceClientError("MetadataTooLarge") + } + req.SetHeader(http.BCE_USER_METADATA_PREFIX+k, v) + } + return nil +} + +func isCnameLikeHost(host string) bool { + for _, suffix := range DEFAULT_CNAME_LIKE_LIST { + if strings.HasSuffix(strings.ToLower(host), suffix) { + return true + } + } + return false +} + +func SendRequest(cli bce.Client, req *bce.BceRequest, resp *bce.BceResponse) error { + var ( + err error + need_retry bool + ) + + req.SetEndpoint(cli.GetBceClientConfig().Endpoint) + origin_uri := req.Uri() + // set uri for cname or cdn endpoint + if cli.GetBceClientConfig().CnameEnabled || isCnameLikeHost(cli.GetBceClientConfig().Endpoint) { + req.SetUri(getCnameUri(origin_uri)) + } + + if err = cli.SendRequest(req, resp); err != nil { + if serviceErr, isServiceErr := err.(*bce.BceServiceError); isServiceErr { + if serviceErr.StatusCode == net_http.StatusInternalServerError || + serviceErr.StatusCode == net_http.StatusBadGateway || + serviceErr.StatusCode == net_http.StatusServiceUnavailable || + (serviceErr.StatusCode == net_http.StatusBadRequest && serviceErr.Code == "Http400") { + need_retry = true + } + } + if _, isClientErr := err.(*bce.BceClientError); isClientErr { + need_retry = true + } + // retry backup endpoint + if need_retry && cli.GetBceClientConfig().BackupEndpoint != "" { + req.SetEndpoint(cli.GetBceClientConfig().BackupEndpoint) + if cli.GetBceClientConfig().CnameEnabled || isCnameLikeHost(cli.GetBceClientConfig().BackupEndpoint) { + req.SetUri(getCnameUri(origin_uri)) + } + if err = cli.SendRequest(req, resp); err != nil { + return err + } + } + } + return err +} + +func getDefaultContentType(object string) string { + dot := strings.LastIndex(object, ".") + if dot == -1 { + return "application/octet-stream" + } + ext := object[dot:] + mimeMap := util.GetMimeMap() + if contentType, ok := mimeMap[ext]; ok { + return contentType + } + return "application/octet-stream" + +} diff --git a/bce-sdk-go/services/bos/client.go b/bce-sdk-go/services/bos/client.go new file mode 100644 index 0000000..c2cc352 --- /dev/null +++ b/bce-sdk-go/services/bos/client.go @@ -0,0 +1,2380 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for BOS service + +// Package bos defines the BOS services of BCE. The supported APIs are all defined in sub-package +// model with three types: 16 bucket APIs, 9 object APIs and 7 multipart APIs. +package bos + +import ( + "encoding/json" + "errors" + "fmt" + "io" + "math" + "net/http" + "os" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + sdk_http "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/bos/api" + "github.com/baidubce/bce-sdk-go/services/sts" + "github.com/baidubce/bce-sdk-go/util/log" +) + +const ( + DEFAULT_SERVICE_DOMAIN = bce.DEFAULT_REGION + ".bcebos.com" + DEFAULT_MAX_PARALLEL = 10 + MULTIPART_ALIGN = 1 << 20 // 1MB + MIN_MULTIPART_SIZE = 100 * (1 << 10) // 100 KB + DEFAULT_MULTIPART_SIZE = 12 * (1 << 20) // 12MB + + MAX_PART_NUMBER = 10000 + MAX_SINGLE_PART_SIZE = 5 * (1 << 30) // 5GB + MAX_SINGLE_OBJECT_SIZE = 48.8 * (1 << 40) // 48.8TB +) + +// Client of BOS service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient + + // Fileds that used in parallel operation for BOS service + MaxParallel int64 + MultipartSize int64 +} + +// BosClientConfiguration defines the config components structure by user. +type BosClientConfiguration struct { + Ak string + Sk string + Endpoint string + RedirectDisabled bool +} + +// NewClient make the BOS service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + return NewClientWithConfig(&BosClientConfiguration{ + Ak: ak, + Sk: sk, + Endpoint: endpoint, + RedirectDisabled: false, + }) +} + +// NewStsClient make the BOS service client with STS configuration, it will first apply stsAK,stsSK, sessionToken, then return bosClient using temporary sts Credential +func NewStsClient(ak, sk, endpoint string, expiration int) (*Client, error) { + stsClient, err := sts.NewClient(ak, sk) + if err != nil { + fmt.Println("create sts client object :", err) + return nil, err + } + sts, err := stsClient.GetSessionToken(expiration, "") + if err != nil { + fmt.Println("get session token failed:", err) + return nil, err + } + + bosClient, err := NewClient(sts.AccessKeyId, sts.SecretAccessKey, endpoint) + if err != nil { + fmt.Println("create bos client failed:", err) + return nil, err + } + stsCredential, err := auth.NewSessionBceCredentials( + sts.AccessKeyId, + sts.SecretAccessKey, + sts.SessionToken) + if err != nil { + fmt.Println("create sts credential object failed:", err) + return nil, err + } + bosClient.Config.Credentials = stsCredential + return bosClient, nil +} + +func NewClientWithConfig(config *BosClientConfiguration) (*Client, error) { + var credentials *auth.BceCredentials + var err error + ak, sk, endpoint := config.Ak, config.Sk, config.Endpoint + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS, + RedirectDisabled: config.RedirectDisabled} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer), + DEFAULT_MAX_PARALLEL, DEFAULT_MULTIPART_SIZE} + return client, nil +} + +// ListBuckets - list all buckets +// +// RETURNS: +// - *api.ListBucketsResult: the all buckets +// - error: the return error if any occurs +func (c *Client) ListBuckets() (*api.ListBucketsResult, error) { + return api.ListBuckets(c) +} + +// ListObjects - list all objects of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - args: the optional arguments to list objects +// +// RETURNS: +// - *api.ListObjectsResult: the all objects of the bucket +// - error: the return error if any occurs +func (c *Client) ListObjects(bucket string, + args *api.ListObjectsArgs) (*api.ListObjectsResult, error) { + return api.ListObjects(c, bucket, args) +} + +// SimpleListObjects - list all objects of the given bucket with simple arguments +// +// PARAMS: +// - bucket: the bucket name +// - prefix: the prefix for listing +// - maxKeys: the max number of result objects +// - marker: the marker to mark the beginning for the listing +// - delimiter: the delimiter for list objects +// +// RETURNS: +// - *api.ListObjectsResult: the all objects of the bucket +// - error: the return error if any occurs +func (c *Client) SimpleListObjects(bucket, prefix string, maxKeys int, marker, + delimiter string) (*api.ListObjectsResult, error) { + args := &api.ListObjectsArgs{delimiter, marker, maxKeys, prefix} + return api.ListObjects(c, bucket, args) +} + +// HeadBucket - test the given bucket existed and access authority +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if exists and have authority otherwise the specific error +func (c *Client) HeadBucket(bucket string) error { + err, _ := api.HeadBucket(c, bucket) + return err +} + +// DoesBucketExist - test the given bucket existed or not +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - bool: true if exists and false if not exists or occurs error +// - error: nil if exists or not exist, otherwise the specific error +func (c *Client) DoesBucketExist(bucket string) (bool, error) { + err, _ := api.HeadBucket(c, bucket) + if err == nil { + return true, nil + } + if realErr, ok := err.(*bce.BceServiceError); ok { + if realErr.StatusCode == http.StatusForbidden { + return true, nil + } + if realErr.StatusCode == http.StatusNotFound { + return false, nil + } + } + return false, err +} + +// IsNsBucket - test the given bucket is namespace bucket or not +func (c *Client) IsNsBucket(bucket string) bool { + err, resp := api.HeadBucket(c, bucket) + if err == nil && resp.Header(sdk_http.BCE_BUCKET_TYPE) == api.NAMESPACE_BUCKET { + return true + } + if realErr, ok := err.(*bce.BceServiceError); ok { + if realErr.StatusCode == http.StatusForbidden && + resp.Header(sdk_http.BCE_BUCKET_TYPE) == api.NAMESPACE_BUCKET { + return true + } + } + return false +} + +// PutBucket - create a new bucket +// +// PARAMS: +// - bucket: the new bucket name +// +// RETURNS: +// - string: the location of the new bucket if create success +// - error: nil if create success otherwise the specific error +func (c *Client) PutBucket(bucket string) (string, error) { + return api.PutBucket(c, bucket) +} + +// DeleteBucket - delete a empty bucket +// +// PARAMS: +// - bucket: the bucket name to be deleted +// +// RETURNS: +// - error: nil if delete success otherwise the specific error +func (c *Client) DeleteBucket(bucket string) error { + return api.DeleteBucket(c, bucket) +} + +// GetBucketLocation - get the location fo the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - string: the location of the bucket +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketLocation(bucket string) (string, error) { + return api.GetBucketLocation(c, bucket) +} + +// PutBucketAcl - set the acl of the given bucket with acl body stream +// +// PARAMS: +// - bucket: the bucket name +// - aclBody: the acl json body stream +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketAcl(bucket string, aclBody *bce.Body) error { + return api.PutBucketAcl(c, bucket, "", aclBody) +} + +// PutBucketAclFromCanned - set the canned acl of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - cannedAcl: the cannedAcl string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketAclFromCanned(bucket, cannedAcl string) error { + return api.PutBucketAcl(c, bucket, cannedAcl, nil) +} + +// PutBucketAclFromFile - set the acl of the given bucket with acl json file name +// +// PARAMS: +// - bucket: the bucket name +// - aclFile: the acl file name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketAclFromFile(bucket, aclFile string) error { + body, err := bce.NewBodyFromFile(aclFile) + if err != nil { + return err + } + return api.PutBucketAcl(c, bucket, "", body) +} + +// PutBucketAclFromString - set the acl of the given bucket with acl json string +// +// PARAMS: +// - bucket: the bucket name +// - aclString: the acl string with json format +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketAclFromString(bucket, aclString string) error { + body, err := bce.NewBodyFromString(aclString) + if err != nil { + return err + } + return api.PutBucketAcl(c, bucket, "", body) +} + +// PutBucketAclFromStruct - set the acl of the given bucket with acl data structure +// +// PARAMS: +// - bucket: the bucket name +// - aclObj: the acl struct object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketAclFromStruct(bucket string, aclObj *api.PutBucketAclArgs) error { + jsonBytes, jsonErr := json.Marshal(aclObj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.PutBucketAcl(c, bucket, "", body) +} + +// GetBucketAcl - get the acl of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - *api.GetBucketAclResult: the result of the bucket acl +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketAcl(bucket string) (*api.GetBucketAclResult, error) { + return api.GetBucketAcl(c, bucket) +} + +// PutBucketLogging - set the loging setting of the given bucket with json stream +// +// PARAMS: +// - bucket: the bucket name +// - body: the json body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketLogging(bucket string, body *bce.Body) error { + return api.PutBucketLogging(c, bucket, body) +} + +// PutBucketLoggingFromString - set the loging setting of the given bucket with json string +// +// PARAMS: +// - bucket: the bucket name +// - logging: the json format string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketLoggingFromString(bucket, logging string) error { + body, err := bce.NewBodyFromString(logging) + if err != nil { + return err + } + return api.PutBucketLogging(c, bucket, body) +} + +// PutBucketLoggingFromStruct - set the loging setting of the given bucket with args object +// +// PARAMS: +// - bucket: the bucket name +// - obj: the logging setting object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketLoggingFromStruct(bucket string, obj *api.PutBucketLoggingArgs) error { + jsonBytes, jsonErr := json.Marshal(obj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.PutBucketLogging(c, bucket, body) +} + +// GetBucketLogging - get the logging setting of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - *api.GetBucketLoggingResult: the logging setting of the bucket +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketLogging(bucket string) (*api.GetBucketLoggingResult, error) { + return api.GetBucketLogging(c, bucket) +} + +// DeleteBucketLogging - delete the logging setting of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketLogging(bucket string) error { + return api.DeleteBucketLogging(c, bucket) +} + +// PutBucketLifecycle - set the lifecycle rule of the given bucket with raw stream +// +// PARAMS: +// - bucket: the bucket name +// - lifecycle: the lifecycle rule json body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketLifecycle(bucket string, lifecycle *bce.Body) error { + return api.PutBucketLifecycle(c, bucket, lifecycle) +} + +// PutBucketLifecycleFromString - set the lifecycle rule of the given bucket with string +// +// PARAMS: +// - bucket: the bucket name +// - lifecycle: the lifecycle rule json format string body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketLifecycleFromString(bucket, lifecycle string) error { + body, err := bce.NewBodyFromString(lifecycle) + if err != nil { + return err + } + return api.PutBucketLifecycle(c, bucket, body) +} + +// GetBucketLifecycle - get the lifecycle rule of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - *api.GetBucketLifecycleResult: the lifecycle rule of the bucket +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketLifecycle(bucket string) (*api.GetBucketLifecycleResult, error) { + return api.GetBucketLifecycle(c, bucket) +} + +// DeleteBucketLifecycle - delete the lifecycle rule of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketLifecycle(bucket string) error { + return api.DeleteBucketLifecycle(c, bucket) +} + +// PutBucketStorageclass - set the storage class of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - storageClass: the storage class string value +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketStorageclass(bucket, storageClass string) error { + return api.PutBucketStorageclass(c, bucket, storageClass) +} + +// GetBucketStorageclass - get the storage class of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - string: the storage class string value +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketStorageclass(bucket string) (string, error) { + return api.GetBucketStorageclass(c, bucket) +} + +// PutBucketReplication - set the bucket replication config of different region +// +// PARAMS: +// - bucket: the bucket name +// - replicationConf: the replication config json body stream +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketReplication(bucket string, replicationConf *bce.Body, replicationRuleId string) error { + return api.PutBucketReplication(c, bucket, replicationConf, replicationRuleId) +} + +// PutBucketReplicationFromFile - set the bucket replication config with json file name +// +// PARAMS: +// - bucket: the bucket name +// - confFile: the config json file name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketReplicationFromFile(bucket, confFile string, replicationRuleId string) error { + body, err := bce.NewBodyFromFile(confFile) + if err != nil { + return err + } + return api.PutBucketReplication(c, bucket, body, replicationRuleId) +} + +// PutBucketReplicationFromString - set the bucket replication config with json string +// +// PARAMS: +// - bucket: the bucket name +// - confString: the config string with json format +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketReplicationFromString(bucket, confString string, replicationRuleId string) error { + body, err := bce.NewBodyFromString(confString) + if err != nil { + return err + } + return api.PutBucketReplication(c, bucket, body, replicationRuleId) +} + +// PutBucketReplicationFromStruct - set the bucket replication config with struct +// +// PARAMS: +// - bucket: the bucket name +// - confObj: the replication config struct object +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketReplicationFromStruct(bucket string, + confObj *api.PutBucketReplicationArgs, replicationRuleId string) error { + jsonBytes, jsonErr := json.Marshal(confObj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.PutBucketReplication(c, bucket, body, replicationRuleId) +} + +// GetBucketReplication - get the bucket replication config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - *api.GetBucketReplicationResult: the result of the bucket replication config +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketReplication(bucket string, replicationRuleId string) (*api.GetBucketReplicationResult, error) { + return api.GetBucketReplication(c, bucket, replicationRuleId) +} + +// ListBucketReplication - get all replication config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - *api.ListBucketReplicationResult: the list of the bucket replication config +// - error: nil if success otherwise the specific error +func (c *Client) ListBucketReplication(bucket string) (*api.ListBucketReplicationResult, error) { + return api.ListBucketReplication(c, bucket) +} + +// DeleteBucketReplication - delete the bucket replication config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketReplication(bucket string, replicationRuleId string) error { + return api.DeleteBucketReplication(c, bucket, replicationRuleId) +} + +// GetBucketReplicationProgress - get the bucket replication process of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - replicationRuleId: the replication rule id composed of [0-9 A-Z a-z _ -] +// +// RETURNS: +// - *api.GetBucketReplicationProgressResult: the process of the bucket replication +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketReplicationProgress(bucket string, replicationRuleId string) ( + *api.GetBucketReplicationProgressResult, error) { + return api.GetBucketReplicationProgress(c, bucket, replicationRuleId) +} + +// PutBucketEncryption - set the bucket encryption config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// - algorithm: the encryption algorithm name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketEncryption(bucket, algorithm string) error { + return api.PutBucketEncryption(c, bucket, algorithm) +} + +// GetBucketEncryption - get the bucket encryption config +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - string: the encryption algorithm name +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketEncryption(bucket string) (string, error) { + return api.GetBucketEncryption(c, bucket) +} + +// DeleteBucketEncryption - delete the bucket encryption config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketEncryption(bucket string) error { + return api.DeleteBucketEncryption(c, bucket) +} + +// PutBucketStaticWebsite - set the bucket static website config +// +// PARAMS: +// - bucket: the bucket name +// - config: the static website config body stream +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketStaticWebsite(bucket string, config *bce.Body) error { + return api.PutBucketStaticWebsite(c, bucket, config) +} + +// PutBucketStaticWebsiteFromString - set the bucket static website config from json string +// +// PARAMS: +// - bucket: the bucket name +// - jsonConfig: the static website config json string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketStaticWebsiteFromString(bucket, jsonConfig string) error { + body, err := bce.NewBodyFromString(jsonConfig) + if err != nil { + return err + } + return api.PutBucketStaticWebsite(c, bucket, body) +} + +// PutBucketStaticWebsiteFromStruct - set the bucket static website config from struct +// +// PARAMS: +// - bucket: the bucket name +// - confObj: the static website config object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketStaticWebsiteFromStruct(bucket string, + confObj *api.PutBucketStaticWebsiteArgs) error { + jsonBytes, jsonErr := json.Marshal(confObj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.PutBucketStaticWebsite(c, bucket, body) +} + +// SimplePutBucketStaticWebsite - simple set the bucket static website config +// +// PARAMS: +// - bucket: the bucket name +// - index: the static website config for index file name +// - notFound: the static website config for notFound file name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SimplePutBucketStaticWebsite(bucket, index, notFound string) error { + confObj := &api.PutBucketStaticWebsiteArgs{index, notFound} + return c.PutBucketStaticWebsiteFromStruct(bucket, confObj) +} + +// GetBucketStaticWebsite - get the bucket static website config +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - result: the static website config result object +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketStaticWebsite(bucket string) ( + *api.GetBucketStaticWebsiteResult, error) { + return api.GetBucketStaticWebsite(c, bucket) +} + +// DeleteBucketStaticWebsite - delete the bucket static website config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketStaticWebsite(bucket string) error { + return api.DeleteBucketStaticWebsite(c, bucket) +} + +// PutBucketCors - set the bucket CORS config +// +// PARAMS: +// - bucket: the bucket name +// - config: the bucket CORS config body stream +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketCors(bucket string, config *bce.Body) error { + return api.PutBucketCors(c, bucket, config) +} + +// PutBucketCorsFromFile - set the bucket CORS config from json config file +// +// PARAMS: +// - bucket: the bucket name +// - filename: the bucket CORS json config file name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketCorsFromFile(bucket, filename string) error { + body, err := bce.NewBodyFromFile(filename) + if err != nil { + return err + } + return api.PutBucketCors(c, bucket, body) +} + +// PutBucketCorsFromString - set the bucket CORS config from json config string +// +// PARAMS: +// - bucket: the bucket name +// - filename: the bucket CORS json config string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketCorsFromString(bucket, jsonConfig string) error { + body, err := bce.NewBodyFromString(jsonConfig) + if err != nil { + return err + } + return api.PutBucketCors(c, bucket, body) +} + +// PutBucketCorsFromStruct - set the bucket CORS config from json config object +// +// PARAMS: +// - bucket: the bucket name +// - filename: the bucket CORS json config object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketCorsFromStruct(bucket string, confObj *api.PutBucketCorsArgs) error { + jsonBytes, jsonErr := json.Marshal(confObj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.PutBucketCors(c, bucket, body) +} + +// GetBucketCors - get the bucket CORS config +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - result: the bucket CORS config result object +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketCors(bucket string) (*api.GetBucketCorsResult, error) { + return api.GetBucketCors(c, bucket) +} + +// DeleteBucketCors - delete the bucket CORS config of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketCors(bucket string) error { + return api.DeleteBucketCors(c, bucket) +} + +// PutBucketCopyrightProtection - set the copyright protection config of the given bucket +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - bucket: the bucket name +// - resources: the resource items in the bucket to be protected +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketCopyrightProtection(bucket string, resources ...string) error { + return api.PutBucketCopyrightProtection(c, bucket, resources...) +} + +// GetBucketCopyrightProtection - get the bucket copyright protection config +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - result: the bucket copyright protection config resources +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketCopyrightProtection(bucket string) ([]string, error) { + return api.GetBucketCopyrightProtection(c, bucket) +} + +// DeleteBucketCopyrightProtection - delete the bucket copyright protection config +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketCopyrightProtection(bucket string) error { + return api.DeleteBucketCopyrightProtection(c, bucket) +} + +// PutObject - upload a new object or rewrite the existed object with raw stream +// +// PARAMS: +// - bucket: the name of the bucket to store the object +// - object: the name of the object +// - body: the object content body +// - args: the optional arguments +// +// RETURNS: +// - string: etag of the uploaded object +// - error: the uploaded error if any occurs +func (c *Client) PutObject(bucket, object string, body *bce.Body, + args *api.PutObjectArgs) (string, error) { + return api.PutObject(c, bucket, object, body, args) +} + +// BasicPutObject - the basic interface of uploading an object +// +// PARAMS: +// - bucket: the name of the bucket to store the object +// - object: the name of the object +// - body: the object content body +// +// RETURNS: +// - string: etag of the uploaded object +// - error: the uploaded error if any occurs +func (c *Client) BasicPutObject(bucket, object string, body *bce.Body) (string, error) { + return api.PutObject(c, bucket, object, body, nil) +} + +// PutObjectFromBytes - upload a new object or rewrite the existed object from a byte array +// +// PARAMS: +// - bucket: the name of the bucket to store the object +// - object: the name of the object +// - bytesArr: the content byte array +// - args: the optional arguments +// +// RETURNS: +// - string: etag of the uploaded object +// - error: the uploaded error if any occurs +func (c *Client) PutObjectFromBytes(bucket, object string, bytesArr []byte, + args *api.PutObjectArgs) (string, error) { + body, err := bce.NewBodyFromBytes(bytesArr) + if err != nil { + return "", err + } + return api.PutObject(c, bucket, object, body, args) +} + +// PutObjectFromString - upload a new object or rewrite the existed object from a string +// +// PARAMS: +// - bucket: the name of the bucket to store the object +// - object: the name of the object +// - content: the content string +// - args: the optional arguments +// +// RETURNS: +// - string: etag of the uploaded object +// - error: the uploaded error if any occurs +func (c *Client) PutObjectFromString(bucket, object, content string, + args *api.PutObjectArgs) (string, error) { + body, err := bce.NewBodyFromString(content) + if err != nil { + return "", err + } + return api.PutObject(c, bucket, object, body, args) +} + +// PutObjectFromFile - upload a new object or rewrite the existed object from a local file +// +// PARAMS: +// - bucket: the name of the bucket to store the object +// - object: the name of the object +// - fileName: the local file full path name +// - args: the optional arguments +// +// RETURNS: +// - string: etag of the uploaded object +// - error: the uploaded error if any occurs +func (c *Client) PutObjectFromFile(bucket, object, fileName string, + args *api.PutObjectArgs) (string, error) { + body, err := bce.NewBodyFromFile(fileName) + if err != nil { + return "", err + } + return api.PutObject(c, bucket, object, body, args) +} + +// PutObjectFromStream - upload a new object or rewrite the existed object from stream +// +// PARAMS: +// - bucket: the name of the bucket to store the object +// - object: the name of the object +// - fileName: the local file full path name +// - args: the optional arguments +// +// RETURNS: +// - string: etag of the uploaded object +// - error: the uploaded error if any occurs +func (c *Client) PutObjectFromStream(bucket, object string, reader io.Reader, + args *api.PutObjectArgs) (string, error) { + body, err := bce.NewBodyFromSizedReader(reader, -1) + if err != nil { + return "", err + } + return api.PutObject(c, bucket, object, body, args) +} + +// CopyObject - copy a remote object to another one +// +// PARAMS: +// - bucket: the name of the destination bucket +// - object: the name of the destination object +// - srcBucket: the name of the source bucket +// - srcObject: the name of the source object +// - args: the optional arguments for copying object which are MetadataDirective, StorageClass, +// IfMatch, IfNoneMatch, ifModifiedSince, IfUnmodifiedSince +// +// RETURNS: +// - *api.CopyObjectResult: result struct which contains "ETag" and "LastModified" fields +// - error: any error if it occurs +func (c *Client) CopyObject(bucket, object, srcBucket, srcObject string, + args *api.CopyObjectArgs) (*api.CopyObjectResult, error) { + source := fmt.Sprintf("/%s/%s", srcBucket, srcObject) + return api.CopyObject(c, bucket, object, source, args) +} + +// BasicCopyObject - the basic interface of copying a object to another one +// +// PARAMS: +// - bucket: the name of the destination bucket +// - object: the name of the destination object +// - srcBucket: the name of the source bucket +// - srcObject: the name of the source object +// +// RETURNS: +// - *api.CopyObjectResult: result struct which contains "ETag" and "LastModified" fields +// - error: any error if it occurs +func (c *Client) BasicCopyObject(bucket, object, srcBucket, + srcObject string) (*api.CopyObjectResult, error) { + source := fmt.Sprintf("/%s/%s", srcBucket, srcObject) + return api.CopyObject(c, bucket, object, source, nil) +} + +// GetObject - get the given object with raw stream return +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - args: the optional args in querysring +// - ranges: the optional range start and end to get the given object +// +// RETURNS: +// - *api.GetObjectResult: result struct which contains "Body" and header fields +// for details reference https://cloud.baidu.com/doc/BOS/API.html#GetObject.E6.8E.A5.E5.8F.A3 +// - error: any error if it occurs +func (c *Client) GetObject(bucket, object string, args map[string]string, + ranges ...int64) (*api.GetObjectResult, error) { + return api.GetObject(c, bucket, object, args, ranges...) +} + +// BasicGetObject - the basic interface of geting the given object +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// +// RETURNS: +// - *api.GetObjectResult: result struct which contains "Body" and header fields +// for details reference https://cloud.baidu.com/doc/BOS/API.html#GetObject.E6.8E.A5.E5.8F.A3 +// - error: any error if it occurs +func (c *Client) BasicGetObject(bucket, object string) (*api.GetObjectResult, error) { + return api.GetObject(c, bucket, object, nil) +} + +// BasicGetObjectToFile - use basic interface to get the given object to the given file path +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - filePath: the file path to store the object content +// +// RETURNS: +// - error: any error if it occurs +func (c *Client) BasicGetObjectToFile(bucket, object, filePath string) error { + res, err := api.GetObject(c, bucket, object, nil) + if err != nil { + return err + } + defer res.Body.Close() + + file, fileErr := os.OpenFile(filePath, os.O_TRUNC|os.O_CREATE|os.O_WRONLY, 0644) + if fileErr != nil { + return fileErr + } + defer file.Close() + + written, writeErr := io.CopyN(file, res.Body, res.ContentLength) + if writeErr != nil { + return writeErr + } + if written != res.ContentLength { + return fmt.Errorf("written content size does not match the response content") + } + return nil +} + +// GetObjectMeta - get the given object metadata +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// +// RETURNS: +// - *api.GetObjectMetaResult: metadata result, for details reference +// https://cloud.baidu.com/doc/BOS/API.html#GetObjectMeta.E6.8E.A5.E5.8F.A3 +// - error: any error if it occurs +func (c *Client) GetObjectMeta(bucket, object string) (*api.GetObjectMetaResult, error) { + return api.GetObjectMeta(c, bucket, object) +} + +// SelectObject - select the object content +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - args: the optional arguments to select the object +// +// RETURNS: +// - *api.SelectObjectResult: select object result +// - error: any error if it occurs +func (c *Client) SelectObject(bucket, object string, args *api.SelectObjectArgs) (*api.SelectObjectResult, error) { + return api.SelectObject(c, bucket, object, args) +} + +// FetchObject - fetch the object content from the given source and store +// +// PARAMS: +// - bucket: the name of the bucket to store +// - object: the name of the object to store +// - source: fetch source url +// - args: the optional arguments to fetch the object +// +// RETURNS: +// - *api.FetchObjectResult: result struct with Code, Message, RequestId and JobId fields +// - error: any error if it occurs +func (c *Client) FetchObject(bucket, object, source string, + args *api.FetchObjectArgs) (*api.FetchObjectResult, error) { + return api.FetchObject(c, bucket, object, source, args) +} + +// BasicFetchObject - the basic interface of the fetch object api +// +// PARAMS: +// - bucket: the name of the bucket to store +// - object: the name of the object to store +// - source: fetch source url +// +// RETURNS: +// - *api.FetchObjectResult: result struct with Code, Message, RequestId and JobId fields +// - error: any error if it occurs +func (c *Client) BasicFetchObject(bucket, object, source string) (*api.FetchObjectResult, error) { + return api.FetchObject(c, bucket, object, source, nil) +} + +// SimpleFetchObject - fetch object with simple arguments interface +// +// PARAMS: +// - bucket: the name of the bucket to store +// - object: the name of the object to store +// - source: fetch source url +// - mode: fetch mode which supports sync and async +// - storageClass: the storage class of the fetched object +// +// RETURNS: +// - *api.FetchObjectResult: result struct with Code, Message, RequestId and JobId fields +// - error: any error if it occurs +func (c *Client) SimpleFetchObject(bucket, object, source, mode, + storageClass string) (*api.FetchObjectResult, error) { + args := &api.FetchObjectArgs{mode, storageClass} + return api.FetchObject(c, bucket, object, source, args) +} + +// AppendObject - append the given content to a new or existed object which is appendable +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - content: the append object stream +// - args: the optional arguments to append object +// +// RETURNS: +// - *api.AppendObjectResult: the result of the appended object +// - error: any error if it occurs +func (c *Client) AppendObject(bucket, object string, content *bce.Body, + args *api.AppendObjectArgs) (*api.AppendObjectResult, error) { + return api.AppendObject(c, bucket, object, content, args) +} + +// SimpleAppendObject - the interface to append object with simple offset argument +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - content: the append object stream +// - offset: the offset of where to append +// +// RETURNS: +// - *api.AppendObjectResult: the result of the appended object +// - error: any error if it occurs +func (c *Client) SimpleAppendObject(bucket, object string, content *bce.Body, + offset int64) (*api.AppendObjectResult, error) { + return api.AppendObject(c, bucket, object, content, &api.AppendObjectArgs{Offset: offset}) +} + +// SimpleAppendObjectFromString - the simple interface of appending an object from a string +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - content: the object string to append +// - offset: the offset of where to append +// +// RETURNS: +// - *api.AppendObjectResult: the result of the appended object +// - error: any error if it occurs +func (c *Client) SimpleAppendObjectFromString(bucket, object, content string, + offset int64) (*api.AppendObjectResult, error) { + body, err := bce.NewBodyFromString(content) + if err != nil { + return nil, err + } + return api.AppendObject(c, bucket, object, body, &api.AppendObjectArgs{Offset: offset}) +} + +// SimpleAppendObjectFromFile - the simple interface of appending an object from a file +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - filePath: the full file path +// - offset: the offset of where to append +// +// RETURNS: +// - *api.AppendObjectResult: the result of the appended object +// - error: any error if it occurs +func (c *Client) SimpleAppendObjectFromFile(bucket, object, filePath string, + offset int64) (*api.AppendObjectResult, error) { + body, err := bce.NewBodyFromFile(filePath) + if err != nil { + return nil, err + } + return api.AppendObject(c, bucket, object, body, &api.AppendObjectArgs{Offset: offset}) +} + +// DeleteObject - delete the given object +// +// PARAMS: +// - bucket: the name of the bucket to delete +// - object: the name of the object to delete +// +// RETURNS: +// - error: any error if it occurs +func (c *Client) DeleteObject(bucket, object string) error { + return api.DeleteObject(c, bucket, object) +} + +// DeleteMultipleObjects - delete a list of objects +// +// PARAMS: +// - bucket: the name of the bucket to delete +// - objectListStream: the object list stream to be deleted +// +// RETURNS: +// - *api.DeleteMultipleObjectsResult: the delete information +// - error: any error if it occurs +func (c *Client) DeleteMultipleObjects(bucket string, + objectListStream *bce.Body) (*api.DeleteMultipleObjectsResult, error) { + return api.DeleteMultipleObjects(c, bucket, objectListStream) +} + +// DeleteMultipleObjectsFromString - delete a list of objects with json format string +// +// PARAMS: +// - bucket: the name of the bucket to delete +// - objectListString: the object list string to be deleted +// +// RETURNS: +// - *api.DeleteMultipleObjectsResult: the delete information +// - error: any error if it occurs +func (c *Client) DeleteMultipleObjectsFromString(bucket, + objectListString string) (*api.DeleteMultipleObjectsResult, error) { + body, err := bce.NewBodyFromString(objectListString) + if err != nil { + return nil, err + } + return api.DeleteMultipleObjects(c, bucket, body) +} + +// DeleteMultipleObjectsFromStruct - delete a list of objects with object list struct +// +// PARAMS: +// - bucket: the name of the bucket to delete +// - objectListStruct: the object list struct to be deleted +// +// RETURNS: +// - *api.DeleteMultipleObjectsResult: the delete information +// - error: any error if it occurs +func (c *Client) DeleteMultipleObjectsFromStruct(bucket string, + objectListStruct *api.DeleteMultipleObjectsArgs) (*api.DeleteMultipleObjectsResult, error) { + jsonBytes, jsonErr := json.Marshal(objectListStruct) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.DeleteMultipleObjects(c, bucket, body) +} + +// DeleteMultipleObjectsFromKeyList - delete a list of objects with given key string array +// +// PARAMS: +// - bucket: the name of the bucket to delete +// - keyList: the key string list to be deleted +// +// RETURNS: +// - *api.DeleteMultipleObjectsResult: the delete information +// - error: any error if it occurs +func (c *Client) DeleteMultipleObjectsFromKeyList(bucket string, + keyList []string) (*api.DeleteMultipleObjectsResult, error) { + if len(keyList) == 0 { + return nil, fmt.Errorf("the key list to be deleted is empty") + } + args := make([]api.DeleteObjectArgs, len(keyList)) + for i, k := range keyList { + args[i].Key = k + } + argsContainer := &api.DeleteMultipleObjectsArgs{args} + + jsonBytes, jsonErr := json.Marshal(argsContainer) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.DeleteMultipleObjects(c, bucket, body) +} + +// InitiateMultipartUpload - initiate a multipart upload to get a upload ID +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - contentType: the content type of the object to be uploaded which should be specified, +// otherwise use the default(application/octet-stream) +// - args: the optional arguments +// +// RETURNS: +// - *InitiateMultipartUploadResult: the result data structure +// - error: nil if ok otherwise the specific error +func (c *Client) InitiateMultipartUpload(bucket, object, contentType string, + args *api.InitiateMultipartUploadArgs) (*api.InitiateMultipartUploadResult, error) { + return api.InitiateMultipartUpload(c, bucket, object, contentType, args) +} + +// BasicInitiateMultipartUpload - basic interface to initiate a multipart upload +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// +// RETURNS: +// - *InitiateMultipartUploadResult: the result data structure +// - error: nil if ok otherwise the specific error +func (c *Client) BasicInitiateMultipartUpload(bucket, + object string) (*api.InitiateMultipartUploadResult, error) { + return api.InitiateMultipartUpload(c, bucket, object, "", nil) +} + +// UploadPart - upload the single part in the multipart upload process +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - content: the uploaded part content +// - args: the optional arguments +// +// RETURNS: +// - string: the etag of the uploaded part +// - error: nil if ok otherwise the specific error +func (c *Client) UploadPart(bucket, object, uploadId string, partNumber int, + content *bce.Body, args *api.UploadPartArgs) (string, error) { + return api.UploadPart(c, bucket, object, uploadId, partNumber, content, args) +} + +// BasicUploadPart - basic interface to upload the single part in the multipart upload process +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - content: the uploaded part content +// +// RETURNS: +// - string: the etag of the uploaded part +// - error: nil if ok otherwise the specific error +func (c *Client) BasicUploadPart(bucket, object, uploadId string, partNumber int, + content *bce.Body) (string, error) { + return api.UploadPart(c, bucket, object, uploadId, partNumber, content, nil) +} + +// UploadPartFromBytes - upload the single part in the multipart upload process +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - content: the uploaded part content +// - args: the optional arguments +// +// RETURNS: +// - string: the etag of the uploaded part +// - error: nil if ok otherwise the specific error +func (c *Client) UploadPartFromBytes(bucket, object, uploadId string, partNumber int, + content []byte, args *api.UploadPartArgs) (string, error) { + return api.UploadPartFromBytes(c, bucket, object, uploadId, partNumber, content, args) +} + +// UploadPartCopy - copy the multipart object +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - srcBucket: the source bucket +// - srcObject: the source object +// - uploadId: the multipart upload id +// - partNumber: the current part number +// - args: the optional arguments +// +// RETURNS: +// - *CopyObjectResult: the lastModified and eTag of the part +// - error: nil if ok otherwise the specific error +func (c *Client) UploadPartCopy(bucket, object, srcBucket, srcObject, uploadId string, + partNumber int, args *api.UploadPartCopyArgs) (*api.CopyObjectResult, error) { + source := fmt.Sprintf("/%s/%s", srcBucket, srcObject) + return api.UploadPartCopy(c, bucket, object, source, uploadId, partNumber, args) +} + +// BasicUploadPartCopy - basic interface to copy the multipart object +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - srcBucket: the source bucket +// - srcObject: the source object +// - uploadId: the multipart upload id +// - partNumber: the current part number +// +// RETURNS: +// - *CopyObjectResult: the lastModified and eTag of the part +// - error: nil if ok otherwise the specific error +func (c *Client) BasicUploadPartCopy(bucket, object, srcBucket, srcObject, uploadId string, + partNumber int) (*api.CopyObjectResult, error) { + source := fmt.Sprintf("/%s/%s", srcBucket, srcObject) + return api.UploadPartCopy(c, bucket, object, source, uploadId, partNumber, nil) +} + +// CompleteMultipartUpload - finish a multipart upload operation with parts stream +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// - parts: all parts info stream +// - meta: user defined meta data +// +// RETURNS: +// - *CompleteMultipartUploadResult: the result data +// - error: nil if ok otherwise the specific error +func (c *Client) CompleteMultipartUpload(bucket, object, uploadId string, + body *bce.Body, args *api.CompleteMultipartUploadArgs) (*api.CompleteMultipartUploadResult, error) { + return api.CompleteMultipartUpload(c, bucket, object, uploadId, body, args) +} + +// CompleteMultipartUploadFromStruct - finish a multipart upload operation with parts struct +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// - args: args info struct object +// +// RETURNS: +// - *CompleteMultipartUploadResult: the result data +// - error: nil if ok otherwise the specific error +func (c *Client) CompleteMultipartUploadFromStruct(bucket, object, uploadId string, + args *api.CompleteMultipartUploadArgs) (*api.CompleteMultipartUploadResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return api.CompleteMultipartUpload(c, bucket, object, uploadId, body, args) +} + +// AbortMultipartUpload - abort a multipart upload operation +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) AbortMultipartUpload(bucket, object, uploadId string) error { + return api.AbortMultipartUpload(c, bucket, object, uploadId) +} + +// ListParts - list the successfully uploaded parts info by upload id +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// - args: the optional arguments +// +// RETURNS: +// - *ListPartsResult: the uploaded parts info result +// - error: nil if ok otherwise the specific error +func (c *Client) ListParts(bucket, object, uploadId string, + args *api.ListPartsArgs) (*api.ListPartsResult, error) { + return api.ListParts(c, bucket, object, uploadId, args) +} + +// BasicListParts - basic interface to list the successfully uploaded parts info by upload id +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - uploadId: the multipart upload id +// +// RETURNS: +// - *ListPartsResult: the uploaded parts info result +// - error: nil if ok otherwise the specific error +func (c *Client) BasicListParts(bucket, object, uploadId string) (*api.ListPartsResult, error) { + return api.ListParts(c, bucket, object, uploadId, nil) +} + +// ListMultipartUploads - list the unfinished uploaded parts of the given bucket +// +// PARAMS: +// - bucket: the destination bucket name +// - args: the optional arguments +// +// RETURNS: +// - *ListMultipartUploadsResult: the unfinished uploaded parts info result +// - error: nil if ok otherwise the specific error +func (c *Client) ListMultipartUploads(bucket string, + args *api.ListMultipartUploadsArgs) (*api.ListMultipartUploadsResult, error) { + return api.ListMultipartUploads(c, bucket, args) +} + +// BasicListMultipartUploads - basic interface to list the unfinished uploaded parts +// +// PARAMS: +// - bucket: the destination bucket name +// +// RETURNS: +// - *ListMultipartUploadsResult: the unfinished uploaded parts info result +// - error: nil if ok otherwise the specific error +func (c *Client) BasicListMultipartUploads(bucket string) ( + *api.ListMultipartUploadsResult, error) { + return api.ListMultipartUploads(c, bucket, nil) +} + +// UploadSuperFile - parallel upload the super file by using the multipart upload interface +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - fileName: the local full path filename of the super file +// - storageClass: the storage class to be set to the uploaded file +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UploadSuperFile(bucket, object, fileName, storageClass string) error { + // Get the file size and check the size for multipart upload + file, fileErr := os.Open(fileName) + if fileErr != nil { + return fileErr + } + oldTimeout := c.Config.ConnectionTimeoutInMillis + c.Config.ConnectionTimeoutInMillis = 0 + defer func() { + c.Config.ConnectionTimeoutInMillis = oldTimeout + file.Close() + }() + fileInfo, infoErr := file.Stat() + if infoErr != nil { + return infoErr + } + size := fileInfo.Size() + if size < MIN_MULTIPART_SIZE || c.MultipartSize < MIN_MULTIPART_SIZE { + return bce.NewBceClientError("multipart size should not be less than 1MB") + } + + // Calculate part size and total part number + partSize := (c.MultipartSize + MULTIPART_ALIGN - 1) / MULTIPART_ALIGN * MULTIPART_ALIGN + partNum := (size + partSize - 1) / partSize + if partNum > MAX_PART_NUMBER { + partSize = (size + MAX_PART_NUMBER - 1) / MAX_PART_NUMBER + partSize = (partSize + MULTIPART_ALIGN - 1) / MULTIPART_ALIGN * MULTIPART_ALIGN + partNum = (size + partSize - 1) / partSize + } + log.Debugf("starting upload super file, total parts: %d, part size: %d", partNum, partSize) + + // Inner wrapper function of parallel uploading each part to get the ETag of the part + uploadPart := func(bucket, object, uploadId string, partNumber int, body *bce.Body, + result chan *api.UploadInfoType, ret chan error, id int64, pool chan int64) { + etag, err := c.BasicUploadPart(bucket, object, uploadId, partNumber, body) + if err != nil { + result <- nil + ret <- err + } else { + result <- &api.UploadInfoType{partNumber, etag} + } + pool <- id + } + + // Do the parallel multipart upload + resp, err := c.InitiateMultipartUpload(bucket, object, "", + &api.InitiateMultipartUploadArgs{StorageClass: storageClass}) + if err != nil { + return err + } + uploadId := resp.UploadId + uploadedResult := make(chan *api.UploadInfoType, partNum) + retChan := make(chan error, partNum) + workerPool := make(chan int64, c.MaxParallel) + for i := int64(0); i < c.MaxParallel; i++ { + workerPool <- i + } + for partId := int64(1); partId <= partNum; partId++ { + uploadSize := partSize + offset := (partId - 1) * partSize + left := size - offset + if uploadSize > left { + uploadSize = left + } + partBody, _ := bce.NewBodyFromSectionFile(file, offset, uploadSize) + select { // wait until get a worker to upload + case workerId := <-workerPool: + go uploadPart(bucket, object, uploadId, int(partId), partBody, + uploadedResult, retChan, workerId, workerPool) + case uploadPartErr := <-retChan: + c.AbortMultipartUpload(bucket, object, uploadId) + return uploadPartErr + } + } + + // Check the return of each part uploading, and decide to complete or abort it + completeArgs := &api.CompleteMultipartUploadArgs{ + Parts: make([]api.UploadInfoType, partNum), + } + for i := partNum; i > 0; i-- { + uploaded := <-uploadedResult + if uploaded == nil { // error occurs and not be caught in `select' statement + c.AbortMultipartUpload(bucket, object, uploadId) + return <-retChan + } + completeArgs.Parts[uploaded.PartNumber-1] = *uploaded + log.Debugf("upload part %d success, etag: %s", uploaded.PartNumber, uploaded.ETag) + } + if _, err := c.CompleteMultipartUploadFromStruct(bucket, object, + uploadId, completeArgs); err != nil { + c.AbortMultipartUpload(bucket, object, uploadId) + return err + } + return nil +} + +// DownloadSuperFile - parallel download the super file using the get object with range +// +// PARAMS: +// - bucket: the destination bucket name +// - object: the destination object name +// - fileName: the local full path filename to store the object +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DownloadSuperFile(bucket, object, fileName string) (err error) { + file, err := os.OpenFile(fileName, os.O_WRONLY|os.O_TRUNC|os.O_CREATE, 0644) + if err != nil { + return + } + oldTimeout := c.Config.ConnectionTimeoutInMillis + c.Config.ConnectionTimeoutInMillis = 0 + defer func() { + c.Config.ConnectionTimeoutInMillis = oldTimeout + file.Close() + if err != nil { + os.Remove(fileName) + } + }() + + meta, err := c.GetObjectMeta(bucket, object) + if err != nil { + return + } + size := meta.ContentLength + partSize := (c.MultipartSize + MULTIPART_ALIGN - 1) / MULTIPART_ALIGN * MULTIPART_ALIGN + partNum := (size + partSize - 1) / partSize + log.Debugf("starting download super file, total parts: %d, part size: %d", partNum, partSize) + + doneChan := make(chan struct{}, partNum) + abortChan := make(chan struct{}) + + // Set up multiple goroutine workers to download the object + workerPool := make(chan int64, c.MaxParallel) + for i := int64(0); i < c.MaxParallel; i++ { + workerPool <- i + } + for i := int64(0); i < partNum; i++ { + rangeStart := i * partSize + rangeEnd := (i+1)*partSize - 1 + if rangeEnd > size-1 { + rangeEnd = size - 1 + } + select { + case workerId := <-workerPool: + go func(rangeStart, rangeEnd, workerId int64) { + res, rangeGetErr := c.GetObject(bucket, object, nil, rangeStart, rangeEnd) + if rangeGetErr != nil { + log.Errorf("download object part(offset:%d, size:%d) failed: %v", + rangeStart, res.ContentLength, rangeGetErr) + abortChan <- struct{}{} + err = rangeGetErr + return + } + defer res.Body.Close() + log.Debugf("writing part %d with offset=%d, size=%d", rangeStart/partSize, + rangeStart, res.ContentLength) + buf := make([]byte, 4096) + offset := rangeStart + for { + n, e := res.Body.Read(buf) + if e != nil && e != io.EOF { + abortChan <- struct{}{} + err = e + return + } + if n == 0 { + break + } + if _, writeErr := file.WriteAt(buf[:n], offset); writeErr != nil { + abortChan <- struct{}{} + err = writeErr + return + } + offset += int64(n) + } + log.Debugf("writing part %d done", rangeStart/partSize) + workerPool <- workerId + doneChan <- struct{}{} + }(rangeStart, rangeEnd, workerId) + case <-abortChan: // abort range get if error occurs during downloading any part + return + } + } + + // Wait for writing to local file done + for i := partNum; i > 0; i-- { + <-doneChan + } + return nil +} + +// GeneratePresignedUrl - generate an authorization url with expire time and optional arguments +// +// PARAMS: +// - bucket: the target bucket name +// - object: the target object name +// - expireInSeconds: the expire time in seconds of the signed url +// - method: optional sign method, default is GET +// - headers: optional sign headers, default just set the Host +// - params: optional sign params, default is empty +// +// RETURNS: +// - string: the presigned url with authorization string +func (c *Client) GeneratePresignedUrl(bucket, object string, expireInSeconds int, method string, + headers, params map[string]string) string { + return api.GeneratePresignedUrl(c.Config, c.Signer, bucket, object, + expireInSeconds, method, headers, params) +} + +func (c *Client) GeneratePresignedUrlPathStyle(bucket, object string, expireInSeconds int, method string, + headers, params map[string]string) string { + return api.GeneratePresignedUrlPathStyle(c.Config, c.Signer, bucket, object, + expireInSeconds, method, headers, params) +} + +// BasicGeneratePresignedUrl - basic interface to generate an authorization url with expire time +// +// PARAMS: +// - bucket: the target bucket name +// - object: the target object name +// - expireInSeconds: the expire time in seconds of the signed url +// +// RETURNS: +// - string: the presigned url with authorization string +func (c *Client) BasicGeneratePresignedUrl(bucket, object string, expireInSeconds int) string { + return api.GeneratePresignedUrl(c.Config, c.Signer, bucket, object, + expireInSeconds, "", nil, nil) +} + +// PutObjectAcl - set the ACL of the given object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - aclBody: the acl json body stream +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAcl(bucket, object string, aclBody *bce.Body) error { + return api.PutObjectAcl(c, bucket, object, "", nil, nil, aclBody) +} + +// PutObjectAclFromCanned - set the canned acl of the given object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - cannedAcl: the cannedAcl string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAclFromCanned(bucket, object, cannedAcl string) error { + return api.PutObjectAcl(c, bucket, object, cannedAcl, nil, nil, nil) +} + +// PutObjectAclGrantRead - set the canned grant read acl of the given object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - ids: the user id list to grant read for this object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAclGrantRead(bucket, object string, ids ...string) error { + return api.PutObjectAcl(c, bucket, object, "", ids, nil, nil) +} + +// PutObjectAclGrantFullControl - set the canned grant full-control acl of the given object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - ids: the user id list to grant full-control for this object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAclGrantFullControl(bucket, object string, ids ...string) error { + return api.PutObjectAcl(c, bucket, object, "", nil, ids, nil) +} + +// PutObjectAclFromFile - set the acl of the given object with acl json file name +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - aclFile: the acl file name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAclFromFile(bucket, object, aclFile string) error { + body, err := bce.NewBodyFromFile(aclFile) + if err != nil { + return err + } + return api.PutObjectAcl(c, bucket, object, "", nil, nil, body) +} + +// PutObjectAclFromString - set the acl of the given object with acl json string +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - aclString: the acl string with json format +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAclFromString(bucket, object, aclString string) error { + body, err := bce.NewBodyFromString(aclString) + if err != nil { + return err + } + return api.PutObjectAcl(c, bucket, object, "", nil, nil, body) +} + +// PutObjectAclFromStruct - set the acl of the given object with acl data structure +// +// PARAMS: +// - bucket: the bucket name +// - aclObj: the acl struct object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutObjectAclFromStruct(bucket, object string, aclObj *api.PutObjectAclArgs) error { + jsonBytes, jsonErr := json.Marshal(aclObj) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + return api.PutObjectAcl(c, bucket, object, "", nil, nil, body) +} + +// GetObjectAcl - get the acl of the given object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// +// RETURNS: +// - *api.GetObjectAclResult: the result of the object acl +// - error: nil if success otherwise the specific error +func (c *Client) GetObjectAcl(bucket, object string) (*api.GetObjectAclResult, error) { + return api.GetObjectAcl(c, bucket, object) +} + +// DeleteObjectAcl - delete the acl of the given object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteObjectAcl(bucket, object string) error { + return api.DeleteObjectAcl(c, bucket, object) +} + +// RestoreObject - restore the archive object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - restoreDays: the effective time of restore +// - restoreTier: the tier of restore +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RestoreObject(bucket string, object string, restoreDays int, restoreTier string) error { + if _, ok := api.VALID_RESTORE_TIER[restoreTier]; !ok { + return errors.New("invalid restore tier") + } + + if restoreDays <= 0 { + return errors.New("invalid restore days") + } + + args := api.ArchiveRestoreArgs{ + RestoreTier: restoreTier, + RestoreDays: restoreDays, + } + return api.RestoreObject(c, bucket, object, args) +} + +// PutBucketTrash - put the bucket trash +// +// PARAMS: +// - bucket: the bucket name +// - trashReq: the trash request +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketTrash(bucket string, trashReq api.PutBucketTrashReq) error { + return api.PutBucketTrash(c, bucket, trashReq) +} + +// GetBucketTrash - get the bucket trash +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - *api.GetBucketTrashResult,: the result of the bucket trash +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketTrash(bucket string) (*api.GetBucketTrashResult, error) { + return api.GetBucketTrash(c, bucket) +} + +// DeleteBucketTrash - delete the trash of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketTrash(bucket string) error { + return api.DeleteBucketTrash(c, bucket) +} + +// PutBucketNotification - put the bucket notification +// +// PARAMS: +// - bucket: the bucket name +// - putBucketNotificationReq: the bucket notification request +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PutBucketNotification(bucket string, putBucketNotificationReq api.PutBucketNotificationReq) error { + return api.PutBucketNotification(c, bucket, putBucketNotificationReq) +} + +// GetBucketNotification - get the bucket notification +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - *api.PutBucketNotificationReq,: the result of the bucket notification +// - error: nil if success otherwise the specific error +func (c *Client) GetBucketNotification(bucket string) (*api.PutBucketNotificationReq, error) { + return api.GetBucketNotification(c, bucket) +} + +// DeleteBucketNotification - delete the notification of the given bucket +// +// PARAMS: +// - bucket: the bucket name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBucketNotification(bucket string) error { + return api.DeleteBucketNotification(c, bucket) +} + +// ParallelUpload - auto multipart upload object +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - filename: the filename +// - contentType: the content type default(application/octet-stream) +// - args: the bucket name nil using default +// +// RETURNS: +// - *api.CompleteMultipartUploadResult: multipart upload result +// - error: nil if success otherwise the specific error +func (c *Client) ParallelUpload(bucket string, object string, filename string, contentType string, args *api.InitiateMultipartUploadArgs) (*api.CompleteMultipartUploadResult, error) { + + initiateMultipartUploadResult, err := api.InitiateMultipartUpload(c, bucket, object, contentType, args) + if err != nil { + return nil, err + } + + partEtags, err := c.parallelPartUpload(bucket, object, filename, initiateMultipartUploadResult.UploadId) + if err != nil { + c.AbortMultipartUpload(bucket, object, initiateMultipartUploadResult.UploadId) + return nil, err + } + + completeMultipartUploadResult, err := c.CompleteMultipartUploadFromStruct(bucket, object, initiateMultipartUploadResult.UploadId, &api.CompleteMultipartUploadArgs{Parts: partEtags}) + if err != nil { + c.AbortMultipartUpload(bucket, object, initiateMultipartUploadResult.UploadId) + return nil, err + } + return completeMultipartUploadResult, nil +} + +// parallelPartUpload - single part upload +// +// PARAMS: +// - bucket: the bucket name +// - object: the object name +// - filename: the uploadId +// - uploadId: the uploadId +// +// RETURNS: +// - []api.UploadInfoType: multipart upload result +// - error: nil if success otherwise the specific error +func (c *Client) parallelPartUpload(bucket string, object string, filename string, uploadId string) ([]api.UploadInfoType, error) { + file, err := os.Open(filename) + if err != nil { + return nil, err + } + defer file.Close() + // 分块大小按MULTIPART_ALIGN=1MB对齐 + partSize := (c.MultipartSize + + MULTIPART_ALIGN - 1) / MULTIPART_ALIGN * MULTIPART_ALIGN + + // 获取文件大小,并计算分块数目,最大分块数MAX_PART_NUMBER=10000 + fileInfo, _ := file.Stat() + fileSize := fileInfo.Size() + partNum := (fileSize + partSize - 1) / partSize + if partNum > MAX_PART_NUMBER { // 超过最大分块数,需调整分块大小 + partSize = (fileSize + MAX_PART_NUMBER + 1) / MAX_PART_NUMBER + partSize = (partSize + MULTIPART_ALIGN - 1) / MULTIPART_ALIGN * MULTIPART_ALIGN + partNum = (fileSize + partSize - 1) / partSize + } + + parallelChan := make(chan int, c.MaxParallel) + + errChan := make(chan error, c.MaxParallel) + + resultChan := make(chan api.UploadInfoType, partNum) + + // 逐个分块上传 + for i := int64(1); i <= partNum; i++ { + // 计算偏移offset和本次上传的大小uploadSize + uploadSize := partSize + offset := partSize * (i - 1) + left := fileSize - offset + if left < partSize { + uploadSize = left + } + + // 创建指定偏移、指定大小的文件流 + partBody, _ := bce.NewBodyFromSectionFile(file, offset, uploadSize) + + select { + case err = <-errChan: + return nil, err + default: + select { + case err = <-errChan: + return nil, err + case parallelChan <- 1: + go c.singlePartUpload(bucket, object, uploadId, int(i), partBody, parallelChan, errChan, resultChan) + } + + } + } + + partEtags := make([]api.UploadInfoType, partNum) + for i := int64(0); i < partNum; i++ { + select { + case err := <-errChan: + return nil, err + case result := <-resultChan: + partEtags[result.PartNumber-1].PartNumber = result.PartNumber + partEtags[result.PartNumber-1].ETag = result.ETag + } + } + return partEtags, nil +} + +// singlePartUpload - single part upload +// +// PARAMS: +// - pararelChan: the pararelChan +// - errChan: the error chan +// - result: the upload result chan +// - bucket: the bucket name +// - object: the object name +// - uploadId: the uploadId +// - partNumber: the part number of the object +// - content: the content of current part +func (c *Client) singlePartUpload( + bucket string, object string, uploadId string, + partNumber int, content *bce.Body, + parallelChan chan int, errChan chan error, result chan api.UploadInfoType) { + + defer func() { + if r := recover(); r != nil { + log.Fatal("parallelPartUpload recovered in f:", r) + errChan <- errors.New("parallelPartUpload panic") + } + <-parallelChan + }() + + var args api.UploadPartArgs + args.ContentMD5 = content.ContentMD5() + + etag, err := api.UploadPart(c, bucket, object, uploadId, partNumber, content, &args) + if err != nil { + errChan <- err + log.Error("upload part fail,err:%v", err) + return + } + result <- api.UploadInfoType{PartNumber: partNumber, ETag: etag} + return +} + +// ParallelCopy - auto multipart copy object +// +// PARAMS: +// - srcBucketName: the src bucket name +// - srcObjectName: the src object name +// - destBucketName: the dest bucket name +// - destObjectName: the dest object name +// - args: the copy args +// - srcClient: the src region client +// +// RETURNS: +// - *api.CompleteMultipartUploadResult: multipart upload result +// - error: nil if success otherwise the specific error +func (c *Client) ParallelCopy(srcBucketName string, srcObjectName string, + destBucketName string, destObjectName string, + args *api.MultiCopyObjectArgs, srcClient *Client) (*api.CompleteMultipartUploadResult, error) { + + if srcClient == nil { + srcClient = c + } + objectMeta, err := srcClient.GetObjectMeta(srcBucketName, srcObjectName) + if err != nil { + return nil, err + } + + initArgs := api.InitiateMultipartUploadArgs{ + CacheControl: objectMeta.CacheControl, + ContentDisposition: objectMeta.ContentDisposition, + Expires: objectMeta.Expires, + StorageClass: objectMeta.StorageClass, + } + if args != nil { + if len(args.StorageClass) != 0 { + initArgs.StorageClass = args.StorageClass + } + } + initiateMultipartUploadResult, err := api.InitiateMultipartUpload(c, destBucketName, destObjectName, objectMeta.ContentType, &initArgs) + + if err != nil { + return nil, err + } + + source := fmt.Sprintf("/%s/%s", srcBucketName, srcObjectName) + partEtags, err := c.parallelPartCopy(*objectMeta, source, destBucketName, destObjectName, initiateMultipartUploadResult.UploadId) + + if err != nil { + c.AbortMultipartUpload(destBucketName, destObjectName, initiateMultipartUploadResult.UploadId) + return nil, err + } + + completeMultipartUploadResult, err := c.CompleteMultipartUploadFromStruct(destBucketName, destObjectName, initiateMultipartUploadResult.UploadId, &api.CompleteMultipartUploadArgs{Parts: partEtags}) + if err != nil { + c.AbortMultipartUpload(destBucketName, destObjectName, initiateMultipartUploadResult.UploadId) + return nil, err + } + return completeMultipartUploadResult, nil +} + +// parallelPartCopy - parallel part copy +// +// PARAMS: +// - srcMeta: the copy source object meta +// - source: the copy source +// - bucket: the dest bucket name +// - object: the dest object name +// - uploadId: the uploadId +// +// RETURNS: +// - []api.UploadInfoType: multipart upload result +// - error: nil if success otherwise the specific error +func (c *Client) parallelPartCopy(srcMeta api.GetObjectMetaResult, source string, bucket string, object string, uploadId string) ([]api.UploadInfoType, error) { + var err error + size := srcMeta.ContentLength + partSize := int64(DEFAULT_MULTIPART_SIZE) + if partSize*MAX_PART_NUMBER < size { + lowerLimit := int64(math.Ceil(float64(size) / MAX_PART_NUMBER)) + partSize = int64(math.Ceil(float64(lowerLimit)/float64(partSize))) * partSize + } + partNum := (size + partSize - 1) / partSize + + parallelChan := make(chan int, c.MaxParallel) + + errChan := make(chan error, c.MaxParallel) + + resultChan := make(chan api.UploadInfoType, partNum) + + for i := int64(1); i <= partNum; i++ { + // 计算偏移offset和本次上传的大小uploadSize + uploadSize := partSize + offset := partSize * (i - 1) + left := size - offset + if left < partSize { + uploadSize = left + } + + partCopyArgs := api.UploadPartCopyArgs{ + SourceRange: fmt.Sprintf("bytes=%d-%d", (i-1)*partSize, (i-1)*partSize+uploadSize-1), + IfMatch: srcMeta.ETag, + } + + select { + case err = <-errChan: + return nil, err + default: + select { + case err = <-errChan: + return nil, err + case parallelChan <- 1: + go c.singlePartCopy(source, bucket, object, uploadId, int(i), &partCopyArgs, parallelChan, errChan, resultChan) + } + + } + } + + partEtags := make([]api.UploadInfoType, partNum) + for i := int64(0); i < partNum; i++ { + select { + case err := <-errChan: + return nil, err + case result := <-resultChan: + partEtags[result.PartNumber-1].PartNumber = result.PartNumber + partEtags[result.PartNumber-1].ETag = result.ETag + } + } + return partEtags, nil +} + +// singlePartCopy - single part copy +// +// PARAMS: +// - pararelChan: the pararelChan +// - errChan: the error chan +// - result: the upload result chan +// - source: the copy source +// - bucket: the bucket name +// - object: the object name +// - uploadId: the uploadId +// - partNumber: the part number of the object +// - args: the copy args +func (c *Client) singlePartCopy(source string, bucket string, object string, uploadId string, + partNumber int, args *api.UploadPartCopyArgs, + parallelChan chan int, errChan chan error, result chan api.UploadInfoType) { + + defer func() { + if r := recover(); r != nil { + log.Fatal("parallelPartUpload recovered in f:", r) + errChan <- errors.New("parallelPartUpload panic") + } + <-parallelChan + }() + + copyObjectResult, err := api.UploadPartCopy(c, bucket, object, source, uploadId, partNumber, args) + if err != nil { + errChan <- err + log.Error("upload part fail,err:%v", err) + return + } + result <- api.UploadInfoType{PartNumber: partNumber, ETag: copyObjectResult.ETag} + return +} + +// PutSymlink - create symlink for exist target object +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the object +// - symlinkKey: the name of the symlink +// - symlinkArgs: the optional arguments +// +// RETURNS: +// - error: the put error if any occurs +func (c *Client) PutSymlink(bucket string, object string, symlinkKey string, symlinkArgs *api.PutSymlinkArgs) error { + return api.PutObjectSymlink(c, bucket, object, symlinkKey, symlinkArgs) +} + +// PutSymlink - create symlink for exist target object +// +// PARAMS: +// - bucket: the name of the bucket +// - object: the name of the symlink +// +// RETURNS: +// - string: the target of the symlink +// - error: the put error if any occurs +func (c *Client) GetSymlink(bucket string, object string) (string, error) { + return api.GetObjectSymlink(c, bucket, object) +} + +func (c *Client) PutBucketMirror(bucket string, putBucketMirrorArgs *api.PutBucketMirrorArgs) error { + return api.PutBucketMirror(c, bucket, putBucketMirrorArgs) +} + +func (c *Client) GetBucketMirror(bucket string) (*api.PutBucketMirrorArgs, error) { + return api.GetBucketMirror(c, bucket) +} + +func (c *Client) DeleteBucketMirror(bucket string) error { + return api.DeleteBucketMirror(c, bucket) +} + +func (c *Client) PutBucketTag(bucket string, putBucketTagArgs *api.PutBucketTagArgs) error { + return api.PutBucketTag(c, bucket, putBucketTagArgs) +} + +func (c *Client) GetBucketTag(bucket string) (*api.PutBucketTagArgs, error) { + return api.GetBucketTag(c, bucket) +} + +func (c *Client) DeleteBucketTag(bucket string) error { + return api.DeleteBucketTag(c, bucket) +} diff --git a/bce-sdk-go/services/bos/client_test.go b/bce-sdk-go/services/bos/client_test.go new file mode 100644 index 0000000..59b8157 --- /dev/null +++ b/bce-sdk-go/services/bos/client_test.go @@ -0,0 +1,1177 @@ +package bos + +import ( + "encoding/json" + "fmt" + "net/http" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bos/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + BOS_CLIENT *Client + EXISTS_BUCKET = "gosdk-unittest-bucket" + EXISTS_OBJECT = "gosdk-unittest-object" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string +} + +// init client with your ak/sk written in config.json +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given: %+v\n", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + BOS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, "") + //log.SetLogHandler(log.STDERR | log.FILE) + //log.SetRotateType(log.ROTATE_SIZE) + log.SetLogLevel(log.WARN) + //log.SetLogHandler(log.STDERR) + //log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} +func TestListBuckets(t *testing.T) { + res, err := BOS_CLIENT.ListBuckets() + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestListObjects(t *testing.T) { + args := &api.ListObjectsArgs{Prefix: "test", MaxKeys: 10} + res, err := BOS_CLIENT.ListObjects(EXISTS_BUCKET, args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestSimpleListObjects(t *testing.T) { + res, err := BOS_CLIENT.SimpleListObjects(EXISTS_BUCKET, "test", 10, "", "") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestHeadBucket(t *testing.T) { + err := BOS_CLIENT.HeadBucket(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) +} +func TestDoesBucketExist(t *testing.T) { + exist, err := BOS_CLIENT.DoesBucketExist(EXISTS_BUCKET) + ExpectEqual(t.Errorf, exist, true) + ExpectEqual(t.Errorf, err, nil) + exist, err = BOS_CLIENT.DoesBucketExist("xxx") + ExpectEqual(t.Errorf, exist, false) +} +func TestPutBucket(t *testing.T) { + res, err := BOS_CLIENT.PutBucket("test-put-bucket") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) +} +func TestDeleteBucket(t *testing.T) { + err := BOS_CLIENT.DeleteBucket("test-put-bucket") + ExpectEqual(t.Errorf, err, nil) +} +func TestGetBucketLocation(t *testing.T) { + res, err := BOS_CLIENT.GetBucketLocation(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) +} +func TestPutBucketAcl(t *testing.T) { + acl := `{ + "accessControlList":[ + { + "grantee":[{ + "id":"e13b12d0131b4c8bae959df4969387b8" + }], + "permission":["FULL_CONTROL"] + } + ] +}` + body, _ := bce.NewBodyFromString(acl) + err := BOS_CLIENT.PutBucketAcl(EXISTS_BUCKET, body) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketAcl(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[0].Id, + "e13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "FULL_CONTROL") +} +func TestPutBucketAclFromCanned(t *testing.T) { + err := BOS_CLIENT.PutBucketAclFromCanned(EXISTS_BUCKET, api.CANNED_ACL_PUBLIC_READ) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketAcl(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[0].Id, "*") + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "READ") +} +func TestPutBucketAclFromFile(t *testing.T) { + acl := `{ + "accessControlList":[ + { + "grantee":[ + {"id":"e13b12d0131b4c8bae959df4969387b8"}, + {"id":"a13b12d0131b4c8bae959df4969387b8"} + ], + "permission":["FULL_CONTROL"] + } + ] +}` + fname := "/tmp/test-put-bucket-acl-by-file" + f, _ := os.Create(fname) + f.WriteString(acl) + f.Close() + err := BOS_CLIENT.PutBucketAclFromFile(EXISTS_BUCKET, fname) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketAcl(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + os.Remove(fname) + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[0].Id, + "e13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[1].Id, + "a13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "FULL_CONTROL") +} +func TestPutBucketAclFromString(t *testing.T) { + acl := `{ + "accessControlList":[ + { + "grantee":[ + {"id":"e13b12d0131b4c8bae959df4969387b8"}, + {"id":"a13b12d0131b4c8bae959df4969387b8"} + ], + "permission":["FULL_CONTROL"] + } + ] +}` + err := BOS_CLIENT.PutBucketAclFromString(EXISTS_BUCKET, acl) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketAcl(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[0].Id, + "e13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[1].Id, + "a13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "FULL_CONTROL") +} +func TestPutBucketAclFromStruct(t *testing.T) { + args := &api.PutBucketAclArgs{ + []api.GrantType{ + api.GrantType{ + Grantee: []api.GranteeType{ + api.GranteeType{"e13b12d0131b4c8bae959df4969387b8"}, + }, + Permission: []string{ + "FULL_CONTROL", + }, + }, + }, + } + err := BOS_CLIENT.PutBucketAclFromStruct(EXISTS_BUCKET, args) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketAcl(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.AccessControlList[0].Grantee[0].Id, + "e13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "FULL_CONTROL") +} +func TestPutBucketLogging(t *testing.T) { + body, _ := bce.NewBodyFromString( + `{"targetBucket": "gosdk-unittest-bucket", "targetPrefix": "my-log/"}`) + err := BOS_CLIENT.PutBucketLogging(EXISTS_BUCKET, body) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketLogging(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.TargetBucket, "gosdk-unittest-bucket") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.TargetPrefix, "my-log/") +} +func TestPutBucketLoggingFromString(t *testing.T) { + logging := `{"targetBucket": "gosdk-unittest-bucket", "targetPrefix": "my-log2/"}` + err := BOS_CLIENT.PutBucketLoggingFromString(EXISTS_BUCKET, logging) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketLogging(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.TargetBucket, "gosdk-unittest-bucket") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.TargetPrefix, "my-log2/") +} +func TestPutBucketLoggingFromStruct(t *testing.T) { + obj := &api.PutBucketLoggingArgs{ + TargetBucket: "gosdk-unittest-bucket", + TargetPrefix: "my-log3/", + } + err := BOS_CLIENT.PutBucketLoggingFromStruct(EXISTS_BUCKET, obj) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketLogging(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.TargetBucket, "gosdk-unittest-bucket") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.TargetPrefix, "my-log3/") +} +func TestDeleteBucketLogging(t *testing.T) { + err := BOS_CLIENT.DeleteBucketLogging(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketLogging(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Status, "disabled") +} +func TestPutBucketLifecycle(t *testing.T) { + str := `{ + "rule": [ + { + "id": "transition-to-cold", + "status": "enabled", + "resource": ["gosdk-unittest-bucket/test*"], + "condition": { + "time": { + "dateGreaterThan": "2018-09-07T00:00:00Z" + } + }, + "action": { + "name": "DeleteObject" + } + } + ] +}` + body, _ := bce.NewBodyFromString(str) + err := BOS_CLIENT.PutBucketLifecycle(EXISTS_BUCKET, body) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketLifecycle(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Rule[0].Id, "transition-to-cold") + ExpectEqual(t.Errorf, res.Rule[0].Status, "enabled") + ExpectEqual(t.Errorf, res.Rule[0].Resource[0], "gosdk-unittest-bucket/test*") + ExpectEqual(t.Errorf, res.Rule[0].Condition.Time.DateGreaterThan, "2018-09-07T00:00:00Z") + ExpectEqual(t.Errorf, res.Rule[0].Action.Name, "DeleteObject") +} +func TestPutBucketLifecycleFromString(t *testing.T) { + obj := `{ + "rule": [ + { + "id": "transition-to-cold", + "status": "enabled", + "resource": ["gosdk-unittest-bucket/test*"], + "condition": { + "time": { + "dateGreaterThan": "2018-09-07T00:00:00Z" + } + }, + "action": { + "name": "DeleteObject" + } + } + ] +}` + err := BOS_CLIENT.PutBucketLifecycleFromString(EXISTS_BUCKET, obj) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketLifecycle(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Rule[0].Id, "transition-to-cold") + ExpectEqual(t.Errorf, res.Rule[0].Status, "enabled") + ExpectEqual(t.Errorf, res.Rule[0].Resource[0], "gosdk-unittest-bucket/test*") + ExpectEqual(t.Errorf, res.Rule[0].Condition.Time.DateGreaterThan, "2018-09-07T00:00:00Z") + ExpectEqual(t.Errorf, res.Rule[0].Action.Name, "DeleteObject") +} +func TestDeleteBucketLifecycle(t *testing.T) { + err := BOS_CLIENT.DeleteBucketLifecycle(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, _ := BOS_CLIENT.GetBucketLifecycle(EXISTS_BUCKET) + ExpectEqual(t.Errorf, res, nil) +} +func TestPutBucketStorageClass(t *testing.T) { + err := BOS_CLIENT.PutBucketStorageclass(EXISTS_BUCKET, api.STORAGE_CLASS_STANDARD_IA) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketStorageclass(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res, api.STORAGE_CLASS_STANDARD_IA) +} +func TestGetBucketStorageClass(t *testing.T) { + res, err := BOS_CLIENT.GetBucketStorageclass(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestPutBucketReplication(t *testing.T) { + BOS_CLIENT.DeleteBucketReplication(EXISTS_BUCKET, "") + str := `{ + "id": "abc", + "status":"enabled", + "resource": ["gosdk-unittest-bucket/films"], + "destination": { + "bucket": "bos-rd-su-test", + "storageClass": "COLD" + }, + "replicateDeletes": "disabled" +}` + body, _ := bce.NewBodyFromString(str) + err := BOS_CLIENT.PutBucketReplication(EXISTS_BUCKET, body, "") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketReplication(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Id, "abc") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.Resource[0], "gosdk-unittest-bucket/films") + ExpectEqual(t.Errorf, res.Destination.Bucket, "bos-rd-su-test") + ExpectEqual(t.Errorf, res.ReplicateDeletes, "disabled") +} +func TestPutBucketReplicationFromFile(t *testing.T) { + BOS_CLIENT.DeleteBucketReplication(EXISTS_BUCKET, "") + str := `{ + "id": "abc", + "status":"enabled", + "resource": ["gosdk-unittest-bucket/films"], + "destination": { + "bucket": "bos-rd-su-test", + "storageClass": "COLD" + }, + "replicateDeletes": "disabled" +}` + fname := "/tmp/test-put-bucket-replication-by-file" + f, _ := os.Create(fname) + f.WriteString(str) + f.Close() + err := BOS_CLIENT.PutBucketReplicationFromFile(EXISTS_BUCKET, fname, "") + os.Remove(fname) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketReplication(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Id, "abc") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.Resource[0], "gosdk-unittest-bucket/films") + ExpectEqual(t.Errorf, res.Destination.Bucket, "bos-rd-su-test") + ExpectEqual(t.Errorf, res.ReplicateDeletes, "disabled") +} +func TestPutBucketReplicationFromString(t *testing.T) { + BOS_CLIENT.DeleteBucketReplication(EXISTS_BUCKET, "") + str := `{ + "id": "abc", + "status":"enabled", + "resource": ["gosdk-unittest-bucket/films"], + "destination": { + "bucket": "bos-rd-su-test", + "storageClass": "COLD" + }, + "replicateDeletes": "disabled" +}` + err := BOS_CLIENT.PutBucketReplicationFromString(EXISTS_BUCKET, str, "") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketReplication(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Id, "abc") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.Resource[0], "gosdk-unittest-bucket/films") + ExpectEqual(t.Errorf, res.Destination.Bucket, "bos-rd-su-test") + ExpectEqual(t.Errorf, res.ReplicateDeletes, "disabled") +} +func TestPutBucketReplicationFromStruct(t *testing.T) { + BOS_CLIENT.DeleteBucketReplication(EXISTS_BUCKET, "") + args := &api.PutBucketReplicationArgs{ + Id: "abc", + Status: "enabled", + Resource: []string{"gosdk-unittest-bucket/films"}, + Destination: &api.BucketReplicationDescriptor{"bos-rd-su-test", "COLD"}, + ReplicateDeletes: "disabled", + } + err := BOS_CLIENT.PutBucketReplicationFromStruct(EXISTS_BUCKET, args, "") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketReplication(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Id, "abc") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.Resource[0], "gosdk-unittest-bucket/films") + ExpectEqual(t.Errorf, res.Destination.Bucket, "bos-rd-su-test") + ExpectEqual(t.Errorf, res.ReplicateDeletes, "disabled") +} +func TestGetBucketReplication(t *testing.T) { + res, err := BOS_CLIENT.GetBucketReplication(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Id, "abc") + ExpectEqual(t.Errorf, res.Status, "enabled") + ExpectEqual(t.Errorf, res.Resource[0], "gosdk-unittest-bucket/films") + ExpectEqual(t.Errorf, res.Destination.Bucket, "bos-rd-su-test") + ExpectEqual(t.Errorf, res.ReplicateDeletes, "disabled") +} +func TestGetBucketReplicationProcess(t *testing.T) { + res, err := BOS_CLIENT.GetBucketReplicationProgress(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) +} +func TestDeleteBucketReplication(t *testing.T) { + err := BOS_CLIENT.DeleteBucketReplication(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err, nil) +} +func TestPutBucketEncryption(t *testing.T) { + err := BOS_CLIENT.PutBucketEncryption(EXISTS_BUCKET, api.ENCRYPTION_AES256) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketEncryption(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res, api.ENCRYPTION_AES256) +} +func TestGetBucketEncryption(t *testing.T) { + res, err := BOS_CLIENT.GetBucketEncryption(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestDeleteBucketEncryption(t *testing.T) { + err := BOS_CLIENT.DeleteBucketEncryption(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketEncryption(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestPutBucketStaticWebsite(t *testing.T) { + BOS_CLIENT.DeleteBucketStaticWebsite(EXISTS_BUCKET) + body, _ := bce.NewBodyFromString(`{"index": "index.html", "notFound":"blank.html"}`) + err := BOS_CLIENT.PutBucketStaticWebsite(EXISTS_BUCKET, body) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Index, "index.html") + ExpectEqual(t.Errorf, res.NotFound, "blank.html") +} +func TestPutBucketStaticWebsiteFromString(t *testing.T) { + BOS_CLIENT.DeleteBucketStaticWebsite(EXISTS_BUCKET) + jsonConf := `{"index": "index.html", "notFound":"blank.html"}` + err := BOS_CLIENT.PutBucketStaticWebsiteFromString(EXISTS_BUCKET, jsonConf) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Index, "index.html") + ExpectEqual(t.Errorf, res.NotFound, "blank.html") +} +func TestPutBucketStaticWebsiteFromStruct(t *testing.T) { + BOS_CLIENT.DeleteBucketStaticWebsite(EXISTS_BUCKET) + obj := &api.PutBucketStaticWebsiteArgs{"index.html", "blank.html"} + err := BOS_CLIENT.PutBucketStaticWebsiteFromStruct(EXISTS_BUCKET, obj) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Index, "index.html") + ExpectEqual(t.Errorf, res.NotFound, "blank.html") +} +func TestSimplePutBucketStaticWebsite(t *testing.T) { + BOS_CLIENT.DeleteBucketStaticWebsite(EXISTS_BUCKET) + err := BOS_CLIENT.SimplePutBucketStaticWebsite(EXISTS_BUCKET, "index.html", "blank.html") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.Index, "index.html") + ExpectEqual(t.Errorf, res.NotFound, "blank.html") +} +func TestGetBucketStaticWebsite(t *testing.T) { + res, err := BOS_CLIENT.GetBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) +} +func TestDeleteBucketStaticWebsite(t *testing.T) { + err := BOS_CLIENT.DeleteBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketStaticWebsite(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v", res) +} +func TestPutBucketCors(t *testing.T) { + body, _ := bce.NewBodyFromString(` + { + "corsConfiguration": [ + { + "allowedOrigins": ["https://www.baidu.com"], + "allowedMethods": ["GET"], + "maxAgeSeconds": 1800 + } + ] + } + `) + err := BOS_CLIENT.PutBucketCors(EXISTS_BUCKET, body) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedOrigins[0], "https://www.baidu.com") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedMethods[0], "GET") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].MaxAgeSeconds, 1800) +} +func TestPutBucketCorsFromFile(t *testing.T) { + str := `{ + "corsConfiguration": [ + { + "allowedOrigins": ["https://www.baidu.com"], + "allowedMethods": ["GET"], + "maxAgeSeconds": 1800 + } + ] + }` + fname := "/tmp/test-put-bucket-cors-by-file" + f, _ := os.Create(fname) + f.WriteString(str) + f.Close() + err := BOS_CLIENT.PutBucketCorsFromFile(EXISTS_BUCKET, fname) + os.Remove(fname) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedOrigins[0], "https://www.baidu.com") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedMethods[0], "GET") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].MaxAgeSeconds, 1800) + err = BOS_CLIENT.PutBucketCorsFromFile(EXISTS_BUCKET, "/tmp/not-exist") + ExpectEqual(t.Errorf, err != nil, true) +} +func TestPutBucketCorsFromString(t *testing.T) { + str := `{ + "corsConfiguration": [ + { + "allowedOrigins": ["https://www.baidu.com"], + "allowedMethods": ["GET"], + "maxAgeSeconds": 1800 + } + ] + }` + err := BOS_CLIENT.PutBucketCorsFromString(EXISTS_BUCKET, str) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedOrigins[0], "https://www.baidu.com") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedMethods[0], "GET") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].MaxAgeSeconds, 1800) + err = BOS_CLIENT.PutBucketCorsFromString(EXISTS_BUCKET, "") + ExpectEqual(t.Errorf, err != nil, true) +} +func TestPutBucketCorsFromStruct(t *testing.T) { + obj := &api.PutBucketCorsArgs{ + []api.BucketCORSType{ + api.BucketCORSType{ + AllowedOrigins: []string{"https://www.baidu.com"}, + AllowedMethods: []string{"GET"}, + MaxAgeSeconds: 1200, + }, + }, + } + err := BOS_CLIENT.PutBucketCorsFromStruct(EXISTS_BUCKET, obj) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedOrigins[0], "https://www.baidu.com") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedMethods[0], "GET") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].MaxAgeSeconds, 1200) + err = BOS_CLIENT.PutBucketCorsFromStruct(EXISTS_BUCKET, nil) + ExpectEqual(t.Errorf, err != nil, true) +} +func TestGetBucketCors(t *testing.T) { + res, err := BOS_CLIENT.GetBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedOrigins[0], "https://www.baidu.com") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].AllowedMethods[0], "GET") + ExpectEqual(t.Errorf, res.CorsConfiguration[0].MaxAgeSeconds, 1200) +} +func TestDeleteBucketCors(t *testing.T) { + err := BOS_CLIENT.DeleteBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCors(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v, %v", res, err) +} +func TestPutBucketCopyrightProtection(t *testing.T) { + err := BOS_CLIENT.PutBucketCopyrightProtection(EXISTS_BUCKET, + "gosdk-unittest-bucket/test-put-object", "gosdk-unittest-bucket/films/*") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCopyrightProtection(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res[0], "gosdk-unittest-bucket/test-put-object") + ExpectEqual(t.Errorf, res[1], "gosdk-unittest-bucket/films/*") +} +func TestGetBucketCopyrightProtection(t *testing.T) { + res, err := BOS_CLIENT.GetBucketCopyrightProtection(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v, %v", res, err) +} +func TestDeleteBucketCopyrightProtection(t *testing.T) { + err := BOS_CLIENT.DeleteBucketCopyrightProtection(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketCopyrightProtection(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v, %v", res, err) +} + +func TestPutObject(t *testing.T) { + args := &api.PutObjectArgs{StorageClass: api.STORAGE_CLASS_COLD} + body, _ := bce.NewBodyFromString("12345") + etag, err := BOS_CLIENT.PutObject(EXISTS_BUCKET, "test-put-object", body, args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "827ccb0eea8a706c4c34a16891f84e7b", etag) +} + +func TestBasicPutObject(t *testing.T) { + body, _ := bce.NewBodyFromString("12345") + etag, err := BOS_CLIENT.BasicPutObject(EXISTS_BUCKET, "test-put-object", body) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "827ccb0eea8a706c4c34a16891f84e7b", etag) +} + +func TestPutObjectFromBytes(t *testing.T) { + arr := []byte("12345") + etag, err := BOS_CLIENT.PutObjectFromBytes(EXISTS_BUCKET, "test-put-object", arr, nil) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "827ccb0eea8a706c4c34a16891f84e7b", etag) +} + +func TestPutObjectFromString(t *testing.T) { + etag, err := BOS_CLIENT.PutObjectFromString(EXISTS_BUCKET, "test-put-object", "12345", nil) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "827ccb0eea8a706c4c34a16891f84e7b", etag) +} + +func TestPutObjectFromFile(t *testing.T) { + fname := "/tmp/test-put-file" + f, _ := os.Create(fname) + f.WriteString("12345") + f.Close() + etag, err := BOS_CLIENT.PutObjectFromFile(EXISTS_BUCKET, "test-put-object", fname, nil) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "827ccb0eea8a706c4c34a16891f84e7b", etag) + args := &api.PutObjectArgs{ContentLength: 6} + etag, err = BOS_CLIENT.PutObjectFromFile(EXISTS_BUCKET, "test-put-object", fname, args) + ExpectEqual(t.Errorf, true, err != nil) + ExpectEqual(t.Errorf, "", etag) + os.Remove(fname) +} + +func TestPutObjectFromStream(t *testing.T) { + fname := "/tmp/test-put-file" + fw, _ := os.Create(fname) + defer os.Remove(fname) + fw.WriteString("12345") + fw.Close() + fr, _ := os.Open(fname) + defer fr.Close() + etag, err := BOS_CLIENT.PutObjectFromStream(EXISTS_BUCKET, "test-put-object", fr, nil) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "827ccb0eea8a706c4c34a16891f84e7b", etag) +} + +func TestCopyObject(t *testing.T) { + args := new(api.CopyObjectArgs) + args.StorageClass = api.STORAGE_CLASS_COLD + res, err := BOS_CLIENT.CopyObject(EXISTS_BUCKET, "test-copy-object", + EXISTS_BUCKET, "test-put-object", args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("copy result: %+v", res) +} +func TestBasicCopyObject(t *testing.T) { + res, err := BOS_CLIENT.BasicCopyObject(EXISTS_BUCKET, "test-copy-object", + EXISTS_BUCKET, "test-put-object") + ExpectEqual(t.Errorf, err, nil) + t.Logf("copy result: %+v", res) +} +func TestGetObject(t *testing.T) { + res, err := BOS_CLIENT.GetObject(EXISTS_BUCKET, "test-put-object", nil) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + t.Logf("%v", res.ContentLength) + buf := make([]byte, 1024) + n, _ := res.Body.Read(buf) + t.Logf("%s", buf[0:n]) + res.Body.Close() + /* + respHeaders := map[string]string{"ContentEncoding": "qqqqqqqqqqqqq"} + + res, err = BOS_CLIENT.GetObject(EXISTS_BUCKET, "test-put-object", respHeaders) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + t.Logf("%v", res.ContentLength) + n, _ = res.Body.Read(buf) + t.Logf("%s", buf[0:n]) + res.Body.Close() + res, err = BOS_CLIENT.GetObject(EXISTS_BUCKET, "test-put-object", respHeaders, 2) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + t.Logf("%v", res.ContentLength) + n, _ = res.Body.Read(buf) + t.Logf("%s", buf[0:n]) + res, err = BOS_CLIENT.GetObject(EXISTS_BUCKET, "test-put-object", respHeaders, 2, 4) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + t.Logf("%v", res.ContentLength) + n, _ = res.Body.Read(buf) + t.Logf("%s", buf[0:n]) + res.Body.Close() + */ +} +func TestBasicGetObject(t *testing.T) { + res, err := BOS_CLIENT.BasicGetObject(EXISTS_BUCKET, "test-put-object") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + defer res.Body.Close() + t.Logf("%v", res.ContentLength) + for { + buf := make([]byte, 1024) + n, e := res.Body.Read(buf) + t.Logf("%s", buf[0:n]) + if e != nil { + break + } + } +} +func TestBasicGetObjectToFile(t *testing.T) { + fname := "/tmp/test-get-object" + err := BOS_CLIENT.BasicGetObjectToFile(EXISTS_BUCKET, "test-put-object", fname) + ExpectEqual(t.Errorf, err, nil) + os.Remove(fname) + fname = "/bin/test-get-object" + err = BOS_CLIENT.BasicGetObjectToFile(EXISTS_BUCKET, "test-put-object", fname) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v", err) + err = BOS_CLIENT.BasicGetObjectToFile(EXISTS_BUCKET, "not-exist-object-name", fname) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v", err) +} + +/* + func TestGetObjectMeta(t *testing.T) { + res, err := BOS_CLIENT.GetObjectMeta(EXISTS_BUCKET, "test-put-object") + ExpectEqual(t.Errorf, err, nil) + t.Logf("get object meta result: %+v", res) + } +*/ +func TestFetchObject(t *testing.T) { + args := &api.FetchObjectArgs{api.FETCH_MODE_ASYNC, api.STORAGE_CLASS_COLD} + res, err := BOS_CLIENT.FetchObject(EXISTS_BUCKET, "test-fetch-object", + "https://cloud.baidu.com/doc/BOS/API.html", args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("result: %+v", res) +} +func TestBasicFetchObject(t *testing.T) { + res, err := BOS_CLIENT.BasicFetchObject(EXISTS_BUCKET, "test-fetch-object", + "https://bj.bcebos.com/gosdk-unittest-bucket/testsumlink") + ExpectEqual(t.Errorf, err, nil) + t.Logf("result: %+v", res) + res1, err1 := BOS_CLIENT.GetObjectMeta(EXISTS_BUCKET, "test-fetch-object") + ExpectEqual(t.Errorf, err1, nil) + t.Logf("meta: %+v", res1) +} +func TestSimpleFetchObject(t *testing.T) { + res, err := BOS_CLIENT.SimpleFetchObject(EXISTS_BUCKET, "test-fetch-object", + "https://bj.bcebos.com/gosdk-unittest-bucket/testsumlink", + api.FETCH_MODE_ASYNC, api.STORAGE_CLASS_COLD) + ExpectEqual(t.Errorf, err, nil) + t.Logf("result: %+v", res) +} +func TestAppendObject(t *testing.T) { + args := &api.AppendObjectArgs{} + body, _ := bce.NewBodyFromString("aaaaaaaaaaa") + res, err := BOS_CLIENT.AppendObject(EXISTS_BUCKET, "test-append-object", body, args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestSimpleAppendObject(t *testing.T) { + body, _ := bce.NewBodyFromString("bbbbbbbbbbb") + res, err := BOS_CLIENT.SimpleAppendObject(EXISTS_BUCKET, "test-append-object", body, 11) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestSimpleAppendObjectFromString(t *testing.T) { + res, err := BOS_CLIENT.SimpleAppendObjectFromString( + EXISTS_BUCKET, "test-append-object", "123", 22) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestSimpleAppendObjectFromFile(t *testing.T) { + fname := "/tmp/test-append-file" + f, _ := os.Create(fname) + f.WriteString("12345") + f.Close() + res, err := BOS_CLIENT.SimpleAppendObjectFromFile(EXISTS_BUCKET, "test-append-object", fname, 25) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + os.Remove(fname) +} +func TestDeleteObject(t *testing.T) { + err := BOS_CLIENT.DeleteObject(EXISTS_BUCKET, "test-put-object") + ExpectEqual(t.Errorf, err, nil) +} +func TestDeleteMultipleObjectsFromString(t *testing.T) { + multiDeleteStr := `{ + "objects":[ + {"key": "aaaa"}, + {"key": "test-copy-object"}, + {"key": "test-append-object"}, + {"key": "cccc"} + ] +}` + res, err := BOS_CLIENT.DeleteMultipleObjectsFromString(EXISTS_BUCKET, multiDeleteStr) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestDeleteMultipleObjectsFromStruct(t *testing.T) { + multiDeleteObj := &api.DeleteMultipleObjectsArgs{[]api.DeleteObjectArgs{ + api.DeleteObjectArgs{"1"}, api.DeleteObjectArgs{"test-fetch-object"}}} + res, err := BOS_CLIENT.DeleteMultipleObjectsFromStruct(EXISTS_BUCKET, multiDeleteObj) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestDeleteMultipleObjectsFromKeyList(t *testing.T) { + keyList := []string{"aaaa", "test-copy-object", "test-append-object", "cccc"} + res, err := BOS_CLIENT.DeleteMultipleObjectsFromKeyList(EXISTS_BUCKET, keyList) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestInitiateMultipartUpload(t *testing.T) { + args := &api.InitiateMultipartUploadArgs{Expires: "aaaaaaa"} + res, err := BOS_CLIENT.InitiateMultipartUpload(EXISTS_BUCKET, "test-multipart-upload", "", args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + err1 := BOS_CLIENT.AbortMultipartUpload(EXISTS_BUCKET, + "test-multipart-upload", res.UploadId) + ExpectEqual(t.Errorf, err1, nil) +} +func TestBasicInitiateMultipartUpload(t *testing.T) { + res, err := BOS_CLIENT.BasicInitiateMultipartUpload(EXISTS_BUCKET, "test-multipart-upload") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + err1 := BOS_CLIENT.AbortMultipartUpload(EXISTS_BUCKET, + "test-multipart-upload", res.UploadId) + ExpectEqual(t.Errorf, err1, nil) +} +func TestUploadPart(t *testing.T) { + res, err := BOS_CLIENT.UploadPart(EXISTS_BUCKET, "a", "b", 1, nil, nil) + t.Logf("%+v, %+v", res, err) +} +func TestUploadPartCopy(t *testing.T) { + res, err := BOS_CLIENT.UploadPartCopy(EXISTS_BUCKET, "test-multipart-upload", + EXISTS_BUCKET, "test-multipart-copy", "12345", 1, nil) + t.Logf("%+v, %+v", res, err) +} +func TestBasicUploadPartCopy(t *testing.T) { + res, err := BOS_CLIENT.BasicUploadPartCopy(EXISTS_BUCKET, "test-multipart-upload", + EXISTS_BUCKET, "test-multipart-copy", "12345", 1) + t.Logf("%+v, %+v", res, err) +} +func TestListMultipartUploads(t *testing.T) { + args := &api.ListMultipartUploadsArgs{MaxUploads: 10} + res, err := BOS_CLIENT.ListMultipartUploads(EXISTS_BUCKET, args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestBasicListMultipartUploads(t *testing.T) { + res, err := BOS_CLIENT.BasicListMultipartUploads(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) +} +func TestUploadSuperFile(t *testing.T) { + err := BOS_CLIENT.UploadSuperFile(EXISTS_BUCKET, "super-object", "test-object", "") + ExpectEqual(t.Errorf, err, nil) + err = BOS_CLIENT.UploadSuperFile(EXISTS_BUCKET, "not-exist", "not-exist", "") + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%+v", err) +} +func TestDownloadSuperFile(t *testing.T) { + err := BOS_CLIENT.DownloadSuperFile(EXISTS_BUCKET, "super-object", "/dev/null") + ExpectEqual(t.Errorf, err, nil) + err = BOS_CLIENT.DownloadSuperFile(EXISTS_BUCKET, "not-exist", "/tmp/not-exist") + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%+v", err) +} + +func TestGeneratePresignedUrl(t *testing.T) { + url := BOS_CLIENT.BasicGeneratePresignedUrl(EXISTS_BUCKET, EXISTS_OBJECT, 100) + resp, err := http.Get(url) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, resp.StatusCode, 200) + params := map[string]string{"responseContentType": "text"} + url = BOS_CLIENT.GeneratePresignedUrl(EXISTS_BUCKET, EXISTS_OBJECT, 1000, "HEAD", nil, params) + resp, err = http.Head(url) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, resp.StatusCode, 200) + BOS_CLIENT.Config.Endpoint = "10.180.112.31" + url = BOS_CLIENT.GeneratePresignedUrl(EXISTS_BUCKET, EXISTS_OBJECT, 100, "HEAD", nil, params) + resp, err = http.Head(url) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, resp.StatusCode, 200) + BOS_CLIENT.Config.Endpoint = "10.180.112.31:80" + url = BOS_CLIENT.GeneratePresignedUrl(EXISTS_BUCKET, EXISTS_OBJECT, 100, "HEAD", nil, params) + resp, err = http.Head(url) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, resp.StatusCode, 200) +} + +func TestGeneratePresignedUrl1(t *testing.T) { + + url := BOS_CLIENT.GeneratePresignedUrlPathStyle(EXISTS_BUCKET, EXISTS_OBJECT, 1000, "", nil, nil) + t.Logf("res:%v\n", url) +} + +func TestPutObjectAcl(t *testing.T) { + acl := `{ + "accessControlList":[ + { + "grantee":[{ + "id":"e13b12d0131b4c8bae959df4969387b8" + }], + "permission":["READ"] + } + ] +}` + body, _ := bce.NewBodyFromString(acl) + err := BOS_CLIENT.PutObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT, body) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "READ") +} +func TestPutObjectAclFromCanned(t *testing.T) { + err := BOS_CLIENT.PutObjectAclFromCanned(EXISTS_BUCKET, EXISTS_OBJECT, api.CANNED_ACL_PUBLIC_READ) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) +} +func TestPutObjectAclGrantRead(t *testing.T) { + err := BOS_CLIENT.PutObjectAclGrantRead(EXISTS_BUCKET, + EXISTS_OBJECT, "e13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "READ") +} +func TestPutObjectAclGrantFullControl(t *testing.T) { + err := BOS_CLIENT.PutObjectAclGrantFullControl(EXISTS_BUCKET, + EXISTS_OBJECT, "e13b12d0131b4c8bae959df4969387b8") + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "FULL_CONTROL") +} +func TestPutObjectAclFromFile(t *testing.T) { + acl := `{ + "accessControlList":[ + { + "grantee":[{ + "id":"e13b12d0131b4c8bae959df4969387b8" + }], + "permission":["READ"] + } + ] +}` + fname := "/tmp/test-put-object-acl-by-file" + f, _ := os.Create(fname) + f.WriteString(acl) + f.Close() + err := BOS_CLIENT.PutObjectAclFromFile(EXISTS_BUCKET, EXISTS_OBJECT, fname) + os.Remove(fname) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "READ") +} +func TestPutObjectAclFromString(t *testing.T) { + acl := `{ + "accessControlList":[ + { + "grantee":[{ + "id":"e13b12d0131b4c8bae959df4969387b8" + }], + "permission":["FULL_CONTROL"] + } + ] +}` + err := BOS_CLIENT.PutObjectAclFromString(EXISTS_BUCKET, EXISTS_OBJECT, acl) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "FULL_CONTROL") +} +func TestPutObjectAclFromStruct(t *testing.T) { + aclObj := &api.PutObjectAclArgs{ + []api.GrantType{ + api.GrantType{ + Grantee: []api.GranteeType{ + api.GranteeType{"e13b12d0131b4c8bae959df4969387b8"}, + }, + Permission: []string{ + "READ", + }, + }, + }, + } + err := BOS_CLIENT.PutObjectAclFromStruct(EXISTS_BUCKET, EXISTS_OBJECT, aclObj) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) + ExpectEqual(t.Errorf, res.AccessControlList[0].Permission[0], "READ") +} +func TestDeleteObjectAcl(t *testing.T) { + err := BOS_CLIENT.DeleteObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetObjectAcl(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v, %v", res, err) +} + +func TestPutBucketTrash(t *testing.T) { + args := api.PutBucketTrashReq{ + TrashDir: ".trash", + } + + err := BOS_CLIENT.PutBucketTrash(EXISTS_BUCKET, args) + ExpectEqual(t.Errorf, err, nil) + + res, err := BOS_CLIENT.GetBucketTrash(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, false) + t.Logf("%v, %v", res, err) +} + +func TestDeleteBucketTrash(t *testing.T) { + err := BOS_CLIENT.DeleteBucketTrash(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + + res, err := BOS_CLIENT.GetBucketTrash(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v, %v", res, err) +} + +func TestPutBucketNotification(t *testing.T) { + notificationReq := api.PutBucketNotificationReq{ + Notifications: []api.PutBucketNotificationSt{ + { + Id: "water-test-1", + Name: "water-rule-1", + AppId: "water-app-id-1", + Status: "enabled", + Resources: []string{EXISTS_BUCKET + "/path1", "/path2"}, + Events: []string{"PutObject"}, + Apps: []api.PutBucketNotificationAppsSt{ + { + Id: "app-id-1", + EventUrl: "http://xxx.com/event", + XVars: "", + }, + }, + }, + }, + } + + err := BOS_CLIENT.PutBucketNotification(EXISTS_BUCKET, notificationReq) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketNotification(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, false) + t.Logf("%v, %v", res, err) +} + +func TestDeleteBucketNotification(t *testing.T) { + err := BOS_CLIENT.DeleteBucketNotification(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + res, err := BOS_CLIENT.GetBucketNotification(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err != nil, true) + t.Logf("%v, %v", res, err) +} + +func TestParallelUpload(t *testing.T) { + res, err := BOS_CLIENT.ParallelUpload(EXISTS_BUCKET, "test_multiupload", "test_object", "", nil) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v,%v", res, err) +} + +func TestParallelCopy(t *testing.T) { + args := api.MultiCopyObjectArgs{ + StorageClass: api.STORAGE_CLASS_COLD, + } + res, err := BOS_CLIENT.ParallelCopy(EXISTS_BUCKET, "test_multiupload", EXISTS_BUCKET, "test_multiupload_copy", &args, nil) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v,%v", res, err) +} + +func TestBucketTag(t *testing.T) { + args := &api.PutBucketTagArgs{ + Tags: []api.Tag{ + { + TagKey: "key1", + TagValue: "value1", + }, + }, + } + err := BOS_CLIENT.PutBucketTag(EXISTS_BUCKET, args) + ExpectEqual(t.Errorf, err, nil) + _, err = BOS_CLIENT.GetBucketTag(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + err = BOS_CLIENT.DeleteBucketTag(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) +} + +func TestSymLink(t *testing.T) { + args := &api.PutSymlinkArgs{} + + err := BOS_CLIENT.PutSymlink(EXISTS_BUCKET, "test-symlink", EXISTS_OBJECT, args) + ExpectEqual(t.Errorf, err, nil) + + res, err := BOS_CLIENT.GetSymlink(EXISTS_BUCKET, EXISTS_OBJECT) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, res, "test-symlink") + t.Logf("%v, %v", res, err) +} + +func TestBucketMirror(t *testing.T) { + args := &api.PutBucketMirrorArgs{ + BucketMirroringConfiguration: []api.MirrorConfigurationRule{ + { + SourceUrl: "http://gosdk-unittest-bucket.bj.bcebos.com", + Prefix: "testprefix", + StorageClass: api.STORAGE_CLASS_STANDARD, + Mode: "fetch", + }, + }, + } + + err := BOS_CLIENT.PutBucketMirror(EXISTS_BUCKET, args) + ExpectEqual(t.Errorf, err, nil) + MirroConfig, err := BOS_CLIENT.GetBucketMirror(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, MirroConfig.BucketMirroringConfiguration[0].SourceUrl, "http://gosdk-unittest-bucket.bj.bcebos.com") + ExpectEqual(t.Errorf, MirroConfig.BucketMirroringConfiguration[0].Prefix, "testprefix") + err = BOS_CLIENT.DeleteBucketMirror(EXISTS_BUCKET) + ExpectEqual(t.Errorf, err, nil) +} diff --git a/bce-sdk-go/services/bvw/api/edit.go b/bce-sdk-go/services/bvw/api/edit.go new file mode 100644 index 0000000..d6e9abd --- /dev/null +++ b/bce-sdk-go/services/bvw/api/edit.go @@ -0,0 +1,152 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +func CreateDraft(cli bce.Client, request *CreateDraftRequest) (*MatlibTaskResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getDraftURL()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(request) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &MatlibTaskResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func GetSingleDraft(cli bce.Client, id int) (*GetDraftResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getDraftURL() + "/" + strconv.Itoa(id) + "/" + "draftAndTimeline") + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetDraftResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetDraftList(cli bce.Client, request *DraftListRequest) (*ListByPageResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getDraftURL()) + req.SetMethod(http.GET) + + paramsMap := make(map[string]string) + paramsMap["status"] = request.Status + paramsMap["beginTime"] = request.BeginTime + paramsMap["endTime"] = request.EndTime + paramsMap["pageNo"] = strconv.Itoa(request.PageNo) + paramsMap["pageSize"] = strconv.Itoa(request.PageSize) + + req.SetParams(paramsMap) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListByPageResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func UpdateDraft(cli bce.Client, id int, request *MatlibTaskRequest) error { + req := &bce.BceRequest{} + req.SetUri(getDraftURL() + "/" + strconv.Itoa(id) + "/" + "draftAndTimeline") + req.SetMethod(http.PUT) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(request) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func PollingVideoEdit(cli bce.Client, id int) (*VideoEditPollingResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getPollingVideoURL() + strconv.Itoa(id)) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &VideoEditPollingResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func CreateVideoEdit(cli bce.Client, request *VideoEditCreateRequest) (*VideoEditCreateResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getCreateVideoURL()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(request) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &VideoEditCreateResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/bvw/api/matlib.go b/bce-sdk-go/services/bvw/api/matlib.go new file mode 100644 index 0000000..c2650b4 --- /dev/null +++ b/bce-sdk-go/services/bvw/api/matlib.go @@ -0,0 +1,289 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +func UploadMaterial(client bce.Client, matlibUploadRequest *MatlibUploadRequest) (*MatlibUploadResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getUploadMaterial()) + req.SetParam("upload", "") + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(matlibUploadRequest) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := client.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &MatlibUploadResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func SearchMaterial(cli bce.Client, materialSearchRequest *MaterialSearchRequest) (*MaterialSearchResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMaterialLibrary()) + req.SetMethod(http.GET) + + paramsMap := make(map[string]string) + if materialSearchRequest.End != "" { + paramsMap["end"] = materialSearchRequest.End + } + if materialSearchRequest.Begin != "" { + paramsMap["begin"] = materialSearchRequest.Begin + } + if materialSearchRequest.InfoType != "" { + paramsMap["infoType"] = materialSearchRequest.InfoType + } + if materialSearchRequest.MediaType != "" { + paramsMap["mediaType"] = materialSearchRequest.MediaType + } + if materialSearchRequest.Status != "" { + paramsMap["status"] = materialSearchRequest.Status + } + if materialSearchRequest.SourceType != "" { + paramsMap["begin"] = materialSearchRequest.Begin + } + if materialSearchRequest.TitleKeyword != "" { + paramsMap["titleKeyword"] = materialSearchRequest.TitleKeyword + } + if materialSearchRequest.PageNo >= 1 { + paramsMap["pageNo"] = strconv.Itoa(materialSearchRequest.PageNo) + } + if materialSearchRequest.Size >= 1 { + paramsMap["size"] = strconv.Itoa(materialSearchRequest.Size) + } + + req.SetParams(paramsMap) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &MaterialSearchResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetMaterial(cli bce.Client, id string) (*MaterialGetResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMaterialLibrary() + "/" + id) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &MaterialGetResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func DeleteMaterial(cli bce.Client, id string) error { + req := &bce.BceRequest{} + req.SetUri(getMaterialLibrary() + "/" + id) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func UploadMaterialPreset(cli bce.Client, fileType string, request *MatlibUploadRequest) (*MaterialPresetUploadResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMateriaPresrtURL() + fileType) + req.SetParam("upload", "") + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(request) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &MaterialPresetUploadResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func SearchMaterialPreset(cli bce.Client, request *MaterialPresetSearchRequest) (*MaterialPresetSearchResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMateriaPresrtURL()) + req.SetMethod(http.GET) + + paramsMap := make(map[string]string) + + if request.MediaType != "" { + paramsMap["type"] = request.MediaType + } + if request.Status != "" { + paramsMap["status"] = request.Status + } + if request.SourceType != "" { + paramsMap["sourceType"] = request.SourceType + } + if request.PageNo != "" { + paramsMap["pageNo"] = request.PageNo + } else { + paramsMap["pageNo"] = "1" + } + if request.PageSize != "" { + paramsMap["pageSize"] = request.PageSize + } else { + paramsMap["pageSize"] = "10" + } + + req.SetParams(paramsMap) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &MaterialPresetSearchResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetMaterialPreset(cli bce.Client, id string) (*MaterialPresetGetResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMateriaPresrtURL() + id) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &MaterialPresetGetResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func DeleteMaterialPreset(cli bce.Client, id string) error { + req := &bce.BceRequest{} + req.SetUri(getMateriaPresrtURL() + id) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func CreateMatlibConfig(cli bce.Client, request *MatlibConfigBaseRequest) (*bce.BceResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMatlibConfigURL()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(request) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + return resp, nil +} + +func GetMatlibConfig(cli bce.Client) (*MatlibConfigGetResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMatlibConfigURL()) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &MatlibConfigGetResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func UpdateMatlibConfig(cli bce.Client, request *MatlibConfigUpdateRequest) error { + req := &bce.BceRequest{} + req.SetUri(getMatlibConfigURL()) + req.SetMethod(http.PUT) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(request) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/bvw/api/model.go b/bce-sdk-go/services/bvw/api/model.go new file mode 100644 index 0000000..1ab31a3 --- /dev/null +++ b/bce-sdk-go/services/bvw/api/model.go @@ -0,0 +1,300 @@ +package api + +type MatlibUploadRequest struct { + MediaType string `json:"mediaType"` + Title string `json:"title"` + Bucket string `json:"bucket"` + Key string `json:"key"` + Notification string `json:"notification"` +} + +type MatlibUploadResponse struct { + Id string `json:"materialId"` +} + +type MaterialSearchRequest struct { + InfoType string `json:"infoType"` + MediaType string `json:"mediaType"` + SourceType string `json:"sourceType"` + Status string `json:"status"` + TitleKeyword string `json:"titleKeyword"` + PageNo int `json:"pageNo"` + Size int `json:"size"` + Begin string `json:"begin"` + End string `json:"end"` +} + +type MaterialSearchResponse struct { + Items []MaterialGetResponse `json:"items,omitempty"` +} + +type MaterialGetResponse struct { + ID string `json:"id"` + UserID string `json:"userId"` + InfoType string `json:"infoType,omitempty"` + MediaType string `json:"mediaType,omitempty"` + SourceType string `json:"sourceType"` + Status string `json:"status"` + Title string `json:"title"` + SourceURL string `json:"sourceUrl"` + SourceURL360P string `json:"sourceUrl360p"` + ThumbnailList []string `json:"thumbnailList"` + SubtitleUrls []string `json:"subtitleUrls"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` + Duration float64 `json:"duration"` + Height int `json:"height"` + Width int `json:"width"` + Bucket string `json:"bucket"` + Key string `json:"key"` + Key360P string `json:"key360p"` + Key720P string `json:"key720p"` + AudioKey string `json:"audioKey"` + ThumbnailKeys []string `json:"thumbnailKeys"` + Subtitles []string `json:"subtitles"` +} + +type MaterialPresetUploadResponse struct { + Id string `json:"id"` +} + +type MaterialPresetSearchRequest struct { + SourceType string `json:"sourceType"` + Status string `json:"status"` + MediaType string `json:"type"` + PageNo string `json:"pageNo"` + PageSize string `json:"pageSize"` +} + +type MaterialPresetSearchResponse struct { + Result []PresetResponseWrapper `json:"result"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type PresetResponseWrapper struct { + MaterialType string `json:"type"` + Addons []MaterialPresetGetResponse `json:"addons"` +} + +type MaterialPresetGetResponse struct { + ID string `json:"id"` + Status string `json:"status"` + UserID string `json:"userId"` + Title string `json:"title"` + Tag string `json:"tag"` + Type string `json:"type"` + SourceType string `json:"sourceType"` + PreviewMaterialIds map[string]interface{} `json:"previewMaterialIds"` + PreviewBucket map[string]interface{} `json:"previewBucket"` + PreviewKeys map[string]interface{} `json:"previewKeys"` + PreviewUrls map[string]interface{} `json:"previewUrls"` + MaterialID string `json:"materialId"` + Bucket string `json:"bucket"` + Key string `json:"key"` + SourceURL string `json:"sourceUrl"` + Config string `json:"config"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type MatlibConfigGetResponse struct { + Bucket string `json:"bucket"` +} + +type MatlibConfigBaseRequest struct { + Bucket string `json:"bucket"` +} + +type MatlibConfigUpdateRequest struct { + Bucket string `json:"bucket"` +} + +type CreateDraftRequest struct { + Titile string `json:"title"` + Ratio string `json:"ratio"` + Duration string `json:"duration"` +} + +type MatlibTaskResponse struct { + Id int `json:"id"` +} + +type Otimeline struct { + Itimeline Itimeline `json:"timeline"` + Meta interface{} `json:"meta"` +} + +type Itimeline struct { + Video []MediaPair `json:"video"` + Audio []MediaPair `json:"audio"` + Sticker []MediaPair `json:"sticker"` + Subtitle []interface{} `json:"subtitle"` +} + +type MatlibTaskRequest struct { + Title string `json:"title"` + Ratio string `json:"ratio"` + Duration string `json:"duration"` + Timeline Otimeline `json:"timeline"` + ResourceList []MaterialGetResponse `json:"resourceList"` + CoverBucekt string `json:"coverBucket"` + CoverKey string `json:"coverKey"` + LastUpdateTime string `json:"lastUpdateTime"` +} + +type GetDraftResponse struct { + Otimeline Otimeline `json:"timeline"` + ResourceList []GetMaterialResponse `json:"resourceList,omitempty"` + Title string `json:"title"` + Ratio string `json:"ratio"` + CoverBucket string `json:"coverBucket"` + CoverKey string `json:"coverKey"` + Endpoint string `json:"endpoint"` + LastUpdateTime string `json:"lastUpdateTime"` +} +type GetMaterialResponse struct { + ID string `json:"id,omitempty"` + UserID string `json:"userId,omitempty"` + ActualUserID string `json:"actualUserId,omitempty"` + SaasType string `json:"saasType,omitempty"` + InfoType string `json:"infoType,omitempty"` + MediaType string `json:"mediaType,omitempty"` + SourceType string `json:"sourceType,omitempty"` + Status string `json:"status,omitempty"` + Title string `json:"title,omitempty"` + SourceURL string `json:"sourceUrl,omitempty"` + SourceURL360P string `json:"sourceUrl360p,omitempty"` + AudioURL string `json:"audioUrl,omitempty"` + ThumbnailList []string `json:"thumbnailList,omitempty"` + SubtitleUrls []string `json:"subtitleUrls,omitempty"` + CreateTime string `json:"createTime,omitempty"` + UpdateTime string `json:"updateTime,omitempty"` + Duration float64 `json:"duration,omitempty"` + Height int `json:"height,omitempty"` + Width int `json:"width,omitempty"` + FileSizeInByte int `json:"fileSizeInByte,omitempty"` + Bucket string `json:"bucket,omitempty"` + Key string `json:"key,omitempty"` + Key360P string `json:"key360p,omitempty"` + Key720P string `json:"key720p,omitempty"` + AudioKey string `json:"audioKey,omitempty"` + ThumbnailKeys []string `json:"thumbnailKeys,omitempty"` + Subtitles []string `json:"subtitles,omitempty"` + Endpoint string `json:"endpoint,omitempty"` +} + +type MediaPair struct { + Key string `json:"key"` + List []TimelineMaterial `json:"list"` + IsMaster bool `json:"isMaster"` +} + +type MediaInfo struct { + FileType string `json:"fileType,omitempty"` + SourceType string `json:"sourceType,omitempty"` + SourceURL string `json:"sourceUrl,omitempty"` + AudioURL string `json:"audioUrl,omitempty"` + Bucket string `json:"bucket,omitempty"` + Key string `json:"key,omitempty"` + AudioKey string `json:"audioKey,omitempty"` + InstanceID string `json:"instanceId,omitempty"` + CoverImage string `json:"coverImage,omitempty"` + Duration float64 `json:"duration,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` + Errmsg string `json:"errmsg,omitempty"` + Status string `json:"status,omitempty"` + Progress string `json:"progress,omitempty"` + Action string `json:"action,omitempty"` + Size int `json:"size,omitempty"` + Name string `json:"name,omitempty"` + ThumbnailPrefix string `json:"thumbnailPrefix,omitempty"` + ThumbnailKeys []string `json:"thumbnailKeys,omitempty"` + ThumbnailList []string `json:"thumbnailList,omitempty"` + SubtitleKeys []string `json:"subtitleKeys,omitempty"` + MediaID string `json:"mediaId,omitempty"` + Offstandard bool `json:"offstandard,omitempty"` +} + +type TimelineMaterial struct { + Start float64 `json:"start"` + End float64 `json:"end"` + ShowStart float64 `json:"showStart"` + ShowEnd float64 `json:"showEnd"` + Duration float64 `json:"duration"` + Xpos float64 `json:"xpos"` + Ypos float64 `json:"ypos"` + Width float64 `json:"width"` + Height float64 `json:"height"` + MediaInfo MediaInfo `json:"mediaInfo"` + Type string `json:"type"` + UID string `json:"uid"` + Name string `json:"name"` + ExtInfo interface{} `json:"extInfo"` +} + +type ListByPageResponse struct { + Data []MatlibTaskGetResponse `json:"data"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type MatlibTaskGetResponse struct { + ID int `json:"id"` + ResMaterialID string `json:"resMaterialId"` + UserID string `json:"userId"` + Title string `json:"title"` + Status string `json:"status"` + ErrorMessage string `json:"errorMessage"` + CoverURL string `json:"coverUrl"` + LastUpdateTime string `json:"lastUpdateTime"` +} + +type DraftListRequest struct { + Status string `json:"status"` + BeginTime string `json:"beginTime"` + EndTime string `json:"endTime"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type VideoEditPollingResponse struct { + Errorno int `json:"errorno"` + Errmsg string `json:"errmsg"` + Data Data `json:"data"` +} + +type Data struct { + EditID int `json:"editId"` + EditStatus string `json:"editStatus"` + Bucket string `json:"bucket"` + Key string `json:"key"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type VideoEditCreateRequest struct { + Title string `json:"title"` + Bucket string `json:"bucket"` + KeyPath string `json:"keyPath"` + TaskId string `json:"taskId"` + Notification string `json:"notification"` + ExtInfo interface{} `json:"extInfo"` + Cmd interface{} `json:"cmd"` + Endpoint string `json:"endpoint"` +} + +type VideoEditCreateResponse struct { + Errorno int `json:"errorno"` + Errmsg string `json:"errmsg"` + Data string `json:"data"` + Ret Ret `json:"ret"` + Ie string `json:"ie"` +} +type Ret struct { + EditID int `json:"editId"` + BosKey string `json:"bosKey"` +} diff --git a/bce-sdk-go/services/bvw/api/utils.go b/bce-sdk-go/services/bvw/api/utils.go new file mode 100644 index 0000000..989b9fc --- /dev/null +++ b/bce-sdk-go/services/bvw/api/utils.go @@ -0,0 +1,41 @@ +package api + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + BVW_PREFIX = bce.URI_PREFIX + "v1/" + MATERIALIBRARY = "materialLibrary" + MATLIB = "matlib" + PRESET = "/preset/" + CONFIG = "/config" + POLLINGVIDEO = "videoEdit/pollingVideo/" + CREATEVIDEO = "videoEdit/createNewVideo" +) + +func getMaterialLibrary() string { + return BVW_PREFIX + MATERIALIBRARY +} + +func getUploadMaterial() string { + return BVW_PREFIX + MATLIB +} + +func getMateriaPresrtURL() string { + return BVW_PREFIX + MATERIALIBRARY + PRESET +} + +func getMatlibConfigURL() string { + return BVW_PREFIX + MATLIB + CONFIG +} + +func getDraftURL() string { + return BVW_PREFIX + MATLIB +} + +func getPollingVideoURL() string { + return BVW_PREFIX + POLLINGVIDEO +} + +func getCreateVideoURL() string { + return BVW_PREFIX + CREATEVIDEO +} diff --git a/bce-sdk-go/services/bvw/client.go b/bce-sdk-go/services/bvw/client.go new file mode 100644 index 0000000..bd164fd --- /dev/null +++ b/bce-sdk-go/services/bvw/client.go @@ -0,0 +1,126 @@ +package bvw + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/bvw/api" +) + +type Client struct { + *bce.BceClient +} + +const DEFAULT_SERVICE_DOMAIN = "bvw.bj.baidubce.com" + +// NewClient make BVW service client with defualt configuration +// endPoint value only bj can be chosed and enPoint value defualt bj +func NewClient(ak, sk, endPoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endPoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// upload video /audio/picture to MaterialLibaray +func (cli *Client) UploadMaterial(request *api.MatlibUploadRequest) (*api.MatlibUploadResponse, error) { + return api.UploadMaterial(cli, request) +} + +// search material +func (cli *Client) SearchMaterial(materialSearchRequest *api.MaterialSearchRequest) (*api.MaterialSearchResponse, error) { + return api.SearchMaterial(cli, materialSearchRequest) +} + +// get material by materialId +func (cli *Client) GetMaterial(id string) (*api.MaterialGetResponse, error) { + return api.GetMaterial(cli, id) +} + +// delete material by materialId +func (cli *Client) DeleteMaterial(id string) error { + return api.DeleteMaterial(cli, id) +} + +// upload preset materials to the media library +func (cli *Client) UploadMaterialPreset(fileType string, request *api.MatlibUploadRequest) ( + *api.MaterialPresetUploadResponse, error) { + return api.UploadMaterialPreset(cli, fileType, request) +} + +// search preset materials +func (cli Client) SearchMaterialPreset(request *api.MaterialPresetSearchRequest) (*api.MaterialPresetSearchResponse, error) { + return api.SearchMaterialPreset(cli, request) +} + +// get preset matertials by id +func (cli Client) GetMaterialPreset(id string) (*api.MaterialPresetGetResponse, error) { + return api.GetMaterialPreset(cli, id) +} + +// delete preset matertials by id +func (cli *Client) DeleteMaterialPreset(id string) error { + return api.DeleteMaterialPreset(cli, id) +} + +// create matlib config +func (cli *Client) CreateMatlibConfig(request *api.MatlibConfigBaseRequest) (*bce.BceResponse, error) { + return api.CreateMatlibConfig(cli, request) +} + +// get matlib config +func (cli *Client) GetMatlibConfig() (*api.MatlibConfigGetResponse, error) { + return api.GetMatlibConfig(cli) +} + +// update matlib config +func (cli *Client) UpdateMatlibConfig(request *api.MatlibConfigUpdateRequest) error { + return api.UpdateMatlibConfig(cli, request) +} + +// create edit draft +func (cli *Client) CreateDraft(request *api.CreateDraftRequest) (*api.MatlibTaskResponse, error) { + return api.CreateDraft(cli, request) +} + +// get draft and timeline with matlib task id +func (cli *Client) GetSingleDraft(id int) (*api.GetDraftResponse, error) { + return api.GetSingleDraft(cli, id) +} + +// get draft list +func (cli *Client) GetDraftList(request *api.DraftListRequest) (*api.ListByPageResponse, error) { + return api.GetDraftList(cli, request) +} + +// update draft by id +func (cli *Client) UpdateDraft(id int, request *api.MatlibTaskRequest) error { + return api.UpdateDraft(cli, id, request) +} + +// query video edit job status +func (cli *Client) PollingVideoEdit(id int) (*api.VideoEditPollingResponse, error) { + return api.PollingVideoEdit(cli, id) +} + +// create edit job +func (cli *Client) CreateVideoEdit(request *api.VideoEditCreateRequest) (*api.VideoEditCreateResponse, error) { + return api.CreateVideoEdit(cli, request) +} diff --git a/bce-sdk-go/services/bvw/client_test.go b/bce-sdk-go/services/bvw/client_test.go new file mode 100644 index 0000000..7f05ee7 --- /dev/null +++ b/bce-sdk-go/services/bvw/client_test.go @@ -0,0 +1,362 @@ +package bvw + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/services/bvw/api" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + BVW_CLIENT *Client +) + +type Conf struct { + AK string + SK string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given: %+v\n", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + BVW_CLIENT, _ = NewClient(confObj.AK, confObj.SK, "") + log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestUploadMaterial(t *testing.T) { + req := &api.MatlibUploadRequest{} + req.Key = "dog.mp4" + req.Bucket = "bvw-console" + req.Title = "split_result_267392.mp4" + req.MediaType = "video" + uploadResponse, err := BVW_CLIENT.UploadMaterial(req) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", uploadResponse) +} + +func TestSearchMaterial(t *testing.T) { + req := &api.MaterialSearchRequest{} + req.Size = 5 + req.PageNo = 1 + req.Status = "FINISHED" + req.MediaType = "video" + req.Begin = "2023-01-11T16:00:00Z" + req.End = "2023-04-12T15:59:59Z" + materialResp, err := BVW_CLIENT.SearchMaterial(req) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", materialResp) +} + +func TestGetMaterial(t *testing.T) { + materialGetResponse, err := BVW_CLIENT.GetMaterial("d9b9f08ef1e0a28967fa0f7b5819db30") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", materialGetResponse) +} + +func TestDeleteMaterial(t *testing.T) { + err := BVW_CLIENT.DeleteMaterial("d9b9f08ef1e0a28967fa0f7b5819db30") + ExpectEqual(t.Errorf, err, nil) +} + +func TestUploadMaterialPreset(t *testing.T) { + req := &api.MatlibUploadRequest{} + req.Key = "item2.jpeg" + req.Bucket = "bvw-console" + req.Title = "item2.jpeg" + req.MediaType = "image" + uploadResponse, err := BVW_CLIENT.UploadMaterialPreset("PICTURE", req) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", uploadResponse) +} + +func TestSearchMaterialPreset(t *testing.T) { + req := &api.MaterialPresetSearchRequest{} + req.PageSize = "10" + req.Status = "FINISHED" + req.PageNo = "1" + req.SourceType = "USER" + req.MediaType = "PICTURE" + response, err := BVW_CLIENT.SearchMaterialPreset(req) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestGetMaterialPreset(t *testing.T) { + response, err := BVW_CLIENT.GetMaterialPreset("cc0aabdc71421abaa17e80a26caa009f") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestDeleteMaterialPreset(t *testing.T) { + err := BVW_CLIENT.DeleteMaterialPreset("cc0aabdc71421abaa17e80a26caa009f") + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateMatlibConfig(t *testing.T) { + request := &api.MatlibConfigBaseRequest{ + Bucket: "go-test"} + response, err := BVW_CLIENT.CreateMatlibConfig(request) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestGetMatlibConfig(t *testing.T) { + response, err := BVW_CLIENT.GetMatlibConfig() + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestUpdateMatlibConfig(t *testing.T) { + err := BVW_CLIENT.UpdateMatlibConfig(&api.MatlibConfigUpdateRequest{Bucket: "go-test"}) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateDraft(t *testing.T) { + response, err := BVW_CLIENT.CreateDraft(&api.CreateDraftRequest{ + Duration: "0", + Titile: "testCreateDraft3", + Ratio: "hori16x9"}) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestGetSingleDraft(t *testing.T) { + response, err := BVW_CLIENT.GetSingleDraft(1017834) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestGetDraftList(t *testing.T) { + response, err := BVW_CLIENT.GetDraftList(&api.DraftListRequest{ + PageNo: 1, + PageSize: 20, + BeginTime: "2023-01-11T16:00:00Z", + EndTime: "2023-04-12T15:59:59Z"}) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestUpdateDraft(t *testing.T) { + var request api.MatlibTaskRequest + jsonStr := "{\"title\":\"updatesucess\",\"draftId\":\"1017890\",\"timeline\":{\"timeline\":{\"video\":[{\"key\"" + + ":\"name\",\"isMaster\":true,\"list\":[{\"type\":\"video\",\"start\":0,\"end\":5.859375,\"showStart\":0," + + "\"showEnd\":5.859375,\"xpos\":0,\"ypos\":0,\"width\":1280,\"height\":720,\"duration\":5.859375,\"extInfo" + + "\":{\"style\":\"\",\"lightness\":0,\"gifMode\":0,\"contrast\":0,\"saturation\":0,\"hue\":0,\"speed\":1" + + ",\"transitionStart\":\"\",\"transitionEnd\":\"black\",\"transitionDuration\":1,\"volume\":1,\"rotate\":0," + + "\"mirror\":\"\",\"blankArea\":\"\"},\"mediaInfo\":{\"fileType\":\"video\",\"sourceType\":\"USER\",\"" + + "sourceUrl\":\"https://bj.bcebos.com/v1/bvw-console/360p/dog.mp4?x-bce-security-token=" + + "ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7x" + + "G%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hb" + + "SJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRp" + + "OC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ" + + "%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2" + + "F%2Fb227edbf73344bdfc9fed00ba491c5c0c3abe229792d7b3d026604cfbe541b68\",\"audioUrl\":\"" + + "https://bj.bcebos.com/v1/bvw-console/audio/dog.mp3?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjY" + + "yYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ" + + "5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3" + + "OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzT" + + "Cgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=" + + "bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F3dcc823c9497aca1154f" + + "f0007eca86af4e682363c3ceddba0b3c74ca14e2d154\",\"bucket\":\"bvw-console\",\"key\":\"dog.mp4\",\"audioKey\":" + + "\"audio/dog.mp3\",\"coverImage\":\"https://bj.bcebos.com/v1/bvw-console/thumbnail/dog00000500.jpg" + + "?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZp" + + "Ppsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQz" + + "FlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6P" + + "z36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQj" + + "Wm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cb" + + "c0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F21a92744dfb9fc3f46745e75d095da327bb04677f9028fb85e00ff5dc7df6" + + "daf\",\"duration\":18.73,\"width\":1920,\"height\":1080,\"status\":\"FINISHED\",\"name\":\"dog.mp4\"," + + "\"thumbnailPrefix\":\"\",\"thumbnailKeys\":[\"thumbnail/dog00000500.jpg\"],\"mediaId\":\"" + + "1f10ce0db10b8eb5b2f2755daf544900\",\"offstandard\":false},\"uid\":\"a081f1c6-9dc9-4e7b-a00e-6eb5217e771d" + + "\"},{\"type\":\"video\",\"start\":5.859375,\"end\":18.73,\"showStart\":5.859375,\"showEnd\":18.73,\"xpos" + + "\":0,\"ypos\":0,\"width\":1280,\"height\":720,\"duration\":12.870625,\"extInfo\":{\"style\":\"\",\"lightness" + + "\":0,\"gifMode\":0,\"contrast\":0,\"saturation\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"black\",\"" + + "transitionEnd\":\"\",\"transitionDuration\":1,\"volume\":1,\"rotate\":0,\"mirror\":\"\",\"blankArea\":\"\"}," + + "\"mediaInfo\":{\"fileType\":\"video\",\"sourceType\":\"USER\",\"sourceUrl\":" + + "\"https://bj.bcebos.com/v1/bvw-console/360p/dog.mp4?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyN" + + "jk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9" + + "RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7D" + + "GO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df" + + "5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%" + + "3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2Fb" + + "227edbf73344bdfc9fed00ba491c5c0c3abe229792d7b3d026604cfbe541b68\",\"audioUrl\":" + + "\"https://bj.bcebos.com/v1/bvw-console/audio/dog.mp3?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjY" + + "yYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5" + + "Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3O" + + "HDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCg" + + "h8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=" + + "bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F3dcc823c9497aca1" + + "154ff0007eca86af4e682363c3ceddba0b3c74ca14e2d154\",\"bucket\":\"bvw-console\",\"key\":\"dog.mp4\",\"" + + "audioKey\":\"audio/dog.mp3\",\"coverImage\":\"https://bj.bcebos.com/v1/bvw-console/thumbnail/dog00000500" + + ".jpg?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZp" + + "Ppsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQz" + + "FlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz" + + "36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm" + + "231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0" + + "fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F21a92744dfb9fc3f46745e75d095da327bb04677f9028fb85e00ff5dc7df6da" + + "f\",\"duration\":18.73,\"width\":1920,\"height\":1080,\"status\":\"FINISHED\",\"name\":\"dog.mp4\",\"thumb" + + "nailPrefix\":\"\",\"thumbnailKeys\":[\"thumbnail/dog00000500.jpg\"],\"mediaId\":\"1f10ce0db10b8eb5b2f2755d" + + "af544900\",\"offstandard\":false},\"uid\":\"70af482e-0bf5-4c38-8f05-03c9e3b8ae03\"}],\"unlinkMaster\":true" + + "}],\"audio\":[{\"key\":\"\",\"isMaster\":false,\"list\":[{\"start\":0,\"end\":155.99,\"showStart\":" + + "0.234375,\"showEnd\":156.224375,\"duration\":155.99,\"xpos\":0,\"ypos\":0,\"hidden\":false,\"mediaInfo\"" + + ":{\"fileType\":\"audio\",\"sourceUrl\":\"https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset" + + "/music/audio/%E5%8F%A4%E9%A3%8E%E9%A3%98%E6%89%AC.mp3?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772" + + "a1409590%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F2ddcf78c92de29ae3d7c3166a4e17e7c5d07fa38dcefd24c29c4f4d5b" + + "5ba46fe\",\"audioUrl\":\"https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset/music/audio/" + + "%E5%8F%A4%E9%A3%8E%E9%A3%98%E6%89%AC.mp3?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772a1409590%2F2" + + "023-04-14T07%3A16%3A35Z%2F86400%2F%2F2ddcf78c92de29ae3d7c3166a4e17e7c5d07fa38dcefd24c29c4f4d5b5ba46fe\"," + + "\"bucket\":\"videoworks-system-preprocess\",\"key\":\"systemPreset/music/古风飘扬.aac\",\"audioKey\":\"" + + "systemPreset/music/audio/古风飘扬.mp3\",\"coverImage\":\"\",\"duration\":155.99,\"name\":\"\",\"thumbnailList" + + "\":[],\"mediaId\":\"\",\"offstandard\":false},\"type\":\"audio\",\"uid\":\"bd52be7f-1f19-4368-8c41-44e991af" + + "8164\",\"name\":\"古风飘扬\",\"extInfo\":{\"style\":\"\",\"lightness\":0,\"gifMode\":0,\"contrast\":0,\"" + + "saturation\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"\",\"transitionEnd\":\"\",\"transitionDuration" + + "\":1,\"volume\":1,\"rotate\":0},\"boxDataLeft\":4,\"dragBoxWidth\":1996.6720000000003,\"lineType\":\"audio" + + "\"}]}],\"subtitle\":[{\"key\":\"\",\"list\":[{\"duration\":3,\"hidden\":false,\"name\":\"time-place\",\"" + + "tagExtInfo\":{\"marginBottom\":0,\"textFadeIn\":1,\"textFadeOut\":1,\"textOutMaskDur\":1},\"showStart\":" + + "5.859375,\"showEnd\":8.859,\"templateId\":\"6764ce3331ea7e406e4ab4475d1dff18\",\"type\":\"subtitle\",\"uid" + + "\":\"5aaa35f4-8fae-4b8c-b7ed-761a54550244\",\"xpos\":\"0\",\"ypos\":\"309\",\"config\":[{\"alpha\":0,\"" + + "fontColor\":\"#ffffff\",\"fontSize\":50,\"fontStyle\":\"normal\",\"fontType\":\"方正时代宋 简 Extrabold\"" + + ",\"lineHeight\":1.2,\"name\":\"时间\",\"text\":\"haha\",\"backgroundColor\":\"#2468F2\",\"backgroundAlpha" + + "\":0,\"fontx\":0,\"fonty\":0,\"invisible\":false},{\"alpha\":0,\"fontColor\":\"#000000\",\"fontSize\":50," + + "\"fontStyle\":\"normal\",\"fontType\":\"方正时代宋 简 Extrabold\",\"lineHeight\":1.2,\"name\":\"地点\",\"" + + "text\":\"cd\",\"backgroundColor\":\"#ffffff\",\"backgroundAlpha\":0,\"fontx\":0,\"fonty\":0,\"invisible\"" + + ":false}],\"boxDataLeft\":76,\"dragBoxWidth\":38.400000000000006,\"lineType\":\"subtitle\"}],\"master\":" + + "false}],\"sticker\":[{\"key\":\"\",\"isMaster\":false,\"list\":[{\"showStart\":0,\"showEnd\":3,\"duration\"" + + ":3,\"xpos\":0,\"ypos\":0,\"width\":215,\"height\":120.9375,\"hidden\":false,\"mediaInfo\":{\"sourceUrl\":\"" + + "https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset/picture/%E9%9D%A2%E5%8C%85%E3%80%81%E8" + + "%82%A0.png?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772a1409590%2F2023-04-14T07%3A16%3A35Z%2F8640" + + "0%2F%2F84867e4874cc94eb374898017cb4367ed8c24a5750a9d8ebd14d8ca989cf2e53\",\"audioUrl\":\"" + + "https://bj.bcebos.com/v1/videoworks-system-preprocess/systemPreset/picture/audio/%E9%9D%A2%E5%8C%85%E3%80%" + + "81%E8%82%A0.mp3?authorization=bce-auth-v1%2F66c557960e7a4822bd82c772a1409590%2F2023-04-14T07%3A16%3A35Z%2F" + + "86400%2F%2F1807d3005f5f8fc270fa17238ec550c20162252c19952e6a45ae497ef7148086\",\"bucket\":\"" + + "videoworks-system-preprocess\",\"key\":\"systemPreset/picture/面包、肠.png\",\"audioKey\":\"systemPreset" + + "/picture/audio/面包、肠.mp3\",\"coverImage\":\"\",\"width\":215,\"height\":120,\"name\":\"\",\"thumbnailList" + + "\":[],\"mediaId\":\"\",\"offstandard\":false},\"type\":\"image\",\"uid\":\"e419b583-aedb-4265-" + + "9a67-7e21fc621f85\",\"name\":\"面包、肠\",\"extInfo\":{\"style\":\"\",\"lightness\":0,\"gifMode\":0," + + "\"contrast\":0,\"saturation\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"\",\"transitionEnd\":\"\"," + + "\"transitionDuration\":1,\"volume\":1,\"rotate\":0},\"lineType\":\"sticker\",\"boxDataLeft\":1,\"" + + "dragBoxWidth\":38.400000000000006}]}]}},\"ratio\":\"hori16x9\",\"resourceList\":[{\"id\":\"1f10ce0db10" + + "b8eb5b2f2755daf544900\",\"userId\":\"e7e47aa53fbb47dfb1e4c86424bb7ad3\",\"mediaType\":\"video\",\"" + + "sourceType\":\"USER\",\"status\":\"FINISHED\",\"title\":\"dog.mp4\",\"sourceUrl\":\"https://bj.bcebos.com" + + "/v1/bvw-console/dog.mp4?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM" + + "1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Z" + + "zgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkh" + + "MLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7" + + "D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1" + + "a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F4a3c399db912e35f6b6c008faffebe5752c47e36fcd21d4bf03" + + "bc908c3a29e5e\",\"sourceUrl360p\":\"https://bj.bcebos.com/v1/bvw-console/360p/dog.mp4?x-bce-security-toke" + + "n=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZT" + + "NAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwb" + + "rCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F" + + "9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujH" + + "KfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07" + + "%3A16%3A35Z%2F86400%2F%2Fb227edbf73344bdfc9fed00ba491c5c0c3abe229792d7b3d026604cfbe541b68\",\"audioUrl\"" + + ":\"https://bj.bcebos.com/v1/bvw-console/audio/dog.mp3?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1Z" + + "jYyYjlkZjNjODB8AAAAAM0BAABgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8" + + "sJ5Dc75AlLyVko5U4CFsiaEE9xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46Nx" + + "S3OHDvxtr95gIpW592MxArSISjn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOF" + + "zTCgh8qeej6RXfYjBKn0pvmWCKr%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorizatio" + + "n=bce-auth-v1%2F4a2cac88da9411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F3dcc823c9497aca1" + + "154ff0007eca86af4e682363c3ceddba0b3c74ca14e2d154\",\"thumbnailList\":[\"https://bj.bcebos.com/v1/bvw-cons" + + "ole/thumbnail/dog00000500.jpg?x-bce-security-token=ZjkyZmQ2YmQxZTQ3NDcyNjk0ZTg1ZjYyYjlkZjNjODB8AAAAAM0BAA" + + "BgAa0YM1kG5uQI39UZkqCZpPpsi8DEL63qLoYtl2x5OFqZTNAWS7xG%2FfhP%2BlWF9RNJhYFABpfrg8sJ5Dc75AlLyVko5U4CFsiaEE9" + + "xGdGQU4r3Zzgl1fJothQzFlDKfhH9hh9NXykFPkd4OXwbrCmrl902hbSJu8e6Q7DGO0tOi444b9K46NxS3OHDvxtr95gIpW592MxArSIS" + + "jn%2FpMVkhMLtymxh6Pz36iVdo0ErJnD1JIozvKo%2F9bV7pIjpIAysjRpOC8Df5Mh5cSG96BBwftUOFzTCgh8qeej6RXfYjBKn0pvmWCK" + + "r%2BM6bV7D39wKiQjWm231giBr3teGDbG%2BfujHKfC4tNAYpzSrCwEFCyCQ%3D%3D&authorization=bce-auth-v1%2F4a2cac88da9" + + "411edaf1a4f67d1cbc0fc%2F2023-04-14T07%3A16%3A35Z%2F86400%2F%2F21a92744dfb9fc3f46745e75d095da327bb04677f902" + + "8fb85e00ff5dc7df6daf\"],\"subtitleUrls\":[],\"createTime\":\"2023-04-11 16:55:32\",\"updateTime\":\"2023-0" + + "4-11 16:55:43\",\"duration\":18.73,\"height\":1080,\"width\":1920,\"fileSizeInByte\":8948434,\"thumbnailK" + + "eys\":[\"thumbnail/dog00000500.jpg\"],\"subtitles\":[\"\"],\"bucket\":\"bvw-console\",\"key\":\"dog.mp4\"" + + ",\"key360p\":\"360p/dog.mp4\",\"key720p\":\"720p/dog.mp4\",\"audioKey\":\"audio/dog.mp3\",\"used\":true}]" + + ",\"coverBucket\":\"bvw-console\",\"coverKey\":\"thumbnail/dog00000500.jpg\"}" + jsonErr := json.Unmarshal([]byte(jsonStr), &request) + ExpectEqual(t.Errorf, jsonErr, nil) + t.Logf("%+v", &request) + err := BVW_CLIENT.UpdateDraft(1017890, &request) + ExpectEqual(t.Errorf, err, nil) +} + +func TestPollingVideoEdit(t *testing.T) { + response, err := BVW_CLIENT.PollingVideoEdit(267539) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestCreateVideoEdit(t *testing.T) { + var request api.VideoEditCreateRequest + jsonStr := "{\"title\":\"新建作品-202304141603\",\"taskId\":\"1017895\",\"bucket\":\"vwdemo\",\"cmd\":{\"timeline" + + "\":{\"video\":[{\"list\":[{\"type\":\"video\",\"start\":0,\"end\":7.65625,\"showStart\":0,\"showEnd\":" + + "7.65625,\"xpos\":0,\"ypos\":0,\"width\":1,\"height\":1,\"duration\":7.65625,\"extInfo\":{\"style\":\"\"" + + ",\"lightness\":0,\"contrast\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"\",\"transitionEnd\":\"black\"" + + ",\"transitionDuration\":1,\"mirror\":\"\",\"rotate\":0,\"blankArea\":\"\",\"volume\":1},\"mediaInfo\":{\"" + + "mediaId\":\"1f10ce0db10b8eb5b2f2755daf544900\",\"key\":\"dog.mp4\",\"bucket\":\"bvw-console\",\"fileType\"" + + ":\"video\",\"width\":1920,\"height\":1080}},{\"type\":\"video\",\"start\":7.65625,\"end\":18.73,\"showStart" + + "\":7.65625,\"showEnd\":18.73,\"xpos\":0,\"ypos\":0,\"width\":1,\"height\":1,\"duration\":11.07375,\"" + + "extInfo\":{\"style\":\"\",\"lightness\":0,\"contrast\":0,\"hue\":0,\"speed\":1,\"transitionStart\":\"black\"" + + ",\"transitionEnd\":\"\",\"transitionDuration\":1,\"mirror\":\"\",\"rotate\":0,\"blankArea\":\"\",\"volume\":" + + "1},\"mediaInfo\":{\"mediaId\":\"1f10ce0db10b8eb5b2f2755daf544900\",\"key\":\"dog.mp4\",\"bucket\":\"" + + "bvw-console\",\"fileType\":\"video\",\"width\":1920,\"height\":1080}}]}],\"audio\":[{\"list\":[{\"name\":" + + "\"古风飘扬\",\"start\":0,\"end\":155.99,\"duration\":155.99,\"showStart\":0.078125,\"showEnd\":156.068125,\"" + + "uid\":\"cc8c1ecc-fcd3-493d-be5b-8cce8c15ed15\",\"extInfo\":{\"volume\":\"1.0\",\"transitions\":[]},\"" + + "mediaInfo\":{\"fileType\":\"audio\",\"key\":\"systemPreset/music/古风飘扬.aac\",\"bucket\":\"videoworks-" + + "system-preprocess\",\"name\":\"古风飘扬\"}}]}],\"subtitle\":[{\"list\":[{\"templateId\":\"6764ce3331ea7e406e" + + "4ab4475d1dff18\",\"showStart\":0,\"showEnd\":3,\"duration\":3,\"uid\":\"05e59686-b23e-4b33-96d7-040eab63" + + "85b6\",\"tag\":\"time-place\",\"xpos\":0,\"ypos\":0.431,\"config\":[{\"text\":\"时间\",\"fontSize\":50,\"" + + "fontType\":\"方正时代宋 简 Extrabold\",\"fontColor\":\"#ffffff\",\"alpha\":0,\"fontStyle\":\"normal\",\"" + + "backgroundColor\":\"#2468F2\",\"backgroundAlpha\":0,\"fontx\":0.039,\"fonty\":0.028,\"rectx\":0,\"recty\"" + + ":0.431,\"rectWidth\":0.156,\"rectHeight\":0.139},{\"text\":\"地点\",\"fontSize\":50,\"fontType\":\"" + + "方正时代宋 简 Extrabold\",\"fontColor\":\"#000000\",\"alpha\":0,\"fontStyle\":\"normal\",\"backgroundColor" + + "\":\"#ffffff\",\"backgroundAlpha\":0,\"fontx\":0.039,\"fonty\":0.028,\"rectx\":0.156,\"recty\":0.431,\"" + + "rectWidth\":0.156,\"rectHeight\":0.139}],\"tagExtInfo\":{\"glExtInfo\":{}}}]}],\"sticker\":[{\"list\":" + + "[{\"type\":\"image\",\"showStart\":0,\"showEnd\":3,\"duration\":3,\"xpos\":0,\"ypos\":0,\"width\":0.168" + + ",\"height\":0.168,\"extInfo\":{},\"mediaInfo\":{\"key\":\"systemPreset/picture/面包、肠.png\",\"bucket\":" + + "\"videoworks-system-preprocess\",\"width\":215,\"height\":120.9375,\"fileType\":\"image\"}}]}]}},\"extInfo" + + "\":{\"aspect\":\"hori16x9\",\"resolutionRatio\":\"v720p\"}}" + jsonErr := json.Unmarshal([]byte(jsonStr), &request) + ExpectEqual(t.Errorf, jsonErr, nil) + t.Logf("%+v", &request) + response, err := BVW_CLIENT.CreateVideoEdit(&request) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} diff --git a/bce-sdk-go/services/cce/cce.go b/bce-sdk-go/services/cce/cce.go new file mode 100644 index 0000000..5830b5a --- /dev/null +++ b/bce-sdk-go/services/cce/cce.go @@ -0,0 +1,335 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// cce.go - the cce APIs definition supported by the CCE service + +package cce + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateCluster - create an CCE Cluster with the specific parameters +// +// PARAMS: +// - args: the arguments to create a cce cluster +// +// RETURNS: +// - *CreateClusterResult: the result of create cluster, contains new Cluster's uuid and order id +func (c *Client) CreateCluster(args *CreateClusterArgs) (*CreateClusterResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create cluster argments") + } + + result := &CreateClusterResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterUri()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListClusters - list CCE Clusters with the specific parameters +// +// PARAMS: +// - args: the arguments to list cce cluster +// +// RETURNS: +// - *ListClusterResult: the result of list cluster +func (c *Client) ListClusters(args *ListClusterArgs) (*ListClusterResult, error) { + if args == nil { + args = &ListClusterArgs{} + } + + maxKeysStr := "" + if args.MaxKeys != 0 { + maxKeysStr = strconv.Itoa(args.MaxKeys) + } + + result := &ListClusterResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterUri()). + WithQueryParamFilter("maker", args.Marker). + WithQueryParamFilter("maxKeys", maxKeysStr). + WithQueryParamFilter("status", string(args.Status)). + WithResult(result). + Do() + + return result, err +} + +// GetCluster - get a CCE Cluster with the specific cluster uuid +// +// PARAMS: +// - args: the specific cluster uuid +// +// RETURNS: +// - *GetClusterResult: the detail information about the CCE Cluster +func (c *Client) GetCluster(clusterUuid string) (*GetClusterResult, error) { + result := &GetClusterResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterUriWithId(clusterUuid)). + WithResult(result). + Do() + + return result, err +} + +// DeleteCluster - delete a CCE Cluster +// +// PARAMS: +// - args: the arguments to delete a cce cluster +func (c *Client) DeleteCluster(args *DeleteClusterArgs) error { + if args == nil || args.ClusterUuid == "" { + return fmt.Errorf("please set delete cluster uuid") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getClusterUriWithId(args.ClusterUuid)). + WithQueryParamFilter("deleteEipCds", strconv.FormatBool(args.DeleteEipCds)). + WithQueryParamFilter("deleteSnap", strconv.FormatBool(args.DeleteSnap)). + Do() +} + +// ScalingUp - scaling up a CCE Cluster +// +// PARAMS: +// - args: the arguments to create a cce cluster +// +// RETURNS: +// - *ScalingUpResult: the result of scaling up cluster, contains new Cluster's uuid and order id +func (c *Client) ScalingUp(args *ScalingUpArgs) (*ScalingUpResult, error) { + if args == nil { + return nil, fmt.Errorf("please set scaling up cluster argments") + } + + if args.ClusterUuid == "" { + return nil, fmt.Errorf("please set scaling up clusterUuid") + } + + result := &ScalingUpResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterUri()). + WithQueryParam("scalingUp", ""). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ScalingDown - scaling down a CCE Cluster +// +// PARAMS: +// - args: the arguments to scaling down a cce cluster +func (c *Client) ScalingDown(args *ScalingDownArgs) error { + if args == nil { + return fmt.Errorf("please set scaling down cluster argments") + } + + if args.ClusterUuid == "" { + return fmt.Errorf("please set scaling down clusterUuid") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterUri()). + WithQueryParam("scalingDown", ""). + WithQueryParamFilter("deleteEipCds", strconv.FormatBool(args.DeleteEipCds)). + WithQueryParamFilter("deleteSnap", strconv.FormatBool(args.DeleteSnap)). + WithBody(args). + Do() + + return err +} + +// ListNodes - list all nodes in CCE Cluster +// +// PARAMS: +// - args: the arguments to list all nodes +// +// RETURNS: +// - *ListNodeResult: the result of list nodes, contains a Cluster's nodes +func (c *Client) ListNodes(args *ListNodeArgs) (*ListNodeResult, error) { + if args == nil { + return nil, fmt.Errorf("please set list node argments") + } + + if args.ClusterUuid == "" { + return nil, fmt.Errorf("please set cluster uuid for list nodes") + } + + maxKeysStr := "" + if args.MaxKeys != 0 { + maxKeysStr = strconv.Itoa(args.MaxKeys) + } + + result := &ListNodeResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getNodeUri()). + WithQueryParamFilter("maker", args.Marker). + WithQueryParamFilter("maxKeys", maxKeysStr). + WithQueryParamFilter("clusterUuid", args.ClusterUuid). + WithResult(result). + Do() + + return result, err +} + +// ShiftInNode - shift nodes into cluster +// +// PARAMS: +// - args: the arguments about shift nodes into cce cluster +func (c *Client) ShiftInNode(args *ShiftInNodeArgs) error { + if args == nil { + return fmt.Errorf("please set shift in argments") + } + + if args.ClusterUuid == "" { + return fmt.Errorf("please set shift in cluster uuid") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterExisteNodeUri()). + WithQueryParamFilter("action", "shift_in"). + WithBody(args). + Do() +} + +// ShiftOutNode - shift nodes out from CCE Cluster +// +// PARAMS: +// - args: the arguments about shift nodes out from cce cluster +func (c *Client) ShiftOutNode(args *ShiftOutNodeArgs) error { + if args == nil { + return fmt.Errorf("please set shift out argments") + } + + if args.ClusterUuid == "" { + return fmt.Errorf("please set shift out cluster uuid") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterExisteNodeUri()). + WithQueryParamFilter("action", "shift_out"). + WithBody(args). + Do() +} + +// ListExistedBccNode - list all bcc nodes which can shifted into CCE cluster +// +// PARAMS: +// - args: the arguments to list bcc nodes +// +// RETURNS: +// - *ListExistedNodeResult: the result of list nodes +func (c *Client) ListExistedBccNode(args *ListExistedNodeArgs) (*ListExistedNodeResult, error) { + if args == nil { + return nil, fmt.Errorf("please set list existed bcc node argments") + } + + if args.ClusterUuid == "" { + return nil, fmt.Errorf("please set list existed bcc node cluster uuid") + } + + result := &ListExistedNodeResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterExisteNodeListUri()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetContainerNet - get container net in vpc +// +// PARAMS: +// - args: the arguments to get args +// +// RETURNS: +// - *GetContainerNetResult: the result of container net +func (c *Client) GetContainerNet(args *GetContainerNetArgs) (*GetContainerNetResult, error) { + if args == nil { + return nil, fmt.Errorf("please set container net argments") + } + + result := &GetContainerNetResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterContainerNetUri()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetKubeConfig - get config file of CCE Cluster +// +// PARAMS: +// - args: the arguments to get config file of a cce cluster +// +// RETURNS: +// - *GetKubeConfigResult: the kubeconfig file data +func (c *Client) GetKubeConfig(args *GetKubeConfigArgs) (*GetKubeConfigResult, error) { + if args == nil { + return nil, fmt.Errorf("please set kube config argments") + } + + if args.ClusterUuid == "" { + return nil, fmt.Errorf("please set cluster uuid") + } + + result := &GetKubeConfigResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterKubeConfigUri()). + WithQueryParam("clusterUuid", args.ClusterUuid). + WithQueryParamFilter("type", string(args.Type)). + WithResult(result). + Do() + + return result, err +} + +// ListVersions - list all support kubernetes version +// +// RETURNS: +// - *ListVersionsResult: all support kubernetes version list +func (c *Client) ListVersions() (*ListVersionsResult, error) { + result := &ListVersionsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterVersionsUri()). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/cce/client.go b/bce-sdk-go/services/cce/client.go new file mode 100644 index 0000000..2d4171c --- /dev/null +++ b/bce-sdk-go/services/cce/client.go @@ -0,0 +1,78 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for CCE service + +// Package cce defines the CCE services of BCE. The supported APIs are all defined in sub-package + +package cce + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "cce." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_CLUSTER_URL = "/cluster" + REQUEST_NODE_URL = "/node" +) + +// Client of EIP service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getClusterUri() string { + return URI_PREFIX + REQUEST_CLUSTER_URL +} + +func getClusterUriWithId(clusterUuid string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterUuid +} + +func getNodeUri() string { + return URI_PREFIX + REQUEST_NODE_URL +} + +func getClusterExisteNodeUri() string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/existed_node" +} + +func getClusterExisteNodeListUri() string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/existed_bcc_node/list" +} + +func getClusterContainerNetUri() string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/get_container_net" +} + +func getClusterKubeConfigUri() string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/kubeconfig" +} + +func getClusterVersionsUri() string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/versions" +} diff --git a/bce-sdk-go/services/cce/client_test.go b/bce-sdk-go/services/cce/client_test.go new file mode 100644 index 0000000..b2558ac --- /dev/null +++ b/bce-sdk-go/services/cce/client_test.go @@ -0,0 +1,251 @@ +package cce + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + CCE_CLIENT *Client + CCE_CLUSTER_ID string + CCE_SHIFT_IN_NODE_ID string + CCE_SHIFT_OUT_NODE_ID string + CCE_CONTAINER_NET string + CCE_KUBERNETES_VERSION string + + CCE_NODE_ADMIN_PASSWD = "123qwe!" + VPC_TEST_ID = "" + SUBNET_TEST_ID = "" + SECURITY_GROUP_ID = "" + ZONE_TEST_ID = "zoneA" + IMAGE_TEST_ID = "m-Nlv9C0tF" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fmt.Println(conf) + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + CCE_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) + //log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_ListVersion(t *testing.T) { + result, err := CCE_CLIENT.ListVersions() + ExpectEqual(t.Errorf, nil, err) + + CCE_KUBERNETES_VERSION = result.Data[0] +} + +func TestClient_GetContainerNet(t *testing.T) { + args := &GetContainerNetArgs{ + VpcShortId: VPC_TEST_ID, + VpcCidr: "192.168.0.0/24", + Size: 1000, + } + result, err := CCE_CLIENT.GetContainerNet(args) + ExpectEqual(t.Errorf, nil, err) + + CCE_CONTAINER_NET = result.ContainerNet +} + +func TestClient_CreateCluster(t *testing.T) { + args := &CreateClusterArgs{ + ClusterName: "sdk-test", + Version: CCE_KUBERNETES_VERSION, + MainAvailableZone: "zoneA", + ContainerNet: CCE_CONTAINER_NET, + DeployMode: DeployModeBcc, + OrderContent: &BaseCreateOrderRequestVo{Items: []Item{ + { + Config: BccConfig{ + ProductType: ProductTypePostpay, + InstanceType: InstanceTypeG3, + Cpu: 1, + Memory: 2, + ImageType: ImageTypeCommon, + SubnetUuid: SUBNET_TEST_ID, + SecurityGroupId: SECURITY_GROUP_ID, + AdminPass: CCE_NODE_ADMIN_PASSWD, + PurchaseNum: 1, + ImageId: IMAGE_TEST_ID, + ServiceType: ServiceTypeBCC, + }, + }, + }}, + } + result, err := CCE_CLIENT.CreateCluster(args) + ExpectEqual(t.Errorf, nil, err) + + CCE_CLUSTER_ID = result.ClusterUuid +} + +func TestClient_GetCluster(t *testing.T) { + _, err := CCE_CLIENT.GetCluster(CCE_CLUSTER_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListClusters(t *testing.T) { + args := &ListClusterArgs{} + _, err := CCE_CLIENT.ListClusters(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListNodes(t *testing.T) { + args := &ListNodeArgs{ + ClusterUuid: CCE_CLUSTER_ID, + } + result, err := CCE_CLIENT.ListNodes(args) + ExpectEqual(t.Errorf, nil, err) + + CCE_SHIFT_OUT_NODE_ID = result.Nodes[0].InstanceShortId +} + +func TestClient_GetKubeConfig(t *testing.T) { + args := &GetKubeConfigArgs{ + ClusterUuid: CCE_CLUSTER_ID, + } + _, err := CCE_CLIENT.GetKubeConfig(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ScalingUp(t *testing.T) { + args := &ScalingUpArgs{ + ClusterUuid: CCE_CLUSTER_ID, + OrderContent: &BaseCreateOrderRequestVo{Items: []Item{ + { + Config: BccConfig{ + ProductType: ProductTypePostpay, + InstanceType: InstanceTypeG3, + Cpu: 1, + Memory: 2, + ImageType: ImageTypeCommon, + SubnetUuid: SUBNET_TEST_ID, + SecurityGroupId: SECURITY_GROUP_ID, + AdminPass: CCE_NODE_ADMIN_PASSWD, + PurchaseNum: 1, + ImageId: IMAGE_TEST_ID, + ServiceType: ServiceTypeBCC, + }, + }, + }}, + } + _, err := CCE_CLIENT.ScalingUp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ShiftOutNode(t *testing.T) { + args := &ShiftOutNodeArgs{ + ClusterUuid: CCE_CLUSTER_ID, + NodeInfoList: []CceNodeInfo{ + {InstanceId: CCE_SHIFT_OUT_NODE_ID}, + }, + } + err := CCE_CLIENT.ShiftOutNode(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListExistedBccNode(t *testing.T) { + args := &ListExistedNodeArgs{ + ClusterUuid: CCE_CLUSTER_ID, + } + result, err := CCE_CLIENT.ListExistedBccNode(args) + ExpectEqual(t.Errorf, nil, err) + + CCE_SHIFT_IN_NODE_ID = result.NodeList[0].InstanceId +} + +func TestClient_ShiftInNode(t *testing.T) { + args := &ShiftInNodeArgs{ + ClusterUuid: CCE_CLUSTER_ID, + NeedRebuild: false, + AdminPass: CCE_NODE_ADMIN_PASSWD, + InstanceType: ShiftInstanceTypeBcc, + NodeInfoList: []CceNodeInfo{ + { + InstanceId: CCE_SHIFT_IN_NODE_ID, + AdminPass: CCE_NODE_ADMIN_PASSWD, + }, + }, + } + err := CCE_CLIENT.ShiftInNode(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ScalingDown(t *testing.T) { + args := &ScalingDownArgs{ + ClusterUuid: CCE_CLUSTER_ID, + DeleteEipCds: true, + DeleteSnap: true, + NodeInfo: []NodeInfo{ + { + InstanceId: CCE_SHIFT_IN_NODE_ID, + }, + }, + } + err := CCE_CLIENT.ScalingDown(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteCluster(t *testing.T) { + deleteClusterArgs := &DeleteClusterArgs{ + ClusterUuid: CCE_CLUSTER_ID, + DeleteEipCds: true, + DeleteSnap: true, + } + err := CCE_CLIENT.DeleteCluster(deleteClusterArgs) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/cce/model.go b/bce-sdk-go/services/cce/model.go new file mode 100644 index 0000000..cf5d414 --- /dev/null +++ b/bce-sdk-go/services/cce/model.go @@ -0,0 +1,469 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package cce + +import ( + "time" +) + +type ProductType string + +const ( + ProductTypePostpay ProductType = "postpay" + ProductTypePrepay ProductType = "prepay" +) + +type ClusterStatus string + +const ( + ClusterStatusRunning ClusterStatus = "RUNNING" + ClusterStatusCreating ClusterStatus = "CREATING" + ClusterStatusCreateFailed ClusterStatus = "CREATE_FAILED" + ClusterStatusDeleting ClusterStatus = "DELETING" + ClusterStatusDeletingFailed ClusterStatus = "DELETE_FAILED" + ClusterStatusMasterUpgrading ClusterStatus = "MASTER_UPGRADING" + ClusterStatusMasterUpgradeFailed ClusterStatus = "MASTER_UPGRADE_FAILED" + ClusterStatusError ClusterStatus = "ERROR" + ClusterStatusDeleted ClusterStatus = "DELETED" +) + +type SimpleNode struct { + InstanceShortId string `json:"instanceShortId"` + InstanceUuid string `json:"instanceUuid"` + InstanceName string `json:"instanceName"` + ClusterUuid string `json:"clusterUuid"` + Status ClusterStatus `json:"status"` +} + +type Cluster struct { + ClusterUuid string `json:"clusterUuid"` + ClusterName string `json:"clusterName"` + SlaveVmCount int `json:"slaveVmCount"` + MasterVmCount int `json:"masterVmCount"` + ContainerNet string `json:"containerNet"` + Status ClusterStatus `json:"status"` + Region string `json:"region"` + CreateTime time.Time `json:"createTime"` + DeleteTime time.Time `json:"deleteTime"` + AllInstanceNormal bool `json:"allInstanceNormal"` + InstanceList []SimpleNode `json:"instanceList"` + DccUuid string `json:"dccUuid"` + HasPrepay bool `json:"hasPrepay"` + VpcId string `json:"vpcId"` + InstanceMode string `json:"instanceMode"` + MasterExposed bool `json:"masterExposed"` +} + +type ImageType string + +const ( + ImageTypeCommon ImageType = "common" + ImageTypeCustom ImageType = "custom" + ImageTypeGpu ImageType = "gpuBccImage" + ImageTypeGpuCustom ImageType = "gpuBccCustom" + ImageTypeSharing ImageType = "sharing" +) + +type ServiceType string + +const ( + ServiceTypeBCC ServiceType = "BCC" + ServiceTypeCDS ServiceType = "CDS" + ServiceTypeEIP ServiceType = "EIP" +) + +type InstanceType string + +const ( + InstanceTypeG1 InstanceType = "0" + InstanceTypeDCC InstanceType = "1" + InstanceTypeBCC InstanceType = "2" + InstanceTypeC1 InstanceType = "4" + InstanceTypeG2 InstanceType = "7" + InstanceTypeGPU InstanceType = "9" + InstanceTypeG3 InstanceType = "10" + InstanceTypeC2 InstanceType = "11" + InstanceTypeG4 InstanceType = "13" + InstanceTypeVGPU InstanceType = "15" + InstanceTypeKunlun InstanceType = "25" +) + +type BccConfig struct { + Name string `json:"name,omitempty"` + KeypairId string `json:"keypairId,omitempty"` + ProductType ProductType `json:"productType"` + LogicalZone string `json:"logicalZone,omitempty"` + InstanceType InstanceType `json:"instanceType"` + GpuCard string `json:"gpuCard,omitempty"` + GpuCount int `json:"gpuCount"` + Cpu int `json:"cpu"` + Memory int `json:"memory"` + ImageType ImageType `json:"imageType"` + SubnetUuid string `json:"subnetUuid"` + SecurityGroupId string `json:"securityGroupId"` + AdminPass string `json:"adminPass,omitempty"` + PurchaseLength int `json:"purchaseLength,omitempty"` + PurchaseNum int `json:"purchaseNum"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType VolumeType `json:"rootDiskStorageType,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + AutoRenew bool `json:"autoRenew,omitempty"` + ImageId string `json:"imageId"` + ServiceType ServiceType `json:"serviceType"` +} + +type VolumeType string + +const ( + VolumeTypeSata VolumeType = "sata" + VolumeTypeSsd VolumeType = "ssd" + VolumeTypePremiumSsd VolumeType = "premium_ssd" +) + +type DiskSizeConfig struct { + Size string `json:"size"` + VolumeType VolumeType `json:"volumeType"` + SnapshotId string `json:"snapshotId,omitempty"` +} + +type CdsConfig struct { + ProductType ProductType `json:"productType"` + LogicalZone string `json:"logicalZone"` + PurchaseNum int `json:"purchaseNum"` + PurchaseLength int `json:"purchaseLength,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + CdsDiskSize []DiskSizeConfig `json:"cdsDiskSize"` + ServiceType ServiceType `json:"serviceType"` +} + +type EipType string + +const ( + EipTypeBandwidth EipType = "bandwidth" + EipTypeNetraffic EipType = "netraffic" +) + +type EipConfig struct { + ProductType ProductType `json:"productType"` + BandwidthInMbps int `json:"bandwidthInMbps"` + SubProductType EipType `json:"subProductType"` + PurchaseNum int `json:"purchaseNum"` + PurchaseLength int `json:"purchaseLength,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + Name string `json:"name,omitempty"` + ServiceType ServiceType `json:"serviceType"` +} + +type Item struct { + Config interface{} `json:"config"` +} + +type BaseCreateOrderRequestVo struct { + Items []Item `json:"items"` +} + +type CdsPreMountInfo struct { + MountPath string `json:"mountPath"` + CdsConfig []DiskSizeConfig `json:"cdsConfig"` +} + +type CniMode string + +const ( + CniModeKubenet CniMode = "kubenet" + CniModeCni CniMode = "cni" +) + +type CniType string + +const ( + CniTypeEmpty CniType = "" + CniTypeRouteVeth CniType = "VPC_ROUTE_VETH" + CniTypeRouteIpvlan CniType = "VPC_ROUTE_IPVLAN" + CniTypeRouteAutoDetect CniType = "VPC_ROUTE_AUTODETECT" + CniTypeSecondaryIpVeth CniType = "VPC_SECONDARY_IP_VETH" + CniTypeSecondaryIpIpvlan CniType = "VPC_SECONDARY_IP_IPVLAN" + CniTypeSecondaryIpAutoDetect CniType = "VPC_SECONDARY_IP_AUTODETECT" +) + +type DNSMode string + +const ( + DNSModeKubeDNS DNSMode = "kubeDNS" + DNSModeCoreDNS DNSMode = "coreDNS" +) + +type KubeProxyMode string + +const ( + KubeProxyModeIptables KubeProxyMode = "iptables" + KubeProxyModeIpvs KubeProxyMode = "ipvs" +) + +type AdvancedOptions struct { + KubeProxyMode KubeProxyMode `json:"kubeProxyMode,omitempty"` + SecureContainerEnable bool `json:"secureContainerEnable,omitempty"` + SetOSSecurity bool `json:"setOSSecurity,omitempty"` + CniMode CniMode `json:"cniMode,omitempty"` + CniType CniType `json:"cniType,omitempty"` + DnsMode DNSMode `json:"dnsMode,omitempty"` + MaxPodNum int `json:"maxPodNum,omitempty"` +} + +type NodeInfo struct { + InstanceId string `json:"instanceId"` +} + +type Node struct { + InstanceShortId string `json:"instanceShortId"` + InstanceUuid string `json:"instanceUuid"` + InstanceName string `json:"instanceName"` + ClusterUuid string `json:"clusterUuid"` + AvailableZone string `json:"availableZone"` + VpcId string `json:"vpcId"` + VpcCidr string `json:"vpcCidr"` + SubnetId string `json:"subnetId"` + SubnetType string `json:"subnetType"` + Eip string `json:"eip"` + EipBandwidth int `json:"eipBandwidth"` + Cpu int `json:"cpu"` + Memory int `json:"memory"` + DiskSize int `json:"diskSize"` + SysDisk int `json:"sysDisk"` + InstanceType string `json:"instanceType"` + Blb string `json:"blb"` + FloatingIp string `json:"floatingIp"` + FixIp string `json:"fixIp"` + CreateTime time.Time `json:"createTime"` + DeleteTime time.Time `json:"deleteTime"` + Status string `json:"status"` + ExpireTime time.Time `json:"expireTime"` + PaymentMethod string `json:"paymentMethod"` + RuntimeVersion string `json:"runtimeVersion"` +} + +type CceNodeInfo struct { + InstanceId string `json:"instanceId"` + AdminPass string `json:"adminPass,omitempty"` +} + +type ServerForDisplay struct { + InstanceId string `json:"instanceId"` + Name string `json:"name"` + Status string `json:"status"` + Payment string `json:"payment"` + InternalIp string `json:"internalIp"` +} + +type DeployMode string + +const ( + DeployModeBcc DeployMode = "BCC" + DeployModeDcc DeployMode = "DCC" +) + +type CreateClusterArgs struct { + ClusterName string `json:"clusterName"` + Version string `json:"version"` + MainAvailableZone string `json:"mainAvailableZone"` + ContainerNet string `json:"containerNet"` + AdvancedOptions *AdvancedOptions `json:"advancedOptions,omitempty"` + CdsPreMountInfo *CdsPreMountInfo `json:"cdsPreMountInfo,omitempty"` + Comment string `json:"comment,omitempty"` + DeployMode DeployMode `json:"deployMode"` + DccUuid string `json:"dccUuid,omitempty"` + MasterExposed bool `json:"masterExposed,omitempty"` + OrderContent *BaseCreateOrderRequestVo `json:"orderContent"` + MasterOrderContent *BaseCreateOrderRequestVo `json:"masterOrderContent,omitempty"` +} + +type CreateClusterResult struct { + ClusterUuid string `json:"clusterUuid"` + OrderId []string `json:"orderId"` +} + +type ListClusterArgs struct { + Status ClusterStatus + Marker string + MaxKeys int +} + +type ListClusterResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Clusters []Cluster `json:"clusters"` +} + +type GetClusterResult struct { + ClusterUuid string `json:"clusterUuid"` + ClusterName string `json:"clusterName"` + Version string `json:"version"` + Region string `json:"region"` + SlaveVmCount int `json:"slaveVmCount"` + MasterVmCount int `json:"masterVmCount"` + VpcId string `json:"vpcId"` + VpcUuid string `json:"vpcUuid"` + VpcCidr string `json:"vpcCidr"` + ZoneSubnetMap map[string]string `json:"zoneSubnetMap"` + ContainerNet string `json:"containerNet"` + AdvancedOptions *AdvancedOptions `json:"advancedOptions"` + Status ClusterStatus `json:"status"` + CreateStartTime time.Time `json:"createStartTime"` + DeleteTime time.Time `json:"deleteTime"` + Comment string `json:"comment"` + InstanceMode string `json:"instanceMode"` + HasPrepay bool `json:"hasPrepay"` + VpcName string `json:"vpcName"` + SecureContainerEnable bool `json:"secureContainerEnable"` + MasterZoneSubnetMap map[string]string `json:"masterZoneSubnetMap"` + MasterExposed bool `json:"masterExposed"` +} + +type DeleteClusterArgs struct { + ClusterUuid string + DeleteEipCds bool + DeleteSnap bool +} + +type ScalingUpArgs struct { + ClusterUuid string `json:"clusterUuid"` + DccUuid string `json:"dccUuid,omitempty"` + CdsPreMountInfo *CdsPreMountInfo `json:"cdsPreMountInfo,omitempty"` + OrderContent *BaseCreateOrderRequestVo `json:"orderContent"` +} + +type ScalingUpResult struct { + ClusterUuid string `json:"clusterUuid"` + OrderId []string `json:"orderId"` +} + +type ScalingDownArgs struct { + ClusterUuid string `json:"clusterUuid"` + DeleteEipCds bool `json:"-"` + DeleteSnap bool `json:"-"` + NodeInfo []NodeInfo `json:"nodeInfo"` +} + +type ListNodeArgs struct { + ClusterUuid string + Marker string + MaxKeys int +} + +type ListNodeResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Nodes []Node `json:"nodes"` +} + +type ShiftInstanceType string + +const ( + ShiftInstanceTypeBcc ShiftInstanceType = "BCC" + ShiftInstanceTypeBBC ShiftInstanceType = "BBC" +) + +type ShiftInNodeArgs struct { + ClusterUuid string `json:"clusterUuid"` + NeedRebuild bool `json:"needRebuild"` + ImageId string `json:"imageId,omitempty"` + AdminPass string `json:"adminPass"` + InstanceType ShiftInstanceType `json:"instanceType"` + NodeInfoList []CceNodeInfo `json:"nodeInfoList"` +} + +type ShiftOutNodeArgs struct { + ClusterUuid string `json:"clusterUuid"` + NodeInfoList []CceNodeInfo `json:"nodeInfoList"` +} + +type Order string + +const ( + OrderAsc Order = "asc" + OrderDesc Order = "desc" +) + +type KeywordType string + +const ( + KeywordTypeName KeywordType = "name" + KeywordTypeInstanceId KeywordType = "instanceId" +) + +type ListExistedNodeArgs struct { + ClusterUuid string `json:"clusterUuid"` + VpcId string `json:"vpcId,omitempty"` + VpcCidr string `json:"vpcCidr,omitempty"` + InstanceType ShiftInstanceType `json:"instanceType,omitempty"` + BBCFlavorId string `json:"bbcFlavorId,omitempty"` + KeywordType KeywordType `json:"keywordType,omitempty"` + Keyword string `json:"keyword,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + Order Order `json:"order,omitempty"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` +} + +type ListExistedNodeResult struct { + ClusterUuid string `json:"clusterUuid"` + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + NodeList []ServerForDisplay `json:"nodeList"` +} + +type GetContainerNetArgs struct { + VpcShortId string `json:"vpcShortId"` + VpcCidr string `json:"vpcCidr"` + Size int `json:"size"` +} + +type GetContainerNetResult struct { + ContainerNet string `json:"containerNet"` + Capacity int `json:"capacity"` +} + +type KubeConfigType string + +const ( + KubeConfigTypeDefault KubeConfigType = "default" + KubeConfigTypeInternal KubeConfigType = "internal" + KubeConfigTypeIntraVpc KubeConfigType = "intraVpc" +) + +type GetKubeConfigArgs struct { + ClusterUuid string + Type KubeConfigType +} + +type GetKubeConfigResult struct { + Data string `json:"data"` +} + +type ListVersionsResult struct { + Data []string `json:"data"` +} diff --git a/bce-sdk-go/services/cce/v2/ccev2.go b/bce-sdk-go/services/cce/v2/ccev2.go new file mode 100644 index 0000000..0ed6036 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/ccev2.go @@ -0,0 +1,676 @@ +package v2 + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/services/cce/v2/types" +) + +// 创建集群 +func (c *Client) CreateCluster(args *CreateClusterArgs) (*CreateClusterResponse, error) { + if args == nil || args.CreateClusterRequest == nil { + return nil, fmt.Errorf("args is nil") + } + + //给其中可能存在的user script用base64编码 + if err := encodeUserScriptInInstanceSet(args.CreateClusterRequest.MasterSpecs); err != nil { + return nil, err + } + + if err := encodeUserScriptInInstanceSet(args.CreateClusterRequest.NodeSpecs); err != nil { + return nil, err + } + + result := &CreateClusterResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterURI()). + WithBody(args.CreateClusterRequest). + WithResult(result). + Do() + + return result, err +} + +// 删除集群 +func (c *Client) DeleteCluster(args *DeleteClusterArgs) (*DeleteClusterResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &DeleteClusterResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getClusterUriWithIDURI(args.ClusterID)). + WithQueryParamFilter("deleteResource", strconv.FormatBool(args.DeleteResource)). + WithQueryParamFilter("deleteCDSSnapshot", strconv.FormatBool(args.DeleteCDSSnapshot)). + WithResult(result). + Do() + + return result, err +} + +// 获得集群详情 +func (c *Client) GetCluster(clusterID string) (*GetClusterResponse, error) { + if clusterID == "" { + return nil, fmt.Errorf("clusterID is empty") + } + + result := &GetClusterResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterUriWithIDURI(clusterID)). + WithResult(result). + Do() + + return result, err +} + +// 集群列表 +func (c *Client) ListClusters(args *ListClustersArgs) (*ListClustersResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + if args.PageNum <= 0 || args.PageSize <= 0 { + return nil, fmt.Errorf("invlaid pageNo or pageSize") + } + + result := &ListClustersResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterListURI()). + WithQueryParamFilter("keywordType", string(args.KeywordType)). + WithQueryParamFilter("keyword", args.Keyword). + WithQueryParamFilter("orderBy", string(args.OrderBy)). + WithQueryParamFilter("order", string(args.Order)). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNum)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithResult(result). + Do() + + return result, err +} + +// 创建节点(扩容) +func (c *Client) CreateInstances(args *CreateInstancesArgs) (*CreateInstancesResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + //给其中可能存在的user script用base64编码 + if err := encodeUserScriptInInstanceSet(args.Instances); err != nil { + return nil, err + } + + s, _ := json.MarshalIndent(args, "", "\t") + fmt.Println("Args:" + string(s)) + + result := &CreateInstancesResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getClusterInstanceListURI(args.ClusterID)). + WithBody(args.Instances). + WithResult(result). + Do() + + return result, err +} + +// 查询节点 +func (c *Client) GetInstance(args *GetInstanceArgs) (*GetInstanceResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &GetInstanceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterInstanceURI(args.ClusterID, args.InstanceID)). + WithResult(result). + Do() + + return result, err +} + +// 更新节点配置 +func (c *Client) UpdateInstance(args *UpdateInstanceArgs) (*UpdateInstancesResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &UpdateInstancesResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getClusterInstanceURI(args.ClusterID, args.InstanceID)). + WithBody(args.InstanceSpec). + WithResult(result). + Do() + + return result, err +} + +// 删除节点(缩容) +func (c *Client) DeleteInstances(args *DeleteInstancesArgs) (*DeleteInstancesResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &DeleteInstancesResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getClusterInstanceListURI(args.ClusterID)). + WithBody(args.DeleteInstancesRequest). + WithResult(result). + Do() + + return result, err +} + +// 集群内节点列表 +func (c *Client) ListInstancesByPage(args *ListInstancesByPageArgs) (*ListInstancesResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &ListInstancesResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getClusterInstanceListURI(args.ClusterID)). + WithQueryParamFilter("keywordType", string(args.Params.KeywordType)). + WithQueryParamFilter("keyword", args.Params.Keyword). + WithQueryParamFilter("orderBy", string(args.Params.OrderBy)). + WithQueryParamFilter("order", string(args.Params.Order)). + WithQueryParamFilter("pageNo", strconv.Itoa(args.Params.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.Params.PageSize)). + WithResult(result). + Do() + + return result, err +} + +// 检查容器网络网段 +func (c *Client) CheckContainerNetworkCIDR(args *CheckContainerNetworkCIDRArgs) (*CheckContainerNetworkCIDRResponse, error) { + if args == nil { + return nil, fmt.Errorf("CheckContainerNetworkCIDRRequest is nil") + } + + result := &CheckContainerNetworkCIDRResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getNetCheckContainerNetworkCIDRURI()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// 检查集群网络网段 +func (c *Client) CheckClusterIPCIDR(args *CheckClusterIPCIDRArgs) (*CheckClusterIPCIDRResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &CheckClusterIPCIDRResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getNetCheckClusterIPCIDRURL()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// 推荐容器CIDR +func (c *Client) RecommendContainerCIDR(args *RecommendContainerCIDRArgs) (*RecommendContainerCIDRResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &RecommendContainerCIDRResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getNetRecommendContainerCidrURI()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// 推荐集群CIDR +func (c *Client) RecommendClusterIPCIDR(args *RecommendClusterIPCIDRArgs) (*RecommendClusterIPCIDRResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &RecommendClusterIPCIDRResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getNetRecommendClusterIpCidrURI()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// 用户集群 Quota +func (c *Client) GetClusterQuota() (*GetQuotaResponse, error) { + result := &GetQuotaResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getQuotaURI()). + WithResult(result). + Do() + + return result, err +} + +// 用户集群 Node Quota +func (c *Client) GetClusterNodeQuota(clusterID string) (*GetQuotaResponse, error) { + if clusterID == "" { + return nil, fmt.Errorf("clusterID is empty") + } + + result := &GetQuotaResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getQuotaNodeURI(clusterID)). + WithResult(result). + Do() + + return result, err +} + +// 创建节点组 +func (c *Client) CreateInstanceGroup(args *CreateInstanceGroupArgs) (*CreateInstanceGroupResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + encodeUserScript(&args.Request.InstanceTemplate.InstanceSpec) + + result := &CreateInstanceGroupResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getInstanceGroupURI(args.ClusterID)). + WithBody(args.Request). + WithResult(result). + Do() + + return result, err +} + +// 获取节点组列表 +func (c *Client) ListInstanceGroups(args *ListInstanceGroupsArgs) (*ListInstanceGroupResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &ListInstanceGroupResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParamFilter("pageNo", strconv.Itoa(args.ListOption.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.ListOption.PageSize)). + WithURL(getInstanceGroupListURI(args.ClusterID)). + WithResult(result). + Do() + + return result, err +} + +// 获取节点组的节点列表 +func (c *Client) ListInstancesByInstanceGroupID(args *ListInstanceByInstanceGroupIDArgs) (*ListInstancesByInstanceGroupIDResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &ListInstancesByInstanceGroupIDResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithURL(getClusterInstanceListWithInstanceGroupIDURI(args.ClusterID, args.InstanceGroupID)). + WithResult(result). + Do() + + return result, err +} + +// 获取节点组详情 +func (c *Client) GetInstanceGroup(args *GetInstanceGroupArgs) (*GetInstanceGroupResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &GetInstanceGroupResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceGroupWithIDURI(args.ClusterID, args.InstanceGroupID)). + WithResult(result). + Do() + + return result, err +} + +// 更新节点组副本数 +func (c *Client) UpdateInstanceGroupReplicas(args *UpdateInstanceGroupReplicasArgs) (*UpdateInstanceGroupReplicasResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &UpdateInstanceGroupReplicasResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceGroupReplicasURI(args.ClusterID, args.InstanceGroupID)). + WithBody(args.Request). + WithResult(result). + Do() + + return result, err +} + +// 修改节点组节点Autoscaler配置 +func (c *Client) UpdateInstanceGroupClusterAutoscalerSpec(args *UpdateInstanceGroupClusterAutoscalerSpecArgs) (*UpdateInstanceGroupClusterAutoscalerSpecResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + if args.Request == nil { + return nil, fmt.Errorf("nil UpdateInstanceGroupReplicasRequest") + } + if args.Request.Enabled { + if args.Request.MinReplicas < 0 || args.Request.MaxReplicas < args.Request.MinReplicas { + return nil, fmt.Errorf("invalid minReplicas or maxReplicas") + } + if args.Request.ScalingGroupPriority < 0 { + return nil, fmt.Errorf("invalid scalingGroupPriority") + } + } + + result := &UpdateInstanceGroupClusterAutoscalerSpecResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceGroupAutoScalerURI(args.ClusterID, args.InstanceGroupID)). + WithBody(args.Request). + WithResult(result). + Do() + + return result, err +} + +// 删除节点组 +func (c *Client) DeleteInstanceGroup(args *DeleteInstanceGroupArgs) (*DeleteInstanceGroupResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &DeleteInstanceGroupResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getInstanceGroupWithIDURI(args.ClusterID, args.InstanceGroupID)). + WithQueryParamFilter("deleteInstances", strconv.FormatBool(args.DeleteInstances)). + WithQueryParamFilter("releaseAllResources", strconv.FormatBool(args.ReleaseAllResources)). + WithResult(result). + Do() + + return result, err +} + +// 创建autoscaler配置 +func (c *Client) CreateAutoscaler(args *CreateAutoscalerArgs) (*CreateAutoscalerResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &CreateAutoscalerResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAutoscalerURI(args.ClusterID)). + WithResult(result). + Do() + + return result, err +} + +// 查询autoscaler配置 +func (c *Client) GetAutoscaler(args *GetAutoscalerArgs) (*GetAutoscalerResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &GetAutoscalerResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAutoscalerURI(args.ClusterID)). + WithResult(result). + Do() + + return result, err +} + +// 更新autoscaler配置 +func (c *Client) UpdateAutoscaler(args *UpdateAutoscalerArgs) (*UpdateAutoscalerResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &UpdateAutoscalerResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAutoscalerURI(args.ClusterID)). + WithBody(args.AutoscalerConfig). + WithResult(result). + Do() + + return result, err +} + +// 获取kubeconfig +func (c *Client) GetKubeConfig(args *GetKubeConfigArgs) (*GetKubeConfigResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + if err := CheckKubeConfigType(string(args.KubeConfigType)); err != nil { + return nil, err + } + + result := &GetKubeConfigResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getKubeconfigURI(args.ClusterID, args.KubeConfigType)). + WithResult(result). + Do() + + return result, err +} + +// 创建节点组扩容任务 +func (c *Client) CreateScaleUpInstanceGroupTask(args *CreateScaleUpInstanceGroupTaskArgs) (*CreateTaskResp, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + if args.ClusterID == "" { + return nil, fmt.Errorf("clusterID is empty") + } + if args.InstanceGroupID == "" { + return nil, fmt.Errorf("instanceGroupID is empty") + } + if args.TargetReplicas <= 0 { + return nil, fmt.Errorf("target replicas should be positive") + } + + result := &CreateTaskResp{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getScaleUpInstanceGroupURI(args.ClusterID, args.InstanceGroupID)). + WithQueryParamFilter("upToReplicas", strconv.Itoa(args.TargetReplicas)). + WithResult(result). + Do() + return result, err +} + +// 创建节点组缩容任务 +func (c *Client) CreateScaleDownInstanceGroupTask(args *CreateScaleDownInstanceGroupTaskArgs) (*CreateTaskResp, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + if args.ClusterID == "" { + return nil, fmt.Errorf("clusterID is empty") + } + if args.InstanceGroupID == "" { + return nil, fmt.Errorf("instanceGroupID is empty") + } + if len(args.InstancesToBeRemoved) == 0 { + return nil, fmt.Errorf("instances to be removed are not provided") + } + + body := map[string]interface{}{ + "instancesToBeRemoved": args.InstancesToBeRemoved, + } + + result := &CreateTaskResp{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getScaleDownInstanceGroupURI(args.ClusterID, args.InstanceGroupID)). + WithBody(body). + WithResult(result). + Do() + return result, err +} + +// 获取任务信息 +func (c *Client) GetTask(args *GetTaskArgs) (*GetTaskResp, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + if args.TaskType == "" { + return nil, fmt.Errorf("taskType is not set") + } + if args.TaskID == "" { + return nil, fmt.Errorf("taskID is empty") + } + + switch args.TaskType { + case types.TaskTypeInstanceGroupReplicas: + default: + return nil, fmt.Errorf("unsupported taskType") + } + + result := &GetTaskResp{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTaskWithIDURI(args.TaskType, args.TaskID)). + WithResult(result). + Do() + return result, err +} + +// 获取任务列表 +func (c *Client) ListTasks(args *ListTasksArgs) (*ListTaskResp, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + if args.TaskType == "" { + return nil, fmt.Errorf("taskType is not set") + } + + switch args.TaskType { + case types.TaskTypeInstanceGroupReplicas: + if args.TargetID == "" { + return nil, fmt.Errorf("targetID is empty") + } + default: + return nil, fmt.Errorf("unsupported taskType") + } + + result := &ListTaskResp{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTaskListURI(args.TaskType)). + WithQueryParamFilter("targetID", args.TargetID). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithResult(result). + Do() + return result, err +} + +func (c *Client) GetInstanceCRD(args *GetInstanceCRDArgs) (*GetInstanceCRDResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &GetInstanceCRDResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(genGetInstanceCRDURI(args.ClusterID, args.CCEInstanceID)). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) UpdateInstanceCRD(args *UpdateInstanceCRDRequest) (*CommonResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + if args.Instance == nil { + return nil, fmt.Errorf("instance is nil") + } + + result := &CommonResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(genUpdateInstanceCRDURI(args.Instance.Spec.ClusterID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) GetClusterCRD(args *GetClusterCRDArgs) (*GetClusterCRDResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + result := &GetClusterCRDResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(genGetClusterCRDURI(args.ClusterID)). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) UpdateClusterCRD(args *UpdateClusterCRDArgs) (*CommonResponse, error) { + if args == nil { + return nil, fmt.Errorf("args is nil") + } + + if args.Cluster == nil { + return nil, fmt.Errorf("cluster is nil") + } + + result := &CommonResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(genUpdateClusterCRDURI(args.Cluster.Spec.ClusterID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/cce/v2/client.go b/bce-sdk-go/services/cce/v2/client.go new file mode 100644 index 0000000..bc47f59 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/client.go @@ -0,0 +1,216 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package v2 + +import ( + "encoding/base64" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/cce/v2/types" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "api/cce/service/v2" + + DEFAULT_ENDPOINT = "cce." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_CLUSTER_URL = "/cluster" + + REQUEST_CLUSTER_LIST_URL = "/clusters" + + REQUEST_INSTANCE_URL = "/instance" + + REQUEST_INSTANCE_LIST_URL = "/instances" + + REQUEST_INSTANCEGROUP_URL = "/instancegroup" + + REQUEST_INSTANCEGROUP_LIST_URL = "/instancegroups" + + REQUEST_INSTANCEGROUP_AUTOSCALER_URL = "/autoscaler" + + REQUEST_INSTANCEGROUP_REPLICAS_URL = "/replicas" + + REQUEST_INSTANCEGROUP_SCALE_UP_URL = "/scaleup" + + REQUEST_INSTANCEGROUP_SCALE_DOWN_URL = "/scaledown" + + REQUEST_QUOTA_URL = "/quota" + + REQUEST_NODE_URL = "/node" + + REQUEST_NET_URL = "/net" + + REQUEST_NET_CHECK_CONTAINER_NETWORK_CIDR_URL = "/check_container_network_cidr" + + REQUEST_NET_CHECK_CLUSTERIP_CIDR_URL = "/check_clusterip_cidr" + + REQUEST_NET_RECOMMEND_CLSUTERIP_CIDR_URL = "/recommend_clusterip_cidr" + + REQUEST_NET_RECOMMEND_CONTAINER_CIDR_URL = "/recommend_container_cidr" + + REQUEST_AUTOSCALER = "/autoscaler" + + REQUEST_KUBECONFIG = "/kubeconfig/%s/%s" + + REQUEST_TASK_URL = "/task" + + REQUEST_TASK_LIST_URL = "/tasks" +) + +var _ Interface = &Client{} + +// Client 实现 ccev2.Interface +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getClusterURI() string { + return URI_PREFIX + REQUEST_CLUSTER_URL +} + +func getClusterUriWithIDURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID +} + +func getClusterListURI() string { + return URI_PREFIX + REQUEST_CLUSTER_LIST_URL +} + +func getClusterInstanceListURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCE_LIST_URL +} + +func getClusterInstanceURI(clusterID, instanceID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCE_URL + "/" + instanceID +} + +func getClusterInstanceListWithInstanceGroupIDURI(clusterID, instanceGroupID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL + "/" + instanceGroupID + REQUEST_INSTANCE_LIST_URL +} + +func getInstanceGroupURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL +} + +func getInstanceGroupListURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_LIST_URL +} + +func getInstanceGroupWithIDURI(clusterID, instanceGroupID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL + "/" + instanceGroupID +} + +func getInstanceGroupAutoScalerURI(clusterID, instanceGroupID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL + "/" + instanceGroupID + REQUEST_INSTANCEGROUP_AUTOSCALER_URL +} + +func getScaleUpInstanceGroupURI(clusterID, instanceGroupID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL + "/" + instanceGroupID + REQUEST_INSTANCEGROUP_SCALE_UP_URL +} + +func getScaleDownInstanceGroupURI(clusterID, instanceGroupID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL + "/" + instanceGroupID + REQUEST_INSTANCEGROUP_SCALE_DOWN_URL +} + +func getInstanceGroupReplicasURI(clusterID, instanceGroupID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCEGROUP_URL + "/" + instanceGroupID + REQUEST_INSTANCEGROUP_REPLICAS_URL +} + +func getNetCheckContainerNetworkCIDRURI() string { + return URI_PREFIX + REQUEST_NET_URL + REQUEST_NET_CHECK_CONTAINER_NETWORK_CIDR_URL +} + +func getNetCheckClusterIPCIDRURL() string { + return URI_PREFIX + REQUEST_NET_URL + REQUEST_NET_CHECK_CLUSTERIP_CIDR_URL +} + +func getNetRecommendClusterIpCidrURI() string { + return URI_PREFIX + REQUEST_NET_URL + REQUEST_NET_RECOMMEND_CLSUTERIP_CIDR_URL +} + +func getNetRecommendContainerCidrURI() string { + return URI_PREFIX + REQUEST_NET_URL + REQUEST_NET_RECOMMEND_CONTAINER_CIDR_URL +} + +func getQuotaURI() string { + return URI_PREFIX + REQUEST_QUOTA_URL + REQUEST_CLUSTER_URL +} + +func getQuotaNodeURI(clusterID string) string { + return URI_PREFIX + REQUEST_QUOTA_URL + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_NODE_URL +} + +func getAutoscalerURI(clusterID string) string { + return URI_PREFIX + REQUEST_AUTOSCALER + "/" + clusterID +} + +func getKubeconfigURI(clusterID string, kubeConfigType KubeConfigType) string { + return URI_PREFIX + fmt.Sprintf(REQUEST_KUBECONFIG, clusterID, kubeConfigType) +} + +func getTaskWithIDURI(taskType types.TaskType, taskID string) string { + return URI_PREFIX + REQUEST_TASK_URL + "/" + string(taskType) + "/" + taskID +} + +func getTaskListURI(taskType types.TaskType) string { + return URI_PREFIX + REQUEST_TASK_LIST_URL + "/" + string(taskType) +} + +func genGetInstanceCRDURI(clusterID, cceInstanceID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCE_URL + "/" + cceInstanceID + "/crd" +} + +func genUpdateInstanceCRDURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + REQUEST_INSTANCE_URL + "/crd" +} + +func genGetClusterCRDURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + "/crd" +} + +func genUpdateClusterCRDURI(clusterID string) string { + return URI_PREFIX + REQUEST_CLUSTER_URL + "/" + clusterID + "/crd" +} + +func encodeUserScriptInInstanceSet(instancesSets []*InstanceSet) error { + if instancesSets == nil { + return nil + } + for _, instanceSet := range instancesSets { + encodeUserScript(&instanceSet.InstanceSpec) + } + return nil +} + +func encodeUserScript(instanceSpec *types.InstanceSpec) { + if instanceSpec == nil { + return + } + if instanceSpec.DeployCustomConfig.PreUserScript != "" { + base64Str := base64.StdEncoding.EncodeToString([]byte(instanceSpec.DeployCustomConfig.PreUserScript)) + instanceSpec.DeployCustomConfig.PreUserScript = base64Str + } + if instanceSpec.DeployCustomConfig.PostUserScript != "" { + base64Str := base64.StdEncoding.EncodeToString([]byte(instanceSpec.DeployCustomConfig.PostUserScript)) + instanceSpec.DeployCustomConfig.PostUserScript = base64Str + } +} diff --git a/bce-sdk-go/services/cce/v2/client_test.go b/bce-sdk-go/services/cce/v2/client_test.go new file mode 100644 index 0000000..f795be5 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/client_test.go @@ -0,0 +1,688 @@ +package v2 + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + bccapi "github.com/baidubce/bce-sdk-go/services/bcc/api" + "github.com/baidubce/bce-sdk-go/services/cce/v2/types" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + CCE_CLIENT *Client + CCE_CLUSTER_ID string + CCE_INSTANCE_GROUP_ID string + CCE_INSTANCE_ID string + VPC_TEST_ID = "" + IMAGE_TEST_ID = "" + SECURITY_GROUP_TEST_ID = "" + VPC_SUBNET_TEST_ID = "" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func TestMain(m *testing.M) { + setup() + code := m.Run() + os.Exit(code) +} + +func setup() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fmt.Println(conf) + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + log.SetLogLevel(log.WARN) + + CCE_CLIENT, err = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + if err != nil { + log.Fatal(err) + } + + log.Info("Setup Complete") +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CheckClusterIPCIDR(t *testing.T) { + args := &CheckClusterIPCIDRArgs{ + VPCID: VPC_TEST_ID, + VPCCIDR: "192.168.0.0/16", + ClusterIPCIDR: "172.31.0.0/16", + IPVersion: "ipv4", + } + resp, err := CCE_CLIENT.CheckClusterIPCIDR(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_CheckContainerNetworkCIDR(t *testing.T) { + args := &CheckContainerNetworkCIDRArgs{ + VPCID: VPC_TEST_ID, + VPCCIDR: "192.168.0.0/16", + ContainerCIDR: "172.28.0.0/16", + ClusterIPCIDR: "172.31.0.0/16", + MaxPodsPerNode: 256, + } + resp, err := CCE_CLIENT.CheckContainerNetworkCIDR(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_RecommendClusterIPCIDR(t *testing.T) { + args := &RecommendClusterIPCIDRArgs{ + ClusterMaxServiceNum: 8, + ContainerCIDR: "172.28.0.0/16", + IPVersion: "ipv4", + PrivateNetCIDRs: []PrivateNetString{PrivateIPv4Net172}, + VPCCIDR: "192.168.0.0/16", + } + resp, err := CCE_CLIENT.RecommendClusterIPCIDR(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_RecommendContainerCIDR(t *testing.T) { + args := &RecommendContainerCIDRArgs{ + ClusterMaxNodeNum: 2, + IPVersion: "ipv4", + K8SVersion: types.K8S_1_16_8, + MaxPodsPerNode: 32, + PrivateNetCIDRs: []PrivateNetString{PrivateIPv4Net172}, + VPCCIDR: "192.168.0.0/16", + VPCID: VPC_TEST_ID, + } + + resp, err := CCE_CLIENT.RecommendContainerCIDR(args) + if err != nil { + fmt.Println(err.Error()) + return + } + fmt.Println("Request ID:" + resp.RequestID) + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_CreateCluster(t *testing.T) { + args := &CreateClusterArgs{ + CreateClusterRequest: &CreateClusterRequest{ + ClusterSpec: &types.ClusterSpec{ + ClusterName: "sdk-ccev2-test", + K8SVersion: types.K8S_1_16_8, + RuntimeType: types.RuntimeTypeDocker, + VPCID: VPC_TEST_ID, + MasterConfig: types.MasterConfig{ + MasterType: types.MasterTypeManaged, + ClusterHA: 1, + ExposedPublic: false, + ClusterBLBVPCSubnetID: VPC_SUBNET_TEST_ID, + ManagedClusterMasterOption: types.ManagedClusterMasterOption{ + MasterVPCSubnetZone: types.AvailableZoneA, + }, + }, + ContainerNetworkConfig: types.ContainerNetworkConfig{ + Mode: types.ContainerNetworkModeKubenet, + LBServiceVPCSubnetID: VPC_SUBNET_TEST_ID, + ClusterPodCIDR: "172.28.0.0/16", + ClusterIPServiceCIDR: "172.31.0.0/16", + }, + K8SCustomConfig: types.K8SCustomConfig{ + KubeAPIQPS: 1000, + KubeAPIBurst: 2000, + }, + }, + }, + } + resp, err := CCE_CLIENT.CreateCluster(args) + + ExpectEqual(t.Errorf, nil, err) + if resp.ClusterID == "" { + t.Fatalf("Request Fail. Cluster ID is empty.") + } + + CCE_CLUSTER_ID = resp.ClusterID + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + //等集群创建完成 + time.Sleep(time.Duration(180) * time.Second) +} + +func TestClient_GetCluster(t *testing.T) { + resp, err := CCE_CLIENT.GetCluster(CCE_CLUSTER_ID) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_ListClusters(t *testing.T) { + args := &ListClustersArgs{ + KeywordType: "clusterName", + Keyword: "", + OrderBy: "clusterID", + Order: OrderASC, + PageSize: 10, + PageNum: 1, + } + resp, err := CCE_CLIENT.ListClusters(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_CreateInstanceGroup(t *testing.T) { + args := &CreateInstanceGroupArgs{ + ClusterID: CCE_CLUSTER_ID, + Request: &CreateInstanceGroupRequest{ + types.InstanceGroupSpec{ + InstanceGroupName: "jichao-sdk-testcase", + CleanPolicy: types.DeleteCleanPolicy, + Replicas: 3, + InstanceTemplate: types.InstanceTemplate{ + InstanceSpec: types.InstanceSpec{ + ClusterRole: types.ClusterRoleNode, + Existed: false, + MachineType: types.MachineTypeBCC, + InstanceType: bccapi.InstanceTypeN3, + VPCConfig: types.VPCConfig{ + VPCID: VPC_TEST_ID, + VPCSubnetID: VPC_SUBNET_TEST_ID, + SecurityGroupID: SECURITY_GROUP_TEST_ID, + AvailableZone: types.AvailableZoneA, + }, + DeployCustomConfig: types.DeployCustomConfig{ + PreUserScript: "ls", + PostUserScript: "ls", + }, + InstanceResource: types.InstanceResource{ + CPU: 1, + MEM: 4, + RootDiskSize: 40, + LocalDiskSize: 0, + }, + ImageID: IMAGE_TEST_ID, + InstanceOS: types.InstanceOS{ + ImageType: bccapi.ImageTypeSystem, + }, + NeedEIP: false, + InstanceChargingType: bccapi.PaymentTimingPostPaid, + RuntimeType: types.RuntimeTypeDocker, + }, + }, + }, + }, + } + + resp, err := CCE_CLIENT.CreateInstanceGroup(args) + + ExpectEqual(t.Errorf, nil, err) + if resp.InstanceGroupID == "" { + t.Fatalf("Request Fail. Instance Group ID is empty.") + } + CCE_INSTANCE_GROUP_ID = resp.InstanceGroupID + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + time.Sleep(time.Duration(180) * time.Second) +} + +func TestClient_ListInstanceGroups(t *testing.T) { + args := &ListInstanceGroupsArgs{ + ClusterID: CCE_CLUSTER_ID, + ListOption: &InstanceGroupListOption{ + PageNo: 0, + PageSize: 0, + }, + } + resp, err := CCE_CLIENT.ListInstanceGroups(args) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListInstancesByInstanceGroupID(t *testing.T) { + args := &ListInstanceByInstanceGroupIDArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceGroupID: CCE_INSTANCE_GROUP_ID, + PageSize: 0, + PageNo: 0, + } + + resp, err := CCE_CLIENT.ListInstancesByInstanceGroupID(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetInstanceGroup(t *testing.T) { + args := &GetInstanceGroupArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceGroupID: CCE_INSTANCE_GROUP_ID, + } + + resp, err := CCE_CLIENT.GetInstanceGroup(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_UpdateInstanceGroupReplicas(t *testing.T) { + args := &UpdateInstanceGroupReplicasArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceGroupID: CCE_INSTANCE_GROUP_ID, + Request: &UpdateInstanceGroupReplicasRequest{ + Replicas: 1, + DeleteInstance: true, + DeleteOption: &types.DeleteOption{ + MoveOut: false, + DeleteCDSSnapshot: true, + DeleteResource: true, + }, + }, + } + + resp, err := CCE_CLIENT.UpdateInstanceGroupReplicas(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + time.Sleep(time.Duration(120) * time.Second) +} + +func TestClient_CreateAutoscaler(t *testing.T) { + args := &CreateAutoscalerArgs{ + ClusterID: CCE_CLUSTER_ID, + } + + resp, err := CCE_CLIENT.CreateAutoscaler(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetAutoscaler(t *testing.T) { + args := &GetAutoscalerArgs{ + ClusterID: CCE_CLUSTER_ID, + } + + resp, err := CCE_CLIENT.GetAutoscaler(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_UpdateAutoscaler(t *testing.T) { + args := &UpdateAutoscalerArgs{ + ClusterID: CCE_CLUSTER_ID, + AutoscalerConfig: ClusterAutoscalerConfig{ + ReplicaCount: 5, + ScaleDownEnabled: true, + Expander: "random", + }, + } + + resp, err := CCE_CLIENT.UpdateAutoscaler(args) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateInstanceGroupClusterAutoscalerSpec(t *testing.T) { + args := &UpdateInstanceGroupClusterAutoscalerSpecArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceGroupID: CCE_INSTANCE_GROUP_ID, + Request: &ClusterAutoscalerSpec{ + Enabled: true, + MinReplicas: 2, + MaxReplicas: 5, + ScalingGroupPriority: 1, + }, + } + + resp, err := CCE_CLIENT.UpdateInstanceGroupClusterAutoscalerSpec(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetKubeConfig(t *testing.T) { + args := &GetKubeConfigArgs{ + ClusterID: CCE_CLUSTER_ID, + KubeConfigType: KubeConfigTypeVPC, + } + + resp, err := CCE_CLIENT.GetKubeConfig(args) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteInstanceGroup(t *testing.T) { + args := &DeleteInstanceGroupArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceGroupID: CCE_INSTANCE_GROUP_ID, + DeleteInstances: true, + ReleaseAllResources: true, + } + + resp, err := CCE_CLIENT.DeleteInstanceGroup(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + time.Sleep(time.Duration(180) * time.Second) +} + +func TestClient_CreateInstances(t *testing.T) { + args := &CreateInstancesArgs{ + ClusterID: CCE_CLUSTER_ID, + Instances: []*InstanceSet{ + { + Count: 1, + InstanceSpec: types.InstanceSpec{ + ClusterRole: types.ClusterRoleNode, + Existed: false, + MachineType: types.MachineTypeBCC, + InstanceType: bccapi.InstanceTypeN3, + VPCConfig: types.VPCConfig{ + VPCID: VPC_TEST_ID, + VPCSubnetID: VPC_SUBNET_TEST_ID, + SecurityGroupID: SECURITY_GROUP_TEST_ID, + AvailableZone: types.AvailableZoneA, + }, + DeployCustomConfig: types.DeployCustomConfig{ + PreUserScript: "ls", + PostUserScript: "time", + }, + InstanceResource: types.InstanceResource{ + CPU: 1, + MEM: 4, + RootDiskSize: 40, + LocalDiskSize: 0, + }, + ImageID: IMAGE_TEST_ID, + InstanceOS: types.InstanceOS{ + ImageType: bccapi.ImageTypeSystem, + OSType: types.OSTypeLinux, + OSName: types.OSNameCentOS, + OSVersion: "7.5", + OSArch: "x86_64 (64bit)", + }, + NeedEIP: false, + InstanceChargingType: bccapi.PaymentTimingPostPaid, + RuntimeType: types.RuntimeTypeDocker, + }, + }, + }, + } + resp, err := CCE_CLIENT.CreateInstances(args) + + ExpectEqual(t.Errorf, nil, err) + if resp.CCEInstanceIDs == nil || len(resp.CCEInstanceIDs) == 0 { + t.Fatalf("Request Fail. Instance ID is empty.") + } + CCE_INSTANCE_ID = resp.CCEInstanceIDs[0] + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) + + time.Sleep(time.Duration(180) * time.Second) +} + +func TestClient_ListInstancesByPage(t *testing.T) { + args := &ListInstancesByPageArgs{ + ClusterID: CCE_CLUSTER_ID, + Params: &ListInstancesByPageParams{ + KeywordType: InstanceKeywordTypeInstanceName, + Keyword: "", + OrderBy: "createdAt", + Order: OrderASC, + PageNo: 1, + PageSize: 10, + EnableInternalFields: true, + }, + } + resp, err := CCE_CLIENT.ListInstancesByPage(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetInstance(t *testing.T) { + args := &GetInstanceArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceID: CCE_INSTANCE_ID, + } + resp, err := CCE_CLIENT.GetInstance(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_UpdateInstance(t *testing.T) { + args := &GetInstanceArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceID: CCE_INSTANCE_ID, + } + respGet, err := CCE_CLIENT.GetInstance(args) + + oldInstanceSpec := respGet.Instance.Spec + + oldInstanceSpec.CCEInstancePriority = 1 + + argsUpdate := &UpdateInstanceArgs{ + ClusterID: CCE_CLUSTER_ID, + InstanceID: CCE_INSTANCE_ID, + InstanceSpec: oldInstanceSpec, + } + + respUpdate, err := CCE_CLIENT.UpdateInstance(argsUpdate) + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(respUpdate, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetClusterQuota(t *testing.T) { + resp, err := CCE_CLIENT.GetClusterQuota() + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetClusterNodeQuota(t *testing.T) { + resp, err := CCE_CLIENT.GetClusterNodeQuota(CCE_CLUSTER_ID) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_DeleteInstances(t *testing.T) { + args := &DeleteInstancesArgs{ + ClusterID: CCE_CLUSTER_ID, + DeleteInstancesRequest: &DeleteInstancesRequest{ + InstanceIDs: []string{CCE_INSTANCE_ID}, + DeleteOption: &types.DeleteOption{ + MoveOut: false, + DeleteCDSSnapshot: true, + DeleteResource: true, + }, + }, + } + resp, err := CCE_CLIENT.DeleteInstances(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_DeleteCluster(t *testing.T) { + args := &DeleteClusterArgs{ + ClusterID: CCE_CLUSTER_ID, + DeleteResource: true, + DeleteCDSSnapshot: true, + } + resp, err := CCE_CLIENT.DeleteCluster(args) + if err != nil { + fmt.Println(err.Error()) + return + } + fmt.Println("Request ID:" + resp.RequestID) + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_InstanceCRD(t *testing.T) { + getInstanceCRDArgs := &GetInstanceCRDArgs{ + ClusterID: "cce-xyr5njs7", + CCEInstanceID: "cce-xyr5njs7-zjxl4lju", + } + + resp, err := CCE_CLIENT.GetInstanceCRD(getInstanceCRDArgs) + if err != nil { + t.Logf("get instance crd error: %s", err.Error()) + return + } + t.Logf("Request ID: %s", resp.RequestID) + s, _ := json.MarshalIndent(resp, "", "\t") + t.Logf("Response: %s", string(s)) + + // update instance crd + instance := resp.Instance + instance.Spec.AdminPassword = "Test123!" + + updateInstanceCRD := UpdateInstanceCRDRequest{ + Instance: instance, + } + commonResp, err := CCE_CLIENT.UpdateInstanceCRD(&updateInstanceCRD) + if err != nil { + t.Logf("update instance crd error: %s", err.Error()) + return + } + + t.Logf("Request ID: %s", commonResp.RequestID) +} + +func TestClient_UpdateClusterCRD(t *testing.T) { + getClusterCRDArgs := &GetClusterCRDArgs{ + + ClusterID: "cce-bvyohjkg", + } + + resp, err := CCE_CLIENT.GetClusterCRD(getClusterCRDArgs) + if err != nil { + fmt.Printf("get cluster crd error: %s", err.Error()) + return + } + + fmt.Printf("Request ID: %s", resp.RequestID) + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Printf("Response: %s", string(s)) + + cluster := resp.Cluster + cluster.Spec.ClusterName = "gogogogo" + + request := UpdateClusterCRDArgs{ + Cluster: cluster, + } + + commonResp, err := CCE_CLIENT.UpdateClusterCRD(&request) + if err != nil { + fmt.Printf("update cluster crd error: %s", err.Error()) + return + } + + fmt.Printf("Resuest ID: %s", commonResp.RequestID) +} diff --git a/bce-sdk-go/services/cce/v2/model.go b/bce-sdk-go/services/cce/v2/model.go new file mode 100644 index 0000000..5d25c89 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/model.go @@ -0,0 +1,879 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ +/* +CCE V2 版本 GO SDK, Interface 定义 +*/ + +package v2 + +import ( + "fmt" + "time" + + "github.com/baidubce/bce-sdk-go/services/cce/v2/types" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// Interface 定义 CCE V2 SDK +type Interface interface { + CreateCluster(args *CreateClusterArgs) (*CreateClusterResponse, error) + GetCluster(clusterID string) (*GetClusterResponse, error) + DeleteCluster(args *DeleteClusterArgs) (*DeleteClusterResponse, error) + ListClusters(args *ListClustersArgs) (*ListClustersResponse, error) + + CreateInstances(args *CreateInstancesArgs) (*CreateInstancesResponse, error) + GetInstance(args *GetInstanceArgs) (*GetInstanceResponse, error) + DeleteInstances(args *DeleteInstancesArgs) (*DeleteInstancesResponse, error) + ListInstancesByPage(args *ListInstancesByPageArgs) (*ListInstancesResponse, error) + CreateScaleUpInstanceGroupTask(args *CreateScaleUpInstanceGroupTaskArgs) (*CreateTaskResp, error) + CreateScaleDownInstanceGroupTask(args *CreateScaleDownInstanceGroupTaskArgs) (*CreateTaskResp, error) + + GetClusterQuota() (*GetQuotaResponse, error) + GetClusterNodeQuota(clusterID string) (*GetQuotaResponse, error) + + CheckContainerNetworkCIDR(args *CheckContainerNetworkCIDRArgs) (*CheckContainerNetworkCIDRResponse, error) + CheckClusterIPCIDR(args *CheckClusterIPCIDRArgs) (*CheckClusterIPCIDRResponse, error) + RecommendContainerCIDR(args *RecommendContainerCIDRArgs) (*RecommendContainerCIDRResponse, error) + RecommendClusterIPCIDR(args *RecommendClusterIPCIDRArgs) (*RecommendClusterIPCIDRResponse, error) + + GetTask(args *GetTaskArgs) (*GetTaskResp, error) + ListTasks(args *ListTasksArgs) (*ListTaskResp, error) + + GetInstanceCRD(args *GetInstanceCRDArgs) (*GetInstanceCRDResponse, error) + UpdateInstanceCRD(args *UpdateInstanceCRDRequest) (*CommonResponse, error) +} + +// CreateCluterArgs为后续支持clientToken预留空间 +type CreateClusterArgs struct { + CreateClusterRequest *CreateClusterRequest +} + +type DeleteClusterArgs struct { + ClusterID string + DeleteResource bool + DeleteCDSSnapshot bool +} + +type ListClustersArgs struct { + KeywordType ClusterKeywordType + Keyword string + OrderBy ClusterOrderBy + Order Order + PageNum int + PageSize int +} + +type CreateInstancesArgs struct { + ClusterID string + Instances []*InstanceSet +} + +type GetInstanceArgs struct { + ClusterID string + InstanceID string +} + +type GetInstanceCRDArgs struct { + ClusterID string + // cceInstanceID , cce 节点的唯一标志,不是底层机器的instanceID + CCEInstanceID string +} + +type DeleteInstancesArgs struct { + ClusterID string + DeleteInstancesRequest *DeleteInstancesRequest +} + +type ListInstancesByPageArgs struct { + ClusterID string + Params *ListInstancesByPageParams +} + +// CreateClusterRequest - 创建 Cluster 参数 +type CreateClusterRequest struct { + ClusterSpec *types.ClusterSpec `json:"cluster"` + MasterSpecs []*InstanceSet `json:"masters,omitempty"` + NodeSpecs []*InstanceSet `json:"nodes,omitempty"` +} + +type InstanceSet struct { + InstanceSpec types.InstanceSpec `json:"instanceSpec"` + Count int `json:"count"` +} + +// ListInstancesByPageParams - 分页查询集群实例列表参数 +type ListInstancesByPageParams struct { + KeywordType InstanceKeywordType `json:"keywordType"` + Keyword string `json:"keyword"` + OrderBy InstanceOrderBy `json:"orderBy"` + Order Order `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + EnableInternalFields bool `json:"enableInternalFields"` +} + +// CreateClusterResponse - 创建 Cluster 返回 +type CreateClusterResponse struct { + ClusterID string `json:"clusterID"` + RequestID string `json:"requestID"` +} + +// UpdateClusterResponse - 更新 Cluster 返回 +type UpdateClusterResponse struct { + Cluster *Cluster `json:"cluster"` + RequestID string `json:"requestID"` +} + +// GetClusterResponse - 查询 Cluster 返回 +type GetClusterResponse struct { + Cluster *Cluster `json:"cluster"` + RequestID string `json:"requestID"` +} + +// DeleteClusterResponse - 删除 Cluster 返回 +type DeleteClusterResponse struct { + RequestID string `json:"requestID"` +} + +// ListClustersResponse - List 用户 Cluster 返回 +type ListClustersResponse struct { + ClusterPage *ClusterPage `json:"clusterPage"` + RequestID string `json:"requestID"` +} + +// CreateInstancesResponse - 创建 Instances 返回 +type CreateInstancesResponse struct { + CCEInstanceIDs []string `json:"cceInstanceIDs"` + RequestID string `json:"requestID"` +} + +type UpdateInstanceArgs struct { + ClusterID string + InstanceID string + InstanceSpec *types.InstanceSpec +} + +// UpdateInstancesResponse - 更新 Instances 返回 +type UpdateInstancesResponse struct { + Instance *Instance `json:"instance"` + RequestID string `json:"requestID"` +} + +// ClusterPage - 集群分页查询返回 +type ClusterPage struct { + KeywordType ClusterKeywordType `json:"keywordType"` + Keyword string `json:"keyword"` + OrderBy ClusterOrderBy `json:"orderBy"` + Order Order `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + ClusterList []*Cluster `json:"clusterList"` +} + +// ClusterKeywordType 集群模糊查询字段 +type ClusterKeywordType string + +const ( + // ClusterKeywordTypeClusterName 集群模糊查询字段: ClusterName + ClusterKeywordTypeClusterName ClusterKeywordType = "clusterName" + // ClusterKeywordTypeClusterID 集群模糊查询字段: ClusterID + ClusterKeywordTypeClusterID ClusterKeywordType = "clusterID" +) + +// ClusterOrderBy 集群查询排序字段 +type ClusterOrderBy string + +const ( + // ClusterOrderByClusterName 集群查询排序字段: ClusterName + ClusterOrderByClusterName ClusterOrderBy = "clusterName" + // ClusterOrderByClusterID 集群查询排序字段: ClusterID + ClusterOrderByClusterID ClusterOrderBy = "clusterID" + // ClusterOrderByCreatedAt 集群查询排序字段: CreatedAt + ClusterOrderByCreatedAt ClusterOrderBy = "createdAt" +) + +// Order 集群查询排序 +type Order string + +const ( + // OrderASC 集群查询排序: 升序 + OrderASC Order = "ASC" + // OrderDESC 集群查询排序: 降序 + OrderDESC Order = "DESC" +) + +const ( + // PageNoDefault 分页查询默认页码 + PageNoDefault int = 1 + // PageSizeDefault 分页查询默认页面元素数目 + PageSizeDefault int = 10 +) + +// GetInstanceResponse - 查询 Instances 返回 +type GetInstanceResponse struct { + Instance *Instance `json:"instance"` + RequestID string `json:"requestID"` +} + +// DeleteInstancesResponse - 删除 Instances 返回 +type DeleteInstancesResponse struct { + RequestID string `json:"requestID"` +} + +// ListInstancesResponse - List Instances 返回 +type ListInstancesResponse struct { + InstancePage *InstancePage `json:"instancePage"` + RequestID string `json:"requestID"` +} + +// GetQuotaResponse - 查询 Quota 返回 +type GetQuotaResponse struct { + types.Quota + RequestID string `json:"requestID"` +} + +// Cluster - Cluster 返回 +type Cluster struct { + Spec *ClusterSpec `json:"spec"` + Status *ClusterStatus `json:"status"` + + CreatedAt time.Time `json:"createdAt,omitempty"` + UpdatedAt time.Time `json:"updatedAt,omitempty"` +} + +// 作为返回值的ClusterSpec +type ClusterSpec struct { + ClusterID string `json:"clusterID"` + ClusterName string `json:"clusterName"` + ClusterType types.ClusterType `json:"clusterType"` + + Description string `json:"description"` + + K8SVersion types.K8SVersion `json:"k8sVersion"` + + VPCID string `json:"vpcID"` + VPCCIDR string `json:"vpcCIDR"` + + Plugins []string `json:"plugins"` + + MasterConfig types.MasterConfig `json:"masterConfig"` + ContainerNetworkConfig types.ContainerNetworkConfig `json:"containerNetworkConfig"` +} + +// ClusterStatus - Cluster Status +type ClusterStatus struct { + ClusterBLB BLB `json:"clusterBLB"` + + ClusterPhase types.ClusterPhase `json:"clusterPhase"` + + NodeNum int `json:"nodeNum"` +} + +// BLB 定义 BLB 类型 +type BLB struct { + ID string `json:"id"` + VPCIP string `json:"vpcIP"` + EIP string `json:"eip"` +} + +// InstancePage - 节点分页查询返回 +type InstancePage struct { + ClusterID string `json:"clusterID"` + KeywordType InstanceKeywordType `json:"keywordType"` + Keyword string `json:"keyword"` + OrderBy InstanceOrderBy `json:"orderBy"` + Order Order `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + InstanceList []*Instance `json:"instanceList"` +} + +// InstanceKeywordType 节点模糊查询字段 +type InstanceKeywordType string + +const ( + // InstanceKeywordTypeInstanceName 节点模糊查询字段: InstanceName + InstanceKeywordTypeInstanceName InstanceKeywordType = "instanceName" + // InstanceKeywordTypeInstanceID 节点模糊查询字段: InstanceID + InstanceKeywordTypeInstanceID InstanceKeywordType = "instanceID" +) + +// InstanceOrderBy 节点查询排序字段 +type InstanceOrderBy string + +const ( + // InstanceOrderByInstanceName 节点查询排序字段: InstanceName + InstanceOrderByInstanceName InstanceOrderBy = "instanceName" + // InstanceOrderByInstanceID 节点查询排序字段: InstanceID + InstanceOrderByInstanceID InstanceOrderBy = "instanceID" + // InstanceOrderByCreatedAt 节点查询排序字段: CreatedAt + InstanceOrderByCreatedAt InstanceOrderBy = "createdAt" +) + +// Instance - 节点详情 +// 作为sdk返回结果的Instance +type Instance struct { + Spec *types.InstanceSpec `json:"spec"` + Status *InstanceStatus `json:"status"` + + CreatedAt time.Time `json:"createdAt,omitempty"` + UpdatedAt time.Time `json:"updatedAt,omitempty"` +} + +type InstanceCRD struct { + ObjectMeta `json:"metadata,omitempty"` + + Spec types.InstanceSpec `json:"spec,omitempty"` + Status InstanceStatus `json:"status,omitempty"` +} + +type ClusterCRD struct { + ObjectMeta `json:"metadata,omitempty"` + + Spec types.ClusterSpec `json:"spec,omitempty"` + Status ClusterStatus `json:"status,omitempty"` +} + +type ObjectMeta struct { + Name string `json:"name,omitempty"` + GenerateName string `json:"generateName,omitempty"` + ClusterName string `json:"clusterName,omitempty"` +} + +// InstanceStatus - Instance Status +type InstanceStatus struct { + Machine Machine `json:"machine"` + + InstancePhase types.InstancePhase `json:"instancePhase"` + MachineStatus types.ServerStatus `json:"machineStatus"` +} + +// Machine - 定义机器相关信息 +type Machine struct { + InstanceID string `json:"instanceID"` + + OrderID string `json:"orderID,omitempty"` + + MountList []types.MountConfig `json:"mountList,omitempty"` + + VPCIP string `json:"vpcIP,omitempty"` + VPCIPIPv6 string `json:"vpcIPIPv6,omitempty"` + + EIP string `json:"eip,omitempty"` +} + +// DeleteInstancesRequest - 删除节点请求 +type DeleteInstancesRequest struct { + InstanceIDs []string `json:"instanceIDs,omitempty"` + DeleteOption *types.DeleteOption `json:"deleteOption,omitempty"` +} + +// InstanceKeyType - ListInstanceByPage 参数 +type InstanceKeyType string + +// NetworkConflictType 冲突类型 +type NetworkConflictType string + +const ( + // ContainerCIDRAndNodeCIDRConflict 容器网段和本集群的节点网段冲突 + ContainerCIDRAndNodeCIDRConflict NetworkConflictType = "ContainerCIDRAndNodeCIDR" + // ContainerCIDRAndExistedClusterContainerCIDRConflict 容器网段和 VPC 内已有集群的容器网段冲突 + ContainerCIDRAndExistedClusterContainerCIDRConflict NetworkConflictType = "ContainerCIDRAndExistedClusterContainerCIDR" + // ContainerCIDRAndVPCRouteConflict 容器网段与 VPC 路由冲突 + ContainerCIDRAndVPCRouteConflict NetworkConflictType = "ContainerCIDRAndVPCRoute" + // ClusterIPCIDRAndNodeCIDRConflict ClusterIP 网段与本集群节点网段冲突 + ClusterIPCIDRAndNodeCIDRConflict NetworkConflictType = "ClusterIPCIDRAndNodeCIDR" + // ClusterIPCIDRAndContainerCIDRConflict ClusterIP 网段与本集群容器网段冲突 + ClusterIPCIDRAndContainerCIDRConflict NetworkConflictType = "ClusterIPCIDRAndContainerCIDR" +) + +// PrivateNetString IPv4/IPv6 私有网络地址类型 +type PrivateNetString string + +const ( + // PrivateIPv4Net10 - IPv4 10 段 + PrivateIPv4Net10 PrivateNetString = "10.0.0.0/8" + + // PrivateIPv4Net172 - IPv4 172 段 + PrivateIPv4Net172 PrivateNetString = "172.16.0.0/12" + + // PrivateIPv4Net192 - IPv4 192 段 + PrivateIPv4Net192 PrivateNetString = "192.168.0.0/16" + + // PrivateIPv6Net - IPv6 段 + PrivateIPv6Net PrivateNetString = "fc00::/7" +) + +const ( + // MaxClusterIPServiceNum 集群最大的 ClusterIP Service 数量 + MaxClusterIPServiceNum = 65536 +) + +// CheckContainerNetworkCIDRRequest 包含检查容器网络网段冲突的请求参数 +type CheckContainerNetworkCIDRArgs struct { + VPCID string `json:"vpcID"` + VPCCIDR string `json:"vpcCIDR"` + VPCCIDRIPv6 string `json:"vpcCIDRIPv6"` + ContainerCIDR string `json:"containerCIDR"` + ContainerCIDRIPv6 string `json:"containerCIDRIPv6"` + ClusterIPCIDR string `json:"clusterIPCIDR"` + ClusterIPCIDRIPv6 string `json:"clusterIPCIDRIPv6"` + MaxPodsPerNode int `json:"maxPodsPerNode"` + IPVersion types.ContainerNetworkIPType `json:"ipVersion"` // if not set, set ipv4 +} + +// CheckClusterIPCIDRequest - 检查 ClusterIP CIDR 请求 +type CheckClusterIPCIDRArgs struct { + VPCID string `json:"vpcID"` + VPCCIDR string `json:"vpcCIDR"` + VPCCIDRIPv6 string `json:"vpcCIDRIPv6"` + ClusterIPCIDR string `json:"clusterIPCIDR"` + ClusterIPCIDRIPv6 string `json:"clusterIPCIDRIPv6"` + IPVersion types.ContainerNetworkIPType `json:"ipVersion"` // if not set, set ipv4 +} + +// CheckContainerNetworkCIDRResponse 检查容器网络网段冲突的响应 +type CheckContainerNetworkCIDRResponse struct { + MaxNodeNum int `json:"maxNodeNum"` + NetworkConflictInfo + RequestID string `json:"requestID"` +} + +// CheckClusterIPCIDRResponse - 检查 ClusterIP CIDR 返回 +type CheckClusterIPCIDRResponse struct { + IsConflict bool `json:"isConflict"` + ErrMsg string `json:"errMsg"` + RequestID string `json:"requestID"` +} + +// RecommendContainerCIDRRequest 推荐容器网段的请求参数 +type RecommendContainerCIDRArgs struct { + VPCID string `json:"vpcID"` + VPCCIDR string `json:"vpcCIDR"` + VPCCIDRIPv6 string `json:"vpcCIDRIPv6"` + // ClusterMaxNodeNum 集群节点的最大规模 + ClusterMaxNodeNum int `json:"clusterMaxNodeNum"` + MaxPodsPerNode int `json:"maxPodsPerNode"` + // PrivateNetCIDRs 候选的容器网段列表,只能从 [10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16] 里选择 + PrivateNetCIDRs []PrivateNetString `json:"privateNetCIDRs"` + PrivateNetCIDRIPv6s []PrivateNetString `json:"privateNetCIDRIPv6s"` + K8SVersion types.K8SVersion `json:"k8sVersion"` + IPVersion types.ContainerNetworkIPType `json:"ipVersion"` // if not set, set ipv4 +} + +// RecommendContainerCIDRResponse 推荐容器网段的响应 +type RecommendContainerCIDRResponse struct { + RecommendedContainerCIDRs []string `json:"recommendedContainerCIDRs"` + RecommendedContainerCIDRIPv6s []string `json:"recommendedContainerCIDRIPv6s"` + IsSuccess bool `json:"isSuccess"` + ErrMsg string `json:"errMsg"` + RequestID string `json:"requestID"` +} + +// RecommendClusterIPCIDRRequest 推荐 ClusterIP 网段的请求参数 +type RecommendClusterIPCIDRArgs struct { + VPCCIDR string `json:"vpcCIDR"` + VPCCIDRIPv6 string `json:"vpcCIDRIPv6"` + ContainerCIDR string `json:"containerCIDR"` + ContainerCIDRIPv6 string `json:"containerCIDRIPv6"` + // ClusterMaxServiceNum 集群 Service 最大规模 + ClusterMaxServiceNum int `json:"clusterMaxServiceNum"` + // PrivateNetCIDRs 候选的 ClusterIP 网段列表,只能从 [10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16] 里选择 + PrivateNetCIDRs []PrivateNetString `json:"privateNetCIDRs"` + PrivateNetCIDRIPv6s []PrivateNetString `json:"privateNetCIDRIPv6s"` + IPVersion types.ContainerNetworkIPType `json:"ipVersion"` // if not set, set ipv4 +} + +// RecommendClusterIPCIDRResponse 推荐 ClusterIP 网段的响应 +type RecommendClusterIPCIDRResponse struct { + RecommendedClusterIPCIDRs []string `json:"recommendedClusterIPCIDRs"` + RecommendedClusterIPCIDRIPv6s []string `json:"recommendedClusterIPCIDRIPv6s"` + IsSuccess bool `json:"isSuccess"` + ErrMsg string `json:"errMsg"` + RequestID string `json:"requestID"` +} + +// NetworkConflictInfo 容器网络整体配置冲突信息 +type NetworkConflictInfo struct { + IsConflict bool `json:"isConflict"` + ErrMsg string `json:"errMsg"` + ContainerCIDRConflict *ContainerCIDRConflict `json:"containerCIDRConflict"` // 容器网段冲突信息 + ClusterIPCIDRConflict *ClusterIPCIDRConflict `json:"clusterIPCIDRConflict"` // ClusterIP 网段冲突信息 +} + +// ContainerCIDRConflict 容器网段冲突信息 +type ContainerCIDRConflict struct { + // NetworkConflictType 冲突类型,可取的值: ContainerCIDRAndNodeCIDRConflict、ContainerCIDRAndExistedClusterContainerCIDRConflict、ContainerCIDRAndVPCRouteConflict + ConflictType NetworkConflictType `json:"conflictType"` + // ConflictNodeCIDR 与容器网段冲突的节点网段,当且仅当 NetworkConflictType 为 ContainerCIDRAndNodeCIDRConflict 不为 nil + ConflictNodeCIDR *ConflictNodeCIDR `json:"conflictNodeCIDR"` + // ConflictCluster 与容器网段冲突的VPC内集群,当且仅当 NetworkConflictType 为 ContainerCIDRAndExistedClusterContainerCIDRConflict 不为 nil + ConflictCluster *ConflictCluster `json:"conflictCluster"` + // ConflictVPCRoute 与容器网段冲突的VPC路由,当且仅当 NetworkConflictType 为 ContainerCIDRAndVPCRouteConflict 不为 nil + ConflictVPCRoute *ConflictVPCRoute `json:"conflictVPCRoute"` +} + +// ClusterIPCIDRConflict ClusterIP 网段冲突信息 +type ClusterIPCIDRConflict struct { + // NetworkConflictType 冲突类型,可取的值: ClusterIPCIDRAndNodeCIDRConflict、ClusterIPCIDRAndContainerCIDRConflict + ConflictType NetworkConflictType `json:"conflictType"` + // ConflictNodeCIDR 与 ClusterIP 网段冲突的节点网段,当且仅当 NetworkConflictType 为 ClusterIPCIDRAndNodeCIDRConflict 不为 nil + ConflictNodeCIDR *ConflictNodeCIDR `json:"conflictNodeCIDR"` + // ConflictContainerCIDR 与 ClusterIP 网段冲突的节点网段,当且仅当 NetworkConflictType 为 ClusterIPCIDRAndContainerCIDRConflict 不为 nil + ConflictContainerCIDR *ConflictContainerCIDR `json:"conflictContainerCIDR"` +} + +// ConflictNodeCIDR 节点网段冲突信息 +type ConflictNodeCIDR struct { + NodeCIDR string `json:"nodeCIDR"` +} + +// ConflictContainerCIDR 容器网段冲突信息 +type ConflictContainerCIDR struct { + ContainerCIDR string `json:"containerCIDR"` +} + +// ConflictCluster 同一 VPC 内容器网段冲突的集群信息 +type ConflictCluster struct { + ClusterID string `json:"clusterID"` + ContainerCIDR string `json:"containerCIDR"` +} + +// ConflictVPCRoute 冲突的 VPC 路由 +type ConflictVPCRoute struct { + RouteRule vpc.RouteRule `json:"routeRule"` +} + +type InstanceTemplate struct { + types.InstanceSpec `json:",inline"` +} + +type CommonResponse struct { + RequestID string `json:"requestID"` +} + +type InstanceGroup struct { + Spec *InstanceGroupSpec `json:"spec"` + Status *InstanceGroupStatus `json:"status"` + CreatedAt time.Time `json:"createdAt"` +} + +type InstanceGroupSpec struct { + CCEInstanceGroupID string `json:"cceInstanceGroupID,omitempty"` + InstanceGroupName string `json:"instanceGroupName"` + + ClusterID string `json:"clusterID,omitempty"` + ClusterRole types.ClusterRole `json:"clusterRole,omitempty"` + ShrinkPolicy ShrinkPolicy `json:"shrinkPolicy,omitempty"` + UpdatePolicy UpdatePolicy `json:"updatePolicy,omitempty"` + CleanPolicy CleanPolicy `json:"cleanPolicy,omitempty"` + + InstanceTemplate InstanceTemplate `json:"instanceTemplate"` + Replicas int `json:"replicas"` + + ClusterAutoscalerSpec *ClusterAutoscalerSpec `json:"clusterAutoscalerSpec,omitempty"` +} + +type ShrinkPolicy string +type UpdatePolicy string +type CleanPolicy string + +type ClusterAutoscalerSpec struct { + Enabled bool `json:"enabled"` + MinReplicas int `json:"minReplicas"` + MaxReplicas int `json:"maxReplicas"` + ScalingGroupPriority int `json:"scalingGroupPriority"` +} + +// InstanceGroupStatus - +type InstanceGroupStatus struct { + ReadyReplicas int `json:"readyReplicas"` + Pause *PauseDetail `json:"pause,omitempty"` +} + +type PauseDetail struct { + Paused bool `json:"paused"` + Reason string `json:"reason"` +} + +// CreateInstanceGroupRequest - 创建InstanceGroup request +type CreateInstanceGroupRequest struct { + types.InstanceGroupSpec +} + +// CreateInstanceGroupResponse - 创建InstanceGroup response +type CreateInstanceGroupResponse struct { + CommonResponse + InstanceGroupID string `json:"instanceGroupID"` +} + +type ListInstanceGroupResponse struct { + CommonResponse + Page ListInstanceGroupPage `json:"page"` +} + +type ListInstanceGroupPage struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + List []*InstanceGroup `json:"list"` +} + +type GetInstanceGroupResponse struct { + CommonResponse + InstanceGroup *InstanceGroup `json:"instanceGroup"` +} + +type UpdateInstanceGroupReplicasRequest struct { + Replicas int `json:"replicas"` + InstanceIDs []string `json:"instanceIDs"` + DeleteInstance bool `json:"deleteInstance"` + DeleteOption *types.DeleteOption `json:"deleteOption,omitempty"` +} + +type UpdateInstanceGroupReplicasResponse struct { + CommonResponse +} + +type UpdateInstanceGroupClusterAutoscalerSpecResponse struct { + CommonResponse +} + +type DeleteInstanceGroupResponse struct { + CommonResponse +} + +type ListInstancesByInstanceGroupIDPage struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + List []*Instance `json:"list"` +} + +type ListInstancesByInstanceGroupIDResponse struct { + CommonResponse + Page ListInstancesByInstanceGroupIDPage `json:"page"` +} + +type GetAutoscalerArgs struct { + ClusterID string +} + +type GetAutoscalerResponse struct { + Autoscaler *Autoscaler `json:"autoscaler"` + RequestID string `json:"requestID"` +} + +type UpdateAutoscalerArgs struct { + ClusterID string + AutoscalerConfig ClusterAutoscalerConfig +} + +type UpdateAutoscalerResponse struct { + CommonResponse +} + +type CreateAutoscalerArgs struct { + ClusterID string +} + +type CreateAutoscalerResponse struct { + CommonResponse +} + +type Autoscaler struct { + ClusterID string `json:"clusterID"` + ClusterName string `json:"clusterName"` + CAConfig ClusterAutoscalerConfig `json:"caConfig,omitempty"` +} + +type ClusterAutoscalerConfig struct { + KubeVersion string `json:"kubeVersion,omitempty"` + ReplicaCount int `json:"replicaCount"` + InstanceGroups []ClusterAutoscalerInstanceGroup `json:"instanceGroups,omitempty"` + // default: false + ScaleDownEnabled bool `json:"scaleDownEnabled"` + // 可选,缩容阈值百分比,范围(0, 100) + ScaleDownUtilizationThreshold *int `json:"scaleDownUtilizationThreshold,omitempty"` + // 可选,GPU缩容阈值百分比,范围(0, 100) + ScaleDownGPUUtilizationThreshold *int `json:"scaleDownGPUUtilizationThreshold,omitempty"` + // 可选,缩容触发时延,单位:m + ScaleDownUnneededTime *int `json:"scaleDownUnneededTime,omitempty"` + // 可选,扩容后缩容启动时延,单位:m + ScaleDownDelayAfterAdd *int `json:"scaleDownDelayAfterAdd,omitempty"` + // 可选,最大并发缩容数 + MaxEmptyBulkDelete *int `json:"maxEmptyBulkDelete,omitempty"` + // 可选, + SkipNodesWithLocalStorage *bool `json:"skipNodesWithLocalStorage,omitempty"` + // 可选, + SkipNodesWithSystemPods *bool `json:"skipNodesWithSystemPods,omitempty"` + // supported: random, most-pods, least-waste, priority; default: random + Expander string `json:"expander"` +} + +type ClusterAutoscalerInstanceGroup struct { + InstanceGroupID string + MinReplicas int + MaxReplicas int + Priority int +} + +type InstanceGroupListOption struct { + PageNo int + PageSize int +} + +type CreateInstanceGroupArgs struct { + ClusterID string + Request *CreateInstanceGroupRequest +} + +type ListInstanceGroupsArgs struct { + ClusterID string + ListOption *InstanceGroupListOption +} + +type ListInstanceByInstanceGroupIDArgs struct { + ClusterID string + InstanceGroupID string + PageNo int + PageSize int +} + +type GetInstanceGroupArgs struct { + ClusterID string + InstanceGroupID string +} + +type UpdateInstanceGroupClusterAutoscalerSpecArgs struct { + ClusterID string + InstanceGroupID string + Request *ClusterAutoscalerSpec +} + +type UpdateInstanceGroupReplicasArgs struct { + ClusterID string + InstanceGroupID string + Request *UpdateInstanceGroupReplicasRequest +} + +type DeleteInstanceGroupArgs struct { + ClusterID string + InstanceGroupID string + DeleteInstances bool + ReleaseAllResources bool +} + +// KubeConfigType - kube config 类型 +type KubeConfigType string + +const ( + // KubeConfigTypeInternal 使用 BLB FloatingIP + KubeConfigTypeInternal KubeConfigType = "internal" + + // KubeConfigTypeVPC 使用 BLB VPCIP + KubeConfigTypeVPC KubeConfigType = "vpc" + + // KubeConfigTypePublic 使用 BLB EIP + KubeConfigTypePublic KubeConfigType = "public" +) + +type GetKubeConfigArgs struct { + ClusterID string + KubeConfigType KubeConfigType +} + +// GetKubeConfigResponse - 查询 KubeConfig 返回 +type GetKubeConfigResponse struct { + KubeConfigType KubeConfigType `json:"kubeConfigType"` + KubeConfig string `json:"kubeConfig"` + RequestID string `json:"requestID"` +} + +func CheckKubeConfigType(kubeConfigType string) error { + if kubeConfigType != string(KubeConfigTypePublic) && + kubeConfigType != string(KubeConfigTypeInternal) && + kubeConfigType != string(KubeConfigTypeVPC) { + return fmt.Errorf("KubeConfigType %s not valid", kubeConfigType) + } + return nil +} + +type CreateScaleUpInstanceGroupTaskArgs struct { + ClusterID string + InstanceGroupID string + TargetReplicas int +} + +type CreateScaleDownInstanceGroupTaskArgs struct { + ClusterID string + InstanceGroupID string + InstancesToBeRemoved []string +} + +type CreateTaskResp struct { + CommonResponse + TaskID string `json:"taskID"` +} + +type GetTaskArgs struct { + TaskType types.TaskType + TaskID string +} + +type ListTasksArgs struct { + TaskType types.TaskType + TargetID string + PageNo int + PageSize int +} + +type GetTaskResp struct { + CommonResponse + Task *types.Task `json:"task"` +} + +type ListTaskResp struct { + CommonResponse + Page ListTaskPage +} + +type ListTaskPage struct { + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` + TotalCount int `json:"totalCount"` + Items []*types.Task `json:"items"` +} + +type UpdateInstanceCRDRequest struct { + Instance *InstanceCRD `json:"instance"` +} + +type GetInstanceCRDResponse struct { + Instance *InstanceCRD `json:"instance"` + RequestID string `json:"requestID"` +} + +type GetClusterCRDArgs struct { + ClusterID string `json:"clusterID"` +} + +type GetClusterCRDResponse struct { + Cluster *ClusterCRD `json:"cluster"` + RequestID string `json:"requestID"` +} + +type UpdateClusterCRDArgs struct { + Cluster *ClusterCRD `json:"cluster"` +} + +type UpdateClusterCRDResponses struct { +} diff --git a/bce-sdk-go/services/cce/v2/types/bcc.go b/bce-sdk-go/services/cce/v2/types/bcc.go new file mode 100644 index 0000000..441e893 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/bcc.go @@ -0,0 +1,76 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +import bccapi "github.com/baidubce/bce-sdk-go/services/bcc/api" + +const ( + // InstanceTypeDCC DCC 类型 + InstanceTypeDCC bccapi.InstanceType = "DCC" + // InstanceTypeBBC BBC 类型 + InstanceTypeBBC bccapi.InstanceType = "BBC" + // InstanceTypeBBCGPU BBC GPU 类型 + InstanceTypeBBCGPU bccapi.InstanceType = "BBC_GPU" +) + +// SecurityGroupRule 安全组规则 +type SecurityGroupRule struct { + SecurityGroupID string `json:"securityGroupId"` + EtherType EtherType `json:"ethertype"` + Direction Direction `json:"direction"` + Protocol Protocol `json:"protocol"` + SourceGroupID string `json:"sourceGroupId"` + SourceIP string `json:"sourceIp"` + DestGroupID string `json:"destGroupId"` + DestIP string `json:"destIp"` + PortRange string `json:"portRange"` + Remark string `json:"remark"` +} + +type Direction string + +const ( + DirectionIngress Direction = "ingress" + DirectionEgress Direction = "egress" +) + +type EtherType string + +const ( + EtherTypeIPv4 EtherType = "IPv4" + EtherTypeIPv6 EtherType = "IPv6" +) + +type Protocol string + +const ( + ProtocolAll Protocol = "all" + ProtocolTCP Protocol = "tcp" + ProtocolUDP Protocol = "udp" + ProtocolICMP Protocol = "icmp" +) + +// GPUType GPU 类型 +type GPUType string + +const ( + // GPUTypeV100_32 NVIDIA Tesla V100-32G + GPUTypeV100_32 GPUType = "V100-32" + // GPUTypeV100_16 NVIDIA Tesla V100-16G + GPUTypeV100_16 GPUType = "V100-16" + // GPUTypeP40 P40 NVIDIA Tesla P40 + GPUTypeP40 GPUType = "P40" + // GPUTypeP4 P4 NVIDIA Tesla P4 + GPUTypeP4 GPUType = "P4" + // GPUTypeK40 K40 NVIDIA Tesla K40 + GPUTypeK40 GPUType = "K40" + // GPUTypeDLCard NVIDIA 深度学习开发卡 + GPUTypeDLCard GPUType = "DLCard" +) diff --git a/bce-sdk-go/services/cce/v2/types/bccimage.go b/bce-sdk-go/services/cce/v2/types/bccimage.go new file mode 100644 index 0000000..9c9f87f --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/bccimage.go @@ -0,0 +1,42 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +import bccapi "github.com/baidubce/bce-sdk-go/services/bcc/api" + +const ( + ImageTypeService bccapi.ImageType = "service" +) + +// OSType 操作系统类型 +type OSType string + +const ( + // OSTypeLinux linux + OSTypeLinux OSType = "linux" + // OSTypeWindows windows + OSTypeWindows OSType = "windows" +) + +// OSName 操作系统名字 +type OSName string + +const ( + // OSNameCentOS centos + OSNameCentOS OSName = "CentOS" + // OSNameUbuntu ubuntu + OSNameUbuntu OSName = "Ubuntu" + // OSNameWindows windows + OSNameWindows OSName = "Windows Server" + // OSNameDebian debian + OSNameDebian OSName = "Debian" + // OSNameOpensuse opensuse + OSNameOpensuse OSName = "opensuse" +) diff --git a/bce-sdk-go/services/cce/v2/types/cce_supported.go b/bce-sdk-go/services/cce/v2/types/cce_supported.go new file mode 100644 index 0000000..332dd2f --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/cce_supported.go @@ -0,0 +1,111 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +import ( + bccapi "github.com/baidubce/bce-sdk-go/services/bcc/api" +) + +// SupportedInstanceType - CCE 支持的 Instance 类型 +var SupportedInstanceType = map[bccapi.InstanceType]string{ + bccapi.InstanceTypeN1: "", + bccapi.InstanceTypeN2: "", + bccapi.InstanceTypeN3: "", + bccapi.InstanceTypeN4: "", + bccapi.InstanceTypeN5: "", + bccapi.InstanceTypeC1: "", + bccapi.InstanceTypeC2: "", + bccapi.InstanceTypeS1: "", + bccapi.InstanceTypeG1: "", + bccapi.InstanceTypeF1: "", + // 以下为 CCE 自行定义 + InstanceTypeDCC: "", + InstanceTypeBBC: "", + InstanceTypeBBCGPU: "", +} + +// SupportedStorageType - CCE 支持的 Storage 类型 +var SupportedStorageType = map[bccapi.StorageType]string{ + bccapi.StorageTypeStd1: "", + bccapi.StorageTypeHP1: "", + bccapi.StorageTypeCloudHP1: "", +} + +// SupportedRootDiskStorageType - CCE 支持的 RootDiskStorage 类型 +var SupportedRootDiskStorageType = map[bccapi.StorageType]string{ + bccapi.StorageTypeHP1: "", + bccapi.StorageTypeCloudHP1: "", +} + +// SupportedGPUType - CCE 支持的 GPU 类型 +var SupportedGPUType = map[GPUType]string{ + GPUTypeV100_32: "", + GPUTypeV100_16: "", + GPUTypeP40: "", + GPUTypeP4: "", + GPUTypeK40: "", + GPUTypeDLCard: "", +} + +// SupportedK8SVersions - CCE 支持的 K8s 版本 +var SupportedK8SVersions = map[K8SVersion]string{ + K8S_1_13_10: "", + K8S_1_16_8: "", +} + +// SupportedClusterHA - CCE 支持的 ClusterHA 类型 +var SupportedClusterHA = map[ClusterHA]string{ + ClusterHALow: "", + ClusterHAMedium: "", + ClusterHAHigh: "", +} + +// SupportedMasterType - CCE 支持 Master 类型 +var SupportedMasterType = map[MasterType]string{ + MasterTypeManaged: "", + MasterTypeCustom: "", + MasterTypeServerless: "", +} + +// SupportedImageType - CCE 支持镜像类型 +var SupportedImageType = map[bccapi.ImageType]string{ + bccapi.ImageTypeSystem: "", + bccapi.ImageTypeCustom: "", + bccapi.ImageTypeGPUSystem: "", + bccapi.ImageTypeGPUCustom: "", + bccapi.ImageTypeSharing: "", + bccapi.ImageTypeIntegration: "", + ImageTypeService: "", + // ImageTypeBBCSystem BBC 公有 + bccapi.ImageTypeBBCSystem: "", + // ImageTypeBBCCustom BBC 自定义 + bccapi.ImageTypeBBCCustom: "", +} + +// SupportedContainerNetworkMode - CCE 支持的容器网络类型 +var SupportedContainerNetworkMode = map[ContainerNetworkMode]string{ + ContainerNetworkModeKubenet: "", + ContainerNetworkModeVPCCNI: "", + ContainerNetworkModeVPCRouteAutoDetect: "", + ContainerNetworkModeVPCRouteVeth: "", + ContainerNetworkModeVPCRouteIPVlan: "", + ContainerNetworkModeVPCSecondaryIPAutoDetect: "", + ContainerNetworkModeVPCSecondaryIPVeth: "", + ContainerNetworkModeVPCSecondaryIPIPVlan: "", +} + +var SupportedRuntimeType = map[RuntimeType]string{ + RuntimeTypeDocker: "", +} + +var SupportedKubeProxyMode = map[KubeProxyMode]string{ + KubeProxyModeIptables: "", + KubeProxyModeIPVS: "", +} diff --git a/bce-sdk-go/services/cce/v2/types/cluster.go b/bce-sdk-go/services/cce/v2/types/cluster.go new file mode 100644 index 0000000..9e6ea05 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/cluster.go @@ -0,0 +1,291 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +const ( + // LatestSupportedK8SVersion latest K8S Version that we supported + LatestSupportedK8SVersion = "1.16.8" + + // DefaultRuntime default runtime + DefaultRuntime = "docker" + + // LatestSupportedDockerVersion default docker version + LatestSupportedDockerVersion = "18.09.2" + + CCEPrefix = "cce-" + + // ClusterIDLabelKey 关联 ClusterCRD 和 InstanceCRD 或 InstanceGroupCRD + ClusterIDLabelKey = "cluster-id" + + ClusterRoleLabelKey = "cluster-role" + + DoNotHandle = "not-handler-by-cce" +) + +// 创建集群时使用的ClusterSpec +type ClusterSpec struct { + + // 创建集群时无需传入ClusterID + ClusterID string `json:"clusterID,omitempty" ` + + // ClusterName 由用户指定 + ClusterName string `json:"clusterName" valid:"Required"` + + ClusterType ClusterType `json:"clusterType,omitempty" valid:"Required"` + + Description string `json:"description,omitempty"` + + K8SVersion K8SVersion `json:"k8sVersion,omitempty"` + + RuntimeType RuntimeType `json:"runtimeType,omitempty"` + RuntimeVersion string `json:"runtimeVersion,omitempty"` + + // VPCCIDR 无需用户设置 + VPCID string `json:"vpcID,omitempty" valid:"Required"` + VPCCIDR string `json:"vpcCIDR,omitempty"` + VPCCIDRIPv6 string `json:"vpcCIDRIPv6,omitempty"` + + // PluginListType CCE 插件类型 + Plugins []string `json:"plugins,omitempty"` + + MasterConfig MasterConfig `json:"masterConfig,omitempty" valid:"Required"` + ContainerNetworkConfig ContainerNetworkConfig `json:"containerNetworkConfig,omitempty" valid:"Required"` + + AuthenticateMode AuthenticateMode `json:"authenticateMode,omitempty"` // APIServer 认证方式 + + // K8S 自定义配置 + K8SCustomConfig K8SCustomConfig `json:"k8sCustomConfig,omitempty"` +} + +// K8SCustomConfig - K8S 自定义配置 +type K8SCustomConfig struct { + MasterFeatureGates map[string]bool `json:"masterFeatureGates,omitempty"` // 自定义 FeatureGates + NodeFeatureGates map[string]bool `json:"nodeFeatureGates,omitempty"` // 自定义 FeatureGates + AdmissionPlugins []string `json:"admissionPlugins,omitempty"` // 自定义 AdmissionPlugins + PauseImage string `json:"pauseImage,omitempty"` // 自定义 PauseImage + KubeAPIQPS int `json:"kubeAPIQPS,omitempty"` // 自定义 KubeAPIQPS + KubeAPIBurst int `json:"kubeAPIBurst,omitempty"` // 自定义 KubeAPIBurst + SchedulerPredicates []string `json:"schedulerPredicates,omitempty"` // 自定义 SchedulerPredicates + SchedulerPriorities map[string]int `json:"schedulerPriorities,omitempty"` // 自定义 SchedulerPriorities + ETCDDataPath string `json:"etcdDataPath,omitempty"` // 自定义 etcd数据目录 +} + +// ClusterType usually used to init Provider +// and it represents the difference between IaaS +type ClusterType string + +const ( + // ClusterTypeNormal = 普通类型集群 + ClusterTypeNormal ClusterType = "normal" +) + +// K8SVersion defines the k8stypes version of cluster +type K8SVersion string + +const ( + //1.6和1.8不再支持,扩缩容需要联系CCE人员手动操作 + //K8S_1_6_2 K8SVersion = "1.6.2" + //K8S_1_8_6 K8SVersion = "1.8.6" + //K8S_1_8_12 K8SVersion = "1.8.12" + //1.11.1 1.11.5 1.13.4仅支持已有集群扩容节点,不支持新创建集群 + //K8S_1_11_1 K8SVersion = "1.11.1" + //K8S_1_11_5 K8SVersion = "1.11.5" + //K8S_1_13_4 K8SVersion = "1.13.4" + //支持在console创建集群 + K8S_1_13_10 K8SVersion = "1.13.10" + //K8S_1_16_3 K8SVersion = "1.16.3" + K8S_1_16_8 K8SVersion = "1.16.8" +) + +// MasterConfig Master 配置 +type MasterConfig struct { + // MasterTypes: 托管, 自定义, 已有 BCC, 已有 BBC + MasterType MasterType `json:"masterType,omitempty"` + + // ClusterHA 对 3 种集群都有效: 对于 Custom 和 Existed 作为校验和展示作用 + ClusterHA ClusterHA `json:"clusterHA,omitempty"` + + ExposedPublic bool `json:"exposedPublic,omitempty"` + + ClusterBLBVPCSubnetID string `json:"clusterBLBVPCSubnetID,omitempty"` + + ManagedClusterMasterOption `json:"managedClusterMasterOption,omitempty"` +} + +// ManagedClusterMasterOption 托管集群 Master 配置 +type ManagedClusterMasterOption struct { + MasterVPCSubnetZone AvailableZone `json:"masterVPCSubnetZone,omitempty"` +} + +// RuntimeType defines the runtime on each node +type RuntimeType string + +const ( + RuntimeTypeDocker RuntimeType = "docker" +) + +// ContainerNetworkConfig defines the network config +// Some attrs have default value +type ContainerNetworkConfig struct { + // CCE 支持网络类型: kubenet 及 vpc-cni + Mode ContainerNetworkMode `json:"mode,omitempty"` // If not set, set mode = kubenet + + // ENI 网络模式子网 + ENIVPCSubnetIDs map[AvailableZone][]string `json:"eniVPCSubnetIDs,omitempty"` + ENISecurityGroupID string `json:"eniSecurityGroupID,omitempty"` + + // CCE 支持集群 IP version: dual stack, ipv4 only, ipv6 only + IPVersion ContainerNetworkIPType `json:"ipVersion,omitempty"` // if not set, set ipv4 + + // LB Service 关联 BLB 所在子网, 目前只能为普通子网 + LBServiceVPCSubnetID string `json:"lbServiceVPCSubnetID,omitempty" valid:"Required"` + + // 指定 NodePort Service 的端口范围 + NodePortRangeMin int `json:"nodePortRangeMin,omitempty"` + NodePortRangeMax int `json:"nodePortRangeMax,omitempty"` + + // 集群 PodIP CIDR, 在 kubenet 网络模式下有效 + ClusterPodCIDR string `json:"clusterPodCIDR,omitempty"` + ClusterPodCIDRIPv6 string `json:"clusterPodCIDRIPv6,omitempty"` + + // Service ClusterIP 的 CIDR + ClusterIPServiceCIDR string `json:"clusterIPServiceCIDR,omitempty"` + ClusterIPServiceCIDRIPv6 string `json:"clusterIPServiceCIDRIPv6,omitempty"` + + // 每个 Node 上最大的 Pod 数, 限制 NodeCIDR 的分配 + MaxPodsPerNode int `json:"maxPodsPerNode,omitempty"` // If not set, MaxPodsPerNode = 128 + + // KubeProxy 的模式: iptables 和 ipvs + KubeProxyMode KubeProxyMode `json:"kubeProxyMode,omitempty"` // If not set, kubeProxyMode=ipvs +} + +// ContainerNetworkIPType - 容器 IP 类型 +type ContainerNetworkIPType string + +const ( + // ContainerNetworkIPTypeIPv4 - 容器网段 IPv4 + ContainerNetworkIPTypeIPv4 ContainerNetworkIPType = "ipv4" + // ContainerNetworkIPTypeIPv6 - 容器网段 IPv6 + ContainerNetworkIPTypeIPv6 ContainerNetworkIPType = "ipv6" + // ContainerNetworkIPTypeDualStack - 容器网段双栈 + ContainerNetworkIPTypeDualStack ContainerNetworkIPType = "dualStack" +) + +// ContainerNetworkMode defines container config +type ContainerNetworkMode string + +const ( + // ContainerNetworkModeKubenet using kubenet + ContainerNetworkModeKubenet ContainerNetworkMode = "kubenet" + + // ContainerNetworkModeVPCCNI using vpc-cni + ContainerNetworkModeVPCCNI ContainerNetworkMode = "vpc-cni" + + // ContainerNetworkModeVPCRouteVeth using vpc route plus veth + ContainerNetworkModeVPCRouteVeth ContainerNetworkMode = "vpc-route-veth" + + // ContainerNetworkModeVPCRouteIPVlan using vpc route plus ipvlan + ContainerNetworkModeVPCRouteIPVlan ContainerNetworkMode = "vpc-route-ipvlan" + + // ContainerNetworkModeVPCRouteAutoDetect using vpc route and auto detects veth or ipvlan due to kernel version + ContainerNetworkModeVPCRouteAutoDetect ContainerNetworkMode = "vpc-route-auto-detect" + + // ContainerNetworkModeVPCSecondaryIPVeth using vpc secondary ip plus veth + ContainerNetworkModeVPCSecondaryIPVeth ContainerNetworkMode = "vpc-secondary-ip-veth" + + // ContainerNetworkModeVPCSecondaryIPIPVlan using vpc secondary ip plus ipvlan + ContainerNetworkModeVPCSecondaryIPIPVlan ContainerNetworkMode = "vpc-secondary-ip-ipvlan" + + // ContainerNetworkModeVPCSecondaryIPAutoDetect using vpc secondary ip and auto detects veth or ipvlan due to kernel version + ContainerNetworkModeVPCSecondaryIPAutoDetect ContainerNetworkMode = "vpc-secondary-ip-auto-detect" +) + +// KubeProxyMode defines kube-proxy --proxy-mode +// If not set, using KubeProxyModeIPVS as default +type KubeProxyMode string + +const ( + // KubeProxyModeIPVS --proxy-mode=ipvs + KubeProxyModeIPVS KubeProxyMode = "ipvs" + + // KubeProxyModeIptables --proxy-mode=iptables + KubeProxyModeIptables KubeProxyMode = "iptables" +) + +// MasterType 定义 Master 机器来源 +type MasterType string + +const ( + // MasterTypeManaged 托管 Master + MasterTypeManaged MasterType = "managed" + + // MasterTypeCustom 自定义集群, 包含: + // 1. 新建 BCC; + // 2. 已有 BCC; + // 3. 已有 BBC. + MasterTypeCustom MasterType = "custom" + + // MasterTypeServerless Serverless集群Master + MasterTypeServerless MasterType = "serverless" +) + +// ClusterHA Cluster Master 对应副本数 +type ClusterHA int + +const ( + // ClusterHALow 单 Master + ClusterHALow ClusterHA = 1 + // ClusterHAMedium 三 Master + ClusterHAMedium ClusterHA = 3 + // ClusterHAHigh 五 Master + ClusterHAHigh ClusterHA = 5 + // ClusterHAServerless Cluster Master 副本数 + ClusterHAServerless ClusterHA = 2 +) + +// ClusterPhase for CCE K8S Cluster Phase +type ClusterPhase string + +const ( + // ClusterPhasePending 创建 Cluster 时默认状态 + ClusterPhasePending ClusterPhase = "pending" + + // ClusterPhaseProvisioning IaaS 相关资源正在创建中 + ClusterPhaseProvisioning ClusterPhase = "provisioning" + + // ClusterPhaseProvisioned IaaS 相关资源已经 Ready + ClusterPhaseProvisioned ClusterPhase = "provisioned" + + // ClusterPhaseRunning 集群运行正常 + ClusterPhaseRunning ClusterPhase = "running" + + // ClusterPhaseCreateFailed 集群创建失败 + ClusterPhaseCreateFailed ClusterPhase = "create_failed" + + // ClusterPhaseDeleting 集群正在删除 + ClusterPhaseDeleting ClusterPhase = "deleting" + + // ClusterPhaseDeleted 集群删除完成 + ClusterPhaseDeleted ClusterPhase = "deleted" + + // ClusterPhaseDeleteFailed 集群删除失败 + ClusterPhaseDeleteFailed ClusterPhase = "delete_failed" +) + +// AuthenticateMode - 认证类型 +type AuthenticateMode string + +const ( + // AuthenticateModeX509 - X509 + AuthenticateModeX509 AuthenticateMode = "x509" + + // AuthenticateModeOIDC - OIDC + AuthenticateModeOIDC AuthenticateMode = "oidc" +) diff --git a/bce-sdk-go/services/cce/v2/types/eip.go b/bce-sdk-go/services/cce/v2/types/eip.go new file mode 100644 index 0000000..05f4afd --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/eip.go @@ -0,0 +1,30 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +// BillingMethod 计费方式 +type BillingMethod string + +const ( + // BillingMethodByTraffic 按照流量计费 + BillingMethodByTraffic BillingMethod = "ByTraffic" + // BillingMethodByBandwidth 按带宽计费 + BillingMethodByBandwidth BillingMethod = "ByBandwidth" +) + +// PaymentTiming 付费时间选择 +type PaymentTiming string + +const ( + // PaymentTimingPrepaid 预付费 + PaymentTimingPrepaid PaymentTiming = "Prepaid" + // PaymentTimingPostpaid 后付费 + PaymentTimingPostpaid PaymentTiming = "Postpaid" +) diff --git a/bce-sdk-go/services/cce/v2/types/instance.go b/bce-sdk-go/services/cce/v2/types/instance.go new file mode 100644 index 0000000..9b8064e --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/instance.go @@ -0,0 +1,368 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +import ( + bccapi "github.com/baidubce/bce-sdk-go/services/bcc/api" + "github.com/baidubce/bce-sdk-go/services/vpc" +) + +// 已有节点需要用户提供:ClusterRole 、短ID,密码,镜像ID,镜像类型, docker storage(可选); BBC要额外加preservedData、raidId、sysRootSize +type InstanceSpec struct { + + // 用于 CCE 唯一标识 Instance + CCEInstanceID string `json:"cceInstanceID,omitempty"` + InstanceName string `json:"instanceName"` + + RuntimeType RuntimeType `json:"runtimeType,omitempty"` + RuntimeVersion string `json:"runtimeVersion,omitempty"` + + ClusterID string `json:"clusterID,omitempty"` + ClusterRole ClusterRole `json:"clusterRole,omitempty"` + + InstanceGroupID string `json:"instanceGroupID,omitempty"` + InstanceGroupName string `json:"instanceGroupName,omitempty"` + + // 初始化 DelProvider 使用 + MasterType MasterType `json:"masterType,omitempty"` + + // 是否为已有实例 + Existed bool `json:"existed,omitempty"` + ExistedOption ExistedOption `json:"existedOption,omitempty"` + + // BCC, BBC, 裸金属 + MachineType MachineType `json:"machineType,omitempty"` + // 机器规格: 普通一, 普通二 ... + InstanceType bccapi.InstanceType `json:"instanceType"` + // BBC 选项 + BBCOption *BBCOption `json:"bbcOption,omitempty"` + + // 是否为竞价实例 + Bid bool `json:"bid,omitempty"` + BidOption BidOption `json:"bidOption,omitempty"` + + // VPC 相关配置 + VPCConfig VPCConfig `json:"vpcConfig,omitempty"` + + // 集群规格相关配置 + InstanceResource InstanceResource `json:"instanceResource,omitempty"` + + // 优先使用 ImageID, 如果用户传入 InstanceOS 信息, 由 service 计算 ImageID + ImageID string `json:"imageID,omitempty"` + InstanceOS InstanceOS `json:"instanceOS,omitempty"` + + // EIP + NeedEIP bool `json:"needEIP,omitempty"` + EIPOption *EIPOption `json:"eipOption,omitempty"` + + // AdminPassword + AdminPassword string `json:"adminPassword,omitempty"` + SSHKeyID string `json:"sshKeyID,omitempty"` + + // Charging Type, 通常只支持后付费 + InstanceChargingType bccapi.PaymentTimingType `json:"instanceChargingType,omitempty"` // 后付费或预付费 + InstancePreChargingOption InstancePreChargingOption `json:"instancePreChargingOption,omitempty"` + + // 删除节点选项 + DeleteOption *DeleteOption `json:"deleteOption,omitempty"` + + DeployCustomConfig DeployCustomConfig `json:"deployCustomConfig,omitempty"` // 部署相关高级配置 + + Tags TagList `json:"tags,omitempty"` + + Labels InstanceLabels `json:"labels,omitempty"` + Taints InstanceTaints `json:"taints,omitempty"` + Annotations InstanceAnnotations `json:"annotations,omitempty"` + + CCEInstancePriority int `json:"cceInstancePriority,omitempty"` + + AutoSnapshotID string `json:"autoSnapshotID,omitempty"` // 自动快照策略 ID +} + +// VPCConfig 定义 Instance VPC +type VPCConfig struct { + VPCID string `json:"vpcID,omitempty"` + VPCSubnetID string `json:"vpcSubnetID,omitempty"` + SecurityGroupID string `json:"securityGroupID,omitempty"` + + VPCSubnetType vpc.SubnetType `json:"vpcSubnetType,omitempty"` + VPCSubnetCIDR string `json:"vpcSubnetCIDR,omitempty"` + VPCSubnetCIDRIPv6 string `json:"vpcSubnetCIDRIPv6,omitempty"` + + AvailableZone AvailableZone `json:"availableZone,omitempty"` + + SecurityGroup SecurityGroup `json:"securityGroup,omitempty"` +} + +// SecurityGroup 定义 Instance 安全组配置 +type SecurityGroup struct { + // 是否附加 CCE 必须安全组 + EnableCCERequiredSecurityGroup bool `json:"enableCCERequiredSecurityGroup"` + // 是否附加 CCE 可选安全组 + EnableCCEOptionalSecurityGroup bool `json:"enableCCEOptionalSecurityGroup"` + // 用户自定义安全组 ID 列表 + CustomSecurityGroupIDs []string `json:"customSecurityGroups,omitempty"` +} + +// InstanceResource 定义 Instance CPU/MEM/Disk 配置 +type InstanceResource struct { + MachineSpec string `json:"machineSpec,omitempty"` // 机器规格,例:bcc.g5.c2m8 + + CPU int `json:"cpu,omitempty"` // unit: Core + MEM int `json:"mem,omitempty"` // unit: GB + + NodeCPUQuota int `json:"nodeCPUQuota,omitempty"` // unit: Core + NodeMEMQuota int `json:"nodeMEMQuota,omitempty"` // unit: GB + + // RootDisk + RootDiskType bccapi.StorageType `json:"rootDiskType,omitempty"` + RootDiskSize int `json:"rootDiskSize,omitempty"` // unit: GB + + // GPU 机器必须指定, 其他机器不用 + LocalDiskSize int `json:"localDiskSize,omitempty"` // unit: GB + + // CDS 列表, 默认第一块盘作为 docker 和 kubelet 数据盘 + CDSList CDSConfigList `json:"cdsList,omitempty"` + + // Only necessary when InstanceType = GPU + GPUType GPUType `json:"gpuType,omitempty"` + GPUCount int `json:"gpuCount,omitempty"` +} + +// EIPOption 定义 Instance EIP 相关配置 +type EIPOption struct { + EIPName string `json:"eipName,omitempty"` + EIPChargingType BillingMethod `json:"eipChargeType,omitempty"` + EIPBandwidth int `json:"eipBandwidth,omitempty"` +} + +// InstancePreChargingOption 定义付费相关配置 +type InstancePreChargingOption struct { + PurchaseTime int `json:"purchaseTime,omitempty"` // 预付费才生效:单位月,12 = 12 月 + AutoRenew bool `json:"autoRenew,omitempty"` // 是否自动续费 + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` // 续费单位:月 + AutoRenewTime int `json:"autoRenewTime,omitempty"` // 12 = 12 个月 +} + +// DeleteOption 删除节点选项 +type DeleteOption struct { + MoveOut bool `json:"moveOut,omitempty"` + DeleteResource bool `json:"deleteResource,omitempty"` + DeleteCDSSnapshot bool `json:"deleteCDSSnapshot,omitempty"` +} + +// BBCOption BBC 相关配置 +type BBCOption struct { + Flavor string `json:"flavor,omitempty"` + DiskInfo string `json:"diskInfo,omitempty"` + // 是否保留数据 + ReserveData bool `json:"reserveData,omitempty"` + // 磁盘阵列类型 ID + RaidID string `json:"raidID,omitempty"` + // 系统盘分配大小 + SysDiskSize int `json:"sysDiskSize,omitempty"` +} + +// DeployCustomConfig - 部署自定义配置 +type DeployCustomConfig struct { + // Docker相关配置 + DockerConfig DockerConfig `json:"dockerConfig,omitempty"` + // containerd相关配置 + ContainerdConfig ContainerdConfig `json:"containerdConfig,omitempty"` + + // kubelet数据目录 + KubeletRootDir string `json:"kubeletRootDir,omitempty"` + // 是否开启资源预留 + EnableResourceReserved bool `json:"EnableResourceReserved,omitempty"` + // k8s进程资源预留配额 + // key:value: cpu: 50m, memory: 100Mi + KubeReserved map[string]string `json:"kubeReserved,omitempty"` + // 系统进程资源预留配额 + // key:value: cpu: 50m, memory: 100Mi + SystemReserved map[string]string `json:"systemReserved,omitempty"` + + // RegistryPullQPS, default: 5 + RegistryPullQPS int `json:"registryPullQPS,omitempty"` + // RegistryBurst, default: 10 + RegistryBurst int `json:"registryBurst,omitempty"` + // PodPidsLimit, default: -1 + PodPidsLimit int `json:"podPidsLimit,omitempty"` + + // 是否封锁节点 + EnableCordon bool `json:"enableCordon,omitempty"` + + // 部署前执行脚本, 前端 base64编码后传参 + PreUserScript string `json:"preUserScript,omitempty"` + // 部署后执行脚本, 前端 base64编码后传参 + PostUserScript string `json:"postUserScript,omitempty"` + + // KubeletBindAddressType, kubelet bind address + KubeletBindAddressType KubeletBindAddressType `json:"kubeletBindAddressType,omitempty"` +} + +// DockerConfig docker相关配置 +type DockerConfig struct { + DockerDataRoot string `json:"dockerDataRoot,omitempty"` // 自定义 docker 数据目录 + RegistryMirrors []string `json:"registryMirrors,omitempty"` // 自定义 RegistryMirrors + InsecureRegistries []string `json:"insecureRegistries,omitempty"` // 自定义 InsecureRegistries + DockerLogMaxSize string `json:"dockerLogMaxSize,omitempty"` // docker日志大小,default: 20m + DockerLogMaxFile string `json:"dockerLogMaxFile,omitempty"` // docker日志保留数,default: 10 + BIP string `json:"dockerBIP,omitempty"` // docker0网桥网段, default: 169.254.30.1/28 +} + +// ContainerdConfig containerd相关配置 +type ContainerdConfig struct { + DataRoot string `json:"dataRoot,omitempty"` // 自定义 containerd 数据目录 + RegistryMirrors []string `json:"registryMirrors,omitempty"` // 自定义 RegistryMirrors + InsecureRegistries []string `json:"insecureRegistries,omitempty"` // 自定义 InsecureRegistries +} + +// ExistedOption 已有实例相关配置 +type ExistedOption struct { + ExistedInstanceID string `json:"existedInstanceID,omitempty"` + + // nil 为默认: 重装系统 + Rebuild *bool `json:"rebuild,omitempty"` +} + +// MachineType 机器类型: BCC, BBC +type MachineType string + +const ( + // MachineTypeBCC 机器类型 BCC + MachineTypeBCC MachineType = "BCC" + + // MachineTypeBBC 机器类型 BBC + MachineTypeBBC MachineType = "BBC" + + // MachineTypeMetal 机器类型 裸金属 + MachineTypeMetal MachineType = "Metal" +) + +// CDSConfig clone from BCC +type CDSConfig struct { + Path string `json:"diskPath,omitempty"` + StorageType bccapi.StorageType `json:"storageType,omitempty"` + CDSSize int `json:"cdsSize,omitempty"` + SnapshotID string `json:"snapshotID,omitempty"` +} + +// MountConfig - 磁盘挂载信息 +type MountConfig struct { + Path string `json:"diskPath,omitempty"` // "/data" + CDSID string `json:"cdsID,omitempty"` + Device string `json:"device,omitempty"` // "/dev/vdb" + CDSSize int `json:"cdsSize,omitempty"` + StorageType bccapi.StorageType `json:"storageType,omitempty"` +} + +// ClusterRole master & slave +type ClusterRole string + +const ( + // ClusterRoleMaster K8S master + ClusterRoleMaster ClusterRole = "master" + + // ClusterRoleNode K8S node + ClusterRoleNode ClusterRole = "node" +) + +// InstanceOS defines the OS of BCC +type InstanceOS struct { + ImageType bccapi.ImageType `json:"imageType,omitempty"` // 镜像类型 + ImageName string `json:"imageName,omitempty"` // 镜像名字: ubuntu-14.04.1-server-amd64-201506171832 + OSType OSType `json:"osType,omitempty"` // e.g. linux + OSName OSName `json:"osName,omitempty"` // e.g. Ubuntu + OSVersion string `json:"osVersion,omitempty"` // e.g. 14.04.1 LTS + OSArch string `json:"osArch,omitempty"` // e.g. x86_64 (64bit) + OSBuild string `json:"osBuild,omitempty"` // e.g. 2015061700 +} + +// InstancePhase CCE InstancePhase +type InstancePhase string + +const ( + // InstancePhasePending 创建节点时默认状态 + InstancePhasePending InstancePhase = "pending" + + // InstancePhaseProvisioning IaaS 相关资源正在创建中 + InstancePhaseProvisioning InstancePhase = "provisioning" + + // InstancePhaseProvisioned IaaS 相关资源已经 Ready + InstancePhaseProvisioned InstancePhase = "provisioned" + + // InstancePhaseRunning 节点运行正常 + InstancePhaseRunning InstancePhase = "running" + + // InstancePhaseCreateFailed 节点异常 + InstancePhaseCreateFailed InstancePhase = "create_failed" + + // InstancePhaseDeleting 节点正在删除 + InstancePhaseDeleting InstancePhase = "deleting" + + // InstancePhaseDeleted 节点删除完成 + InstancePhaseDeleted InstancePhase = "deleted" + + // InstancePhaseDeleteFailed 节点删除失败 + InstancePhaseDeleteFailed InstancePhase = "delete_failed" +) + +// KubeletBindAddressType - kubelet bind address 类型 +type KubeletBindAddressType string + +const ( + // KubeletBindAddressTypeAll - 0.0.0.0 + KubeletBindAddressTypeAll KubeletBindAddressType = "all" + + // KubeletBindAddressTypeLocal - 127.0.0.1 + KubeletBindAddressTypeLocal KubeletBindAddressType = "local" + + // KubeletBindAddressTypeHostIP - 主网卡 IP + KubeletBindAddressTypeHostIP KubeletBindAddressType = "hostip" +) + +type BidOption struct { + // BidMode 竞价模式 + BidMode BidMode `json:"bidMode,omitempty"` + + // BidPrice 用户的出价, 仅在 BidMode=BidModeCustomPrice 模式下生效 + BidPrice string `json:"bidPrice,omitempty"` + + // BidTime 竞价超时时间, 单位: minute, 超时会取消该竞价实例订单 + BidTimeout int `json:"bidTimeout,omitempty"` + + // BidReleaseEIP 竞价实例被动释放时, 是否联动释放实例 EIP + BidReleaseEIP bool `json:"bidReleaseEIP,omitempty"` + + // BidReleaseEIP 竞价实例被动释放时, 是否联动释放实例 CDS + BidReleaseCDS bool `json:"bidReleaseCDS,omitempty"` +} + +type CDSConfigList []CDSConfig + +type TagList []Tag + +type InstanceLabels map[string]string + +type InstanceTaints []Taint + +type InstanceAnnotations map[string]string + +type BBCFlavorID string + +type BidMode string + +const ( + // BidModeMarketPrice 跟随市场价出价 + BidModeMarketPrice BidMode = "MARKET_PRICE_BID" + + // BidModeCustomPrice 用户自定义出价 + BidModeCustomPrice BidMode = "CUSTOM_BID" +) diff --git a/bce-sdk-go/services/cce/v2/types/instance_group.go b/bce-sdk-go/services/cce/v2/types/instance_group.go new file mode 100644 index 0000000..708ece1 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/instance_group.go @@ -0,0 +1,91 @@ +package types + +const ( + DefaultShrinkPolicy = PriorityShrinkPolicy + PriorityShrinkPolicy ShrinkPolicy = "Priority" + RandomShrinkPolicy ShrinkPolicy = "Random" + + DefaultUpdatePolicy = ConcurrencyUpdatePolicy + RollingUpdatePolicy UpdatePolicy = "Rolling" + ConcurrencyUpdatePolicy UpdatePolicy = "Concurrency" + + DefaultCleanPolicy = RemainCleanPolicy + RemainCleanPolicy CleanPolicy = "Remain" + DeleteCleanPolicy CleanPolicy = "Delete" +) + +type InstanceGroupSpec struct { + CCEInstanceGroupID string `json:"cceInstanceGroupID,omitempty" ` + InstanceGroupName string `json:"instanceGroupName" ` + + ClusterID string `json:"clusterID,omitempty" ` + ClusterRole ClusterRole `json:"clusterRole,omitempty" ` + + Selector *InstanceSelector `json:"selector" ` + + ShrinkPolicy ShrinkPolicy `json:"shrinkPolicy,omitempty" ` + + UpdatePolicy UpdatePolicy `json:"updatePolicy,omitempty" ` + + CleanPolicy CleanPolicy `json:"cleanPolicy,omitempty" ` + + InstanceTemplate InstanceTemplate `json:"instanceTemplate" ` + Replicas int `json:"replicas" ` + + ClusterAutoscalerSpec *ClusterAutoscalerSpec `json:"clusterAutoscalerSpec,omitempty" ` +} + +type InstanceTemplate struct { + InstanceSpec `json:",inline"` +} + +type InstanceSelector struct { + LabelSelector `json:",inline"` +} + +type ShrinkPolicy string +type UpdatePolicy string +type CleanPolicy string + +type ClusterAutoscalerSpec struct { + Enabled bool `json:"enabled" ` + MinReplicas int `json:"minReplicas" ` + MaxReplicas int `json:"maxReplicas" ` + ScalingGroupPriority int `json:"scalingGroupPriority" ` +} + +type InstanceGroupStatus struct { + ReadyReplicas int `json:"readyReplicas" ` + UndeliveredMachines UndeliveredMachines `json:"undeliveredMachines,omitempty" ` + Pause *PauseDetail `json:"pause,omitempty" ` +} + +type UndeliveredMachines struct { + FailedMachines []string `json:"failedMachines,omitempty"` + PendingMachines []string `json:"pendingMachines,omitempty"` +} + +type PauseDetail struct { + Paused bool `json:"paused"` + Reason string `json:"reason"` +} + +type LabelSelector struct { + MatchLabels map[string]string `json:"matchLabels,omitempty" protobuf:"bytes,1,rep,name=matchLabels"` + MatchExpressions []LabelSelectorRequirement `json:"matchExpressions,omitempty" protobuf:"bytes,2,rep,name=matchExpressions"` +} + +type LabelSelectorRequirement struct { + Key string `json:"key" patchStrategy:"merge" patchMergeKey:"key" protobuf:"bytes,1,opt,name=key"` + Operator LabelSelectorOperator `json:"operator" protobuf:"bytes,2,opt,name=operator,casttype=LabelSelectorOperator"` + Values []string `json:"values,omitempty" protobuf:"bytes,3,rep,name=values"` +} + +type LabelSelectorOperator string + +const ( + LabelSelectorOpIn LabelSelectorOperator = "In" + LabelSelectorOpNotIn LabelSelectorOperator = "NotIn" + LabelSelectorOpExists LabelSelectorOperator = "Exists" + LabelSelectorOpDoesNotExist LabelSelectorOperator = "DoesNotExist" +) diff --git a/bce-sdk-go/services/cce/v2/types/internalblb.go b/bce-sdk-go/services/cce/v2/types/internalblb.go new file mode 100644 index 0000000..deb189b --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/internalblb.go @@ -0,0 +1,21 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +// BLBType for load balancer type +type BLBType string + +const ( + // BLBTypeNormal 普通 BLB 类型 + BLBTypeNormal BLBType = "normal" + + // BLBTypeApplication 应用型 BLB 类型 + BLBTypeApplication BLBType = "application" +) diff --git a/bce-sdk-go/services/cce/v2/types/internalvpc.go b/bce-sdk-go/services/cce/v2/types/internalvpc.go new file mode 100644 index 0000000..66274e9 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/internalvpc.go @@ -0,0 +1,33 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +// AvailableZone 可用区 +type AvailableZone string + +const ( + // ZoneA 可用区 A + AvailableZoneA AvailableZone = "zoneA" + + // ZoneB 可用区 B + AvailableZoneB AvailableZone = "zoneB" + + // ZoneC 可用区 C + AvailableZoneC AvailableZone = "zoneC" + + // ZoneD 可用区 D + AvailableZoneD AvailableZone = "zoneD" + + // ZoneE 可用区 E + AvailableZoneE AvailableZone = "zoneE" + + // ZoneF 可用区 F + AvailableZoneF AvailableZone = "zoneF" +) diff --git a/bce-sdk-go/services/cce/v2/types/k8stypes.go b/bce-sdk-go/services/cce/v2/types/k8stypes.go new file mode 100644 index 0000000..38524fa --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/k8stypes.go @@ -0,0 +1,193 @@ +package types + +import ( + "encoding/json" + "time" +) + +// The node this Taint is attached to has the "effect" on +// any pod that does not tolerate the Taint. +type Taint struct { + // Required. The taint key to be applied to a node. + Key string `json:"key" protobuf:"bytes,1,opt,name=key"` + // Required. The taint value corresponding to the taint key. + // +optional + Value string `json:"value,omitempty" protobuf:"bytes,2,opt,name=value"` + // Required. The effect of the taint on pods + // that do not tolerate the taint. + // Valid effects are NoSchedule, PreferNoSchedule and NoExecute. + Effect TaintEffect `json:"effect" protobuf:"bytes,3,opt,name=effect,casttype=TaintEffect"` + // TimeAdded represents the time at which the taint was added. + // It is only written for NoExecute taints. + // +optional + TimeAdded *Time `json:"timeAdded,omitempty" protobuf:"bytes,4,opt,name=timeAdded"` +} + +type TaintEffect string + +const ( + // Do not allow new pods to schedule onto the node unless they tolerate the taint, + // but allow all pods submitted to Kubelet without going through the scheduler + // to start, and allow all already-running pods to continue running. + // Enforced by the scheduler. + TaintEffectNoSchedule TaintEffect = "NoSchedule" + + // Like TaintEffectNoSchedule, but the scheduler tries not to schedule + // new pods onto the node, rather than prohibiting new pods from scheduling + // onto the node entirely. Enforced by the scheduler. + TaintEffectPreferNoSchedule TaintEffect = "PreferNoSchedule" + + // Evict any already-running pods that do not tolerate the taint. + // Currently enforced by NodeController. + TaintEffectNoExecute TaintEffect = "NoExecute" +) + +// Time is a wrapper around time.Time which supports correct +// marshaling to YAML and JSON. Wrappers are provided for many +// of the factory methods that the time package offers. +// +// +protobuf.options.marshal=false +// +protobuf.as=Timestamp +// +protobuf.options.(gogoproto.goproto_stringer)=false +type Time struct { + time.Time `protobuf:"-"` +} + +// DeepCopyInto creates a deep-copy of the Time value. The underlying time.Time +// type is effectively immutable in the time API, so it is safe to +// copy-by-assign, despite the presence of (unexported) Pointer fields. +func (t *Time) DeepCopyInto(out *Time) { + *out = *t +} + +// NewTime returns a wrapped instance of the provided time +func NewTime(time time.Time) Time { + return Time{time} +} + +// Date returns the Time corresponding to the supplied parameters +// by wrapping time.Date. +func Date(year int, month time.Month, day, hour, min, sec, nsec int, loc *time.Location) Time { + return Time{time.Date(year, month, day, hour, min, sec, nsec, loc)} +} + +// Now returns the current local time. +func Now() Time { + return Time{time.Now()} +} + +// IsZero returns true if the value is nil or time is zero. +func (t *Time) IsZero() bool { + if t == nil { + return true + } + return t.Time.IsZero() +} + +// Before reports whether the time instant t is before u. +func (t *Time) Before(u *Time) bool { + if t != nil && u != nil { + return t.Time.Before(u.Time) + } + return false +} + +// Equal reports whether the time instant t is equal to u. +func (t *Time) Equal(u *Time) bool { + if t == nil && u == nil { + return true + } + if t != nil && u != nil { + return t.Time.Equal(u.Time) + } + return false +} + +// Unix returns the local time corresponding to the given Unix time +// by wrapping time.Unix. +func Unix(sec int64, nsec int64) Time { + return Time{time.Unix(sec, nsec)} +} + +// Rfc3339Copy returns a copy of the Time at second-level precision. +func (t Time) Rfc3339Copy() Time { + copied, _ := time.Parse(time.RFC3339, t.Format(time.RFC3339)) + return Time{copied} +} + +// UnmarshalJSON implements the json.Unmarshaller interface. +func (t *Time) UnmarshalJSON(b []byte) error { + if len(b) == 4 && string(b) == "null" { + t.Time = time.Time{} + return nil + } + + var str string + err := json.Unmarshal(b, &str) + if err != nil { + return err + } + + pt, err := time.Parse(time.RFC3339, str) + if err != nil { + return err + } + + t.Time = pt.Local() + return nil +} + +// UnmarshalQueryParameter converts from a URL query parameter value to an object +func (t *Time) UnmarshalQueryParameter(str string) error { + if len(str) == 0 { + t.Time = time.Time{} + return nil + } + // Tolerate requests from older clients that used JSON serialization to build query params + if len(str) == 4 && str == "null" { + t.Time = time.Time{} + return nil + } + + pt, err := time.Parse(time.RFC3339, str) + if err != nil { + return err + } + + t.Time = pt.Local() + return nil +} + +// MarshalJSON implements the json.Marshaler interface. +func (t Time) MarshalJSON() ([]byte, error) { + if t.IsZero() { + // Encode unset/nil objects as JSON's "null". + return []byte("null"), nil + } + buf := make([]byte, 0, len(time.RFC3339)+2) + buf = append(buf, '"') + // time cannot contain non escapable JSON characters + buf = t.UTC().AppendFormat(buf, time.RFC3339) + buf = append(buf, '"') + return buf, nil +} + +// OpenAPISchemaType is used by the kube-openapi generator when constructing +// the OpenAPI spec of this type. +// +// See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators +func (_ Time) OpenAPISchemaType() []string { return []string{"string"} } + +// OpenAPISchemaFormat is used by the kube-openapi generator when constructing +// the OpenAPI spec of this type. +func (_ Time) OpenAPISchemaFormat() string { return "date-time" } + +// MarshalQueryParameter converts to a URL query parameter value +func (t Time) MarshalQueryParameter() (string, error) { + if t.IsZero() { + // Encode unset/nil objects as an empty string + return "", nil + } + + return t.UTC().Format(time.RFC3339), nil +} diff --git a/bce-sdk-go/services/cce/v2/types/logicbcc.go b/bce-sdk-go/services/cce/v2/types/logicbcc.go new file mode 100644 index 0000000..6af344b --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/logicbcc.go @@ -0,0 +1,57 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +// ServerStatus BCC 虚机状态 +type ServerStatus string + +const ( + // ServerStatusActive 虚机运行中 + ServerStatusActive ServerStatus = "ACTIVE" + + // ServerStatusBuild 虚机创建中 + ServerStatusBuild ServerStatus = "BUILD" + + // ServerStatusRebuild 虚机重装系统中 + ServerStatusRebuild ServerStatus = "REBUILD" + + // ServerStatusDeleted 虚机已删除 + ServerStatusDeleted ServerStatus = "DELETED" + + // ServerStatusSnapshot 创建快照 + ServerStatusSnapshot ServerStatus = "SNAPSHOT" + + // ServerStatusDeleteSnapshot 删除快照 + ServerStatusDeleteSnapshot ServerStatus = "DELETE_SNAPSHOT" + + // ServerStatusVolumeResize VOLUME_RESIZE + ServerStatusVolumeResize ServerStatus = "VOLUME_RESIZE" + + // ServerStatusError 虚机异常 + ServerStatusError ServerStatus = "ERROR" + + // ServerStatusExpired 虚机欠费释放 + ServerStatusExpired ServerStatus = "EXPIRED" + + // ServerStatusReboot 虚机重启 + ServerStatusReboot ServerStatus = "REBOOT" + + // ServerStatusRecharge 虚机续费 + ServerStatusRecharge ServerStatus = "RECHARGE" + + // ServerStatusShutoff 虚机关机 + ServerStatusShutoff ServerStatus = "SHUTOFF" + + // ServerStatusStopped 虚机关机 + ServerStatusStopped ServerStatus = "STOPPED" + + // ServerStatusUnknown 虚机状态未知 + ServerStatusUnknown ServerStatus = "UNKNOWN" +) diff --git a/bce-sdk-go/services/cce/v2/types/tag.go b/bce-sdk-go/services/cce/v2/types/tag.go new file mode 100644 index 0000000..23d53ce --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/tag.go @@ -0,0 +1,22 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2020/07/28 16:26:00, by jichao04@baidu.com, create +*/ + +package types + +// Tag represents TagModel in BCE +type Tag struct { + TagKey string `json:"tagKey"` + TagValue string `json:"tagValue"` +} + +// Quota - CCE Cluster/Node Quota +type Quota struct { + Quota int `json:"quota"` + Used int `json:"used"` +} diff --git a/bce-sdk-go/services/cce/v2/types/task.go b/bce-sdk-go/services/cce/v2/types/task.go new file mode 100644 index 0000000..4345013 --- /dev/null +++ b/bce-sdk-go/services/cce/v2/types/task.go @@ -0,0 +1,56 @@ +// Copyright 2019 Baidu Inc. All rights reserved +// Use of this source code is governed by a CCE +// license that can be found in the LICENSE file. +/* +modification history +-------------------- +2021/06/24 16:00:00, by pansiyuan02@baidu.com, create +*/ +package types + +import "time" + +const ( + TaskTypeInstanceGroupReplicas TaskType = "InstanceGroupReplicas" +) + +const ( + TaskPhasePending TaskPhase = "Pending" + TaskPhaseProcessing TaskPhase = "Processing" + TaskPhaseDone TaskPhase = "Done" + TaskPhaseAborted TaskPhase = "Aborted" +) + +const ( + TaskProcessPhasePending TaskProcessPhase = "Pending" + TaskProcessPhaseProcessing TaskProcessPhase = "Processing" + TaskProcessPhaseDone TaskProcessPhase = "Done" + TaskProcessPhaseAborted TaskProcessPhase = "Aborted" +) + +type TaskType string +type TaskPhase string +type TaskProcessPhase string + +type Task struct { + ID string `json:"id"` + Type TaskType `json:"type"` + Description string `json:"description"` + StartTime time.Time `json:"startTime"` + FinishTime *time.Time `json:"finishTime,omitempty"` + Phase TaskPhase `json:"phase"` + + TaskProcesses []TaskProcess `json:"processes,omitempty"` + ErrMessage string `json:"errMessage,omitempty"` +} + +type TaskProcess struct { + Name string `json:"name"` + Phase TaskProcessPhase `json:"phase,omitempty"` + StartTime *time.Time `json:"startTime,omitempty"` + FinishTime *time.Time `json:"finishTime,omitempty"` + + Metrics map[string]string `json:"metrics,omitempty"` + SubProcesses []TaskProcess `json:"subProcesses,omitempty"` + ErrMessage string `json:"errMessage,omitempty"` +} diff --git a/bce-sdk-go/services/cdn/api/cache.go b/bce-sdk-go/services/cdn/api/cache.go new file mode 100644 index 0000000..b55288b --- /dev/null +++ b/bce-sdk-go/services/cdn/api/cache.go @@ -0,0 +1,335 @@ +package api + +import ( + "errors" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util" +) + +type PurgedId string +type PrefetchId string + +// CStatusQueryData defined a struct for the query conditions about the tasks' progress +type CStatusQueryData struct { + EndTime string + StartTime string + Url string + Marker string + Id string +} + +// CRecordQueryData defined a struct for the query conditions about the operated records +type CRecordQueryData struct { + EndTime string + StartTime string + Url string + Marker string + TaskType string +} + +// PurgeTask defined a struct for purged task +type PurgeTask struct { + Url string `json:"url"` + Type string `json:"type,omitempty"` +} + +// PrefetchTask defined a struct for prefetch task +type PrefetchTask struct { + Url string `json:"url"` + Speed int64 `json:"speed,omitempty"` + StartTime string `json:"startTime,omitempty"` +} + +// CachedDetail defined a struct for task details +type CachedDetail struct { + Status string `json:"status"` + CreatedAt string `json:"createdAt"` + StartedAt string `json:"startedAt"` + FinishedAt string `json:"finishedAt"` + Progress int64 `json:"progress"` +} + +// PurgedDetail defined a struct for purged task information +type PurgedDetail struct { + *CachedDetail + Task PurgeTask `json:"task"` +} + +// PrefetchDetail defined a struct for prefetch task information +type PrefetchDetail struct { + *CachedDetail + Task PrefetchTask `json:"task"` +} + +// PurgedStatus defined a struct for purged status +type PurgedStatus struct { + Details []PurgedDetail `json:"details"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` +} + +// PrefetchStatus defined a struct for prefetch status +type PrefetchStatus struct { + Details []PrefetchDetail `json:"details"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` +} + +// QuotaDetail defined a struct for query quota +type QuotaDetail struct { + DirRemain int64 `json:"dirRemain"` + UrlRemain int64 `json:"urlRemain"` + DirQuota int64 `json:"dirQuota"` + UrlQuota int64 `json:"urlQuota"` +} + +// RecordDetail defined a struct for one operating record +type RecordDetail struct { + Status string `json:"status"` + Url string `json:"url"` + Type string `json:"type"` + CreatedAt string `json:"createdAt"` + StartedAt string `json:"startedAt"` + FinishedAt string `json:"finishedAt"` + Progress int64 `json:"progress"` + Reason string `json:"reason"` + Operator string `json:"operator"` +} + +// RecordDetails defined a struct for multi operating records in some querying conditions +type RecordDetails struct { + Details []RecordDetail `json:"details"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` +} + +// Purge - tells the CDN system to purge the specified files +// For more details, please refer https://cloud.baidu.com/doc/CDN/s/ijwvyeyyj +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - tasks: the tasks about purging the files from the CDN nodes +// +// RETURNS: +// - PurgedId: an ID representing a purged task, using it to search the task progress +// - error: nil if success otherwise the specific error +func Purge(cli bce.Client, tasks []PurgeTask) (PurgedId, error) { + + respObj := &struct { + Id string `json:"id"` + }{} + + err := httpRequest(cli, "POST", "/v2/cache/purge", nil, &struct { + Tasks []PurgeTask `json:"tasks"` + }{ + Tasks: tasks, + }, respObj) + if err != nil { + return "", err + } + + return PurgedId(respObj.Id), nil +} + +// GetPurgedStatus - get the purged progress +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ujwvyezqm +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// +// RETURNS: +// - *PurgedStatus: the details about the purged +// - error: nil if success otherwise the specific error +func GetPurgedStatus(cli bce.Client, queryData *CStatusQueryData) (*PurgedStatus, error) { + if queryData == nil { + queryData = &CStatusQueryData{} + } + + params := map[string]string{} + if queryData.Id != "" { + params["id"] = queryData.Id + } + if err := getTimeParams(params, queryData.StartTime, queryData.EndTime); err != nil { + return nil, err + } + + if queryData.Url != "" { + params["url"] = queryData.Url + } + if queryData.Marker != "" { + params["marker"] = queryData.Marker + } + + respObj := &PurgedStatus{} + err := httpRequest(cli, "GET", "/v2/cache/purge", params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// Prefetch - tells the CDN system to prefetch the specified files +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Rjwvyf0ff +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - tasks: the tasks about prefetch the files from the CDN nodes +// - error: nil if success otherwise the specific error +func Prefetch(cli bce.Client, tasks []PrefetchTask) (PrefetchId, error) { + respObj := &struct { + Id string `json:"id"` + }{} + + err := httpRequest(cli, "POST", "/v2/cache/prefetch", nil, &struct { + Tasks []PrefetchTask `json:"tasks"` + }{ + Tasks: tasks, + }, respObj) + if err != nil { + return "", err + } + + return PrefetchId(respObj.Id), nil +} + +// GetPrefetchStatus - get the prefetch progress +// For details, please refer https://cloud.baidu.com/doc/CDN/s/4jwvyf01w +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// +// RETURNS: +// - *PrefetchStatus: the details about the prefetch +// - error: nil if success otherwise the specific error +func GetPrefetchStatus(cli bce.Client, queryData *CStatusQueryData) (*PrefetchStatus, error) { + if queryData == nil { + queryData = &CStatusQueryData{} + } + + params := map[string]string{} + if queryData.Id != "" { + params["id"] = queryData.Id + } + if err := getTimeParams(params, queryData.StartTime, queryData.EndTime); err != nil { + return nil, err + } + + if queryData.Url != "" { + params["url"] = queryData.Url + } + if queryData.Marker != "" { + params["marker"] = queryData.Marker + } + + respObj := &PrefetchStatus{} + err := httpRequest(cli, "GET", "/v2/cache/prefetch", params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// GetQuota - get the quota about purge and prefetch +// For details, please refer https://cloud.baidu.com/doc/CDN/s/zjwvyeze3 +// +// RETURNS: +// - cli: the client agent which can perform sending request +// - QuotaDetail: the quota details about a specified user +// - error: nil if success otherwise the specific error +func GetQuota(cli bce.Client) (*QuotaDetail, error) { + respObj := &QuotaDetail{} + err := httpRequest(cli, "GET", "/v2/cache/quota", nil, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +func getTimeParams(params map[string]string, startTime, endTime string) error { + // get "endTime" + endTs := int64(0) + if endTime == "" { + // default current time + endTs = time.Now().Unix() + params["endTime"] = util.FormatISO8601Date(endTs) + } else { + t, err := util.ParseISO8601Date(endTime) + if err != nil { + return err + } + endTs = t.Unix() + params["endTime"] = endTime + } + + // get "startTime", the default "startTime" is one day later than the "endTime" + startTs := int64(0) + if startTime == "" { + startTs = endTs - 24*60*60 + params["startTime"] = util.FormatISO8601Date(startTs) + } else { + t, err := util.ParseISO8601Date(startTime) + if err != nil { + return err + } + startTs = t.Unix() + params["startTime"] = startTime + } + + // the "startTime should be less than the "endTime" + // if we set "startTime" but not "endTime", we normally assign the current time to the "endTime", + // in this condition, we might get "startTs > endTs" + if startTs > endTs { + return errors.New("error time range, the startTime should be less than the endTime") + } + + return nil +} + +// GetCacheOpRecords get the history operating records +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jypnzjqt +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryData: querying conditions, it contains the time interval, the task type and the specified url +// +// RETURNS: +// - *RecordDetails: the details about the records +// - error: nil if success otherwise the specific error +func GetCacheOpRecords(cli bce.Client, queryData *CRecordQueryData) (*RecordDetails, error) { + params := map[string]string{} + if queryData == nil { + queryData = &CRecordQueryData{} + } + + if queryData.TaskType != "" { + params["type"] = queryData.TaskType + } else { + params["type"] = "all" + } + + if err := getTimeParams(params, queryData.StartTime, queryData.EndTime); err != nil { + return nil, err + } + + if queryData.Url != "" { + params["url"] = queryData.Url + } + if queryData.Marker != "" { + params["marker"] = queryData.Marker + } + + respObj := &RecordDetails{} + err := httpRequest(cli, "GET", "/v2/cache/records", params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} diff --git a/bce-sdk-go/services/cdn/api/cert.go b/bce-sdk-go/services/cdn/api/cert.go new file mode 100644 index 0000000..d626a57 --- /dev/null +++ b/bce-sdk-go/services/cdn/api/cert.go @@ -0,0 +1,108 @@ +package api + +import ( + "errors" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// UserCertificate defined a struct for the origin certificate hold by user. +type UserCertificate struct { + CertName string + ServerData string + PrivateData string + LinkData string +} + +// CertificateDetail defined a struct holds the brief information. +type CertificateDetail struct { + CertId string `json:"certId"` + CertName string `json:"certName"` + Status string `json:"status"` + CommonName string `json:"certCommonName"` + DNSNames string `json:"certDNSNames"` + StartTime string `json:"certStartTime"` + StopTime string `json:"certStopTime"` + CreateTime string `json:"certCreateTime"` + UpdateTime string `json:"certUpdateTime"` +} + +// PutCert - put the certificate data for the specified domain to server, you can also enable HTTPS or not. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qjzuz2hp8 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - userCert: certificate data +// - httpsEnabled: "ON" for enable HTTPS, "OFF" for disable HTTPS, otherwise invalid. +// +// RETURNS: +// - string: certId +// - error: nil if success otherwise the specific error +func PutCert(cli bce.Client, domain string, userCert *UserCertificate, httpsEnabled string) (certId string, err error) { + if userCert == nil { + return "", errors.New("userCert can not be nil") + } + if httpsEnabled != "ON" && httpsEnabled != "OFF" { + return "", fmt.Errorf("httpsEnabled either \"ON\" or \"OFF\", your input is \"%s\"", httpsEnabled) + } + + reqObj := map[string]interface{}{ + "certificate": map[string]string{ + "certName": userCert.CertName, + "certServerData": userCert.ServerData, + "certPrivateData": userCert.PrivateData, + "certLinkData": userCert.LinkData, + }, + "httpsEnable": httpsEnabled, + } + + urlPath := fmt.Sprintf("/v2/%s/certificates", domain) + respObj := struct { + CertId string `json:"certId"` + }{} + if err := httpRequest(cli, "PUT", urlPath, nil, reqObj, &respObj); err != nil { + return "", err + } + + return respObj.CertId, nil +} + +// GetCert - query the certificate data for the specified domain. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/kjzuvz70t +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *CertificateDetail: certificate details +// - error: nil if success otherwise the specific error +func GetCert(cli bce.Client, domain string) (certDetail *CertificateDetail, err error) { + urlPath := fmt.Sprintf("/v2/%s/certificates", domain) + respObj := &CertificateDetail{} + if err := httpRequest(cli, "GET", urlPath, nil, nil, respObj); err != nil { + return nil, err + } + return respObj, err +} + +// DeleteCert - delete the certificate data for the specified domain. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ljzuylmee +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *CertificateDetail: certificate details +// - error: nil if success otherwise the specific error +func DeleteCert(cli bce.Client, domain string) error { + urlPath := fmt.Sprintf("/v2/%s/certificates", domain) + var respObj interface{} + if err := httpRequest(cli, "DELETE", urlPath, nil, nil, respObj); err != nil { + return err + } + return nil +} diff --git a/bce-sdk-go/services/cdn/api/domain.go b/bce-sdk-go/services/cdn/api/domain.go new file mode 100644 index 0000000..b42b2bb --- /dev/null +++ b/bce-sdk-go/services/cdn/api/domain.go @@ -0,0 +1,247 @@ +package api + +import ( + "errors" + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// DomainStatus defined a struct for domain info, +// the status only include "RUNNING", "OPERATING" and "STOPPED", +// the other status is undefined +type DomainStatus struct { + Domain string `json:"domain"` + Status string `json:"status"` +} + +// DomainValidInfo defined a struct for `IsValidDomain` return +type DomainValidInfo struct { + Domain string + IsValid bool `json:"isValid"` + Message string `json:"message"` +} + +// OriginPeer defined a struct for an origin server setting +type OriginPeer struct { + Peer string `json:"peer"` + Host string `json:"host,omitempty"` + Backup bool `json:"backup"` + Follow302 bool `json:"follow302"` + Weight int `json:"weight,omitempty"` + ISP string `json:"isp,omitempty"` +} + +// OriginInit defined a struct for creating a new CDN service in `OPENCDN` +type OriginInit struct { + Origin []OriginPeer `json:"origin"` + DefaultHost string `json:"defaultHost,omitempty"` + Form string `json:"form,omitempty"` +} + +// DomainCreatedInfo defined a struct for `CreateDomain` return +type DomainCreatedInfo struct { + Domain string `json:"domain"` + Status string `json:"status"` + Cname string `json:"cname"` +} + +// ListDomains - list all domains that in CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN/s/sjwvyewt1 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - marker: a marker is a start point of searching +// +// RETURNS: +// - []string: domains belongs to the user +// - string: a marker for next searching, empty if is in the end +// - error: nil if success otherwise the specific error +func ListDomains(cli bce.Client, marker string) ([]string, string, error) { + type domainInfo struct { + Name string `json:"name"` + } + + respObj := &struct { + IsTruncated bool `json:"isTruncated"` + Domains []domainInfo `json:"domains"` + NextMarker string `json:"nextMarker"` + }{} + + params := map[string]string{} + if marker != "" { + params["marker"] = marker + } + + err := httpRequest(cli, "GET", "/v2/domain", params, nil, respObj) + if err != nil { + return nil, "", err + } + + domains := make([]string, len(respObj.Domains)) + for i, domain := range respObj.Domains { + domains[i] = domain.Name + } + + return domains, respObj.NextMarker, nil +} + +// GetDomainStatus - get domains' details +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyewf1 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - status: the specified running status, the available values are "RUNNING", "STOPPED", OPERATING or "ALL" +// - rule: the regex matching rule +// +// RETURNS: +// - []DomainStatus: domain details list +// - error: nil if success otherwise the specific error +func GetDomainStatus(cli bce.Client, status string, rule string) ([]DomainStatus, error) { + if status == "" { + return nil, errors.New("domain status parameter could not be empty") + } + + params := map[string]string{ + "status": status, + } + + if rule != "" { + params["rule"] = rule + } + + respObj := &struct { + Domains []DomainStatus `json:"domains"` + }{} + + err := httpRequest(cli, "GET", "/v2/user/domains", params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Domains, nil +} + +// IsValidDomain - check the specified domain whether it can be added to CDN service or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qjwvyexh6 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *DomainValidInfo: available information about the specified domain +// - error: nil if success otherwise the specific error +func IsValidDomain(cli bce.Client, domain string) (*DomainValidInfo, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/valid", domain) + respObj := &DomainValidInfo{} + + err := httpRequest(cli, "GET", urlPath, nil, nil, respObj) + if err != nil { + return nil, err + } + + respObj.Domain = domain + return respObj, nil +} + +// CreateDomain - add a specified domain into CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN/s/gjwvyex4o +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - originInit: initialized data for a CDN domain +// +// RETURNS: +// - *DomainCreatedInfo: the details about created a CDN domain +// - error: nil if success otherwise the specific error +func CreateDomain(cli bce.Client, domain string, originInit *OriginInit) (*DomainCreatedInfo, error) { + urlPath := fmt.Sprintf("/v2/domain/%s", domain) + respObj := &DomainCreatedInfo{} + + err := httpRequest(cli, "PUT", urlPath, nil, originInit, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// EnableDomain - enable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Jjwvyexv8 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func EnableDomain(cli bce.Client, domain string) error { + if domain == "" { + return errors.New("domain parameter could not be empty") + } + + params := map[string]string{ + "enable": "", + } + urlPath := fmt.Sprintf("/v2/domain/%s", domain) + + err := httpRequest(cli, "POST", urlPath, params, nil, nil) + if err != nil { + return err + } + + return nil +} + +// DisableDomain - disable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/9jwvyew3e +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DisableDomain(cli bce.Client, domain string) error { + if domain == "" { + return errors.New("domain parameter could not be empty") + } + + params := map[string]string{ + "disable": "", + } + urlPath := fmt.Sprintf("/v2/domain/%s", domain) + + err := httpRequest(cli, "POST", urlPath, params, nil, nil) + if err != nil { + return err + } + + return nil +} + +// DeleteDomain - delete a specified domain from BCE CDN system +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Njwvyey7f +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DeleteDomain(cli bce.Client, domain string) error { + if domain == "" { + return errors.New("domain parameter could not be empty") + } + + urlPath := fmt.Sprintf("/v2/domain/%s", domain) + + err := httpRequest(cli, "DELETE", urlPath, nil, nil, nil) + if err != nil { + return err + } + + return nil +} diff --git a/bce-sdk-go/services/cdn/api/domain_config.go b/bce-sdk-go/services/cdn/api/domain_config.go new file mode 100644 index 0000000..686dc22 --- /dev/null +++ b/bce-sdk-go/services/cdn/api/domain_config.go @@ -0,0 +1,1936 @@ +package api + +import ( + "encoding/json" + "errors" + "fmt" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// DomainConfig defined a struct for a specified domain's configuration +type DomainConfig struct { + Domain string `json:"domain"` + Cname string `json:"cname"` + Status string `json:"status"` + CreateTime string `json:"createTime"` + LastModifyTime string `json:"lastModifyTime"` + IsBan string `json:"isBan"` + Origin []OriginPeer `json:"origin"` + OriginProtocol *OriginProtocol `json:"originProtocol,omitempty"` + OriginTimeout *OriginTimeout `json:"originTimeout,omitempty"` + OriginFixedISP bool `json:"originFixedISP,omitempty"` + DefaultHost string `json:"defaultHost,omitempty"` + RequestHostAsOriginHost bool `json:"requestHostAsOriginHost"` + CacheTTL []CacheTTL `json:"cacheTTL"` + LimitRate int `json:"limitRate"` + RequestAuth *RequestAuth `json:"requestAuth,omitempty"` + Https *HTTPSConfig `json:"https,omitempty"` + FollowProtocol bool `json:"followProtocol"` + SeoSwitch *SeoSwitch `json:"seoSwitch"` + Form string `json:"form"` + RangeSwitch string `json:"rangeSwitch"` + OfflineMode bool `json:"offlineMode"` + ClientIp *ClientIp `json:"clientIp"` + OCSP bool `json:"ocsp"` + HttpHeader []HttpHeader `json:"httpHeader"` + MediaDragConf *MediaDragConf `json:"mediaDragConf"` + FileTrim bool `json:"fileTrim"` + QUIC bool `json:"quic"` + RefererACL *RefererACL `json:"refererACL"` + IpACL *IpACL `json:"ipACL"` + UaAcl *UaACL `json:"uaAcl"` + AccessLimit *AccessLimit `json:"accessLimit"` + TrafficLimit *TrafficLimit `json:"trafficLimit"` + ErrorPage []ErrorPage `json:"errorPage"` + CacheShare *CacheShared `json:"cacheShare"` + Compress *Compress `json:"compress,omitempty"` + Cors *CorsCfg `json:"cors,omitempty"` + Ipv6Dispatch *Ipv6Dispatch `json:"ipv6Dispatch,omitempty"` + RetryOrigin *RetryOrigin `json:"retryOrigin,omitempty"` +} + +// CacheTTL defined a struct for cached rules setting +type CacheTTL struct { + Type string `json:"type"` + Value string `json:"value"` + Weight int `json:"weight,omitempty"` + TTL int `json:"ttl"` +} + +// CacheShared defined a struct for sharing cache with the other domain +type CacheShared struct { + Enabled bool `json:"enabled"` + SharedWith string `json:"domain,omitempty"` +} + +// RequestAuth defined a struct for the authorization setting +type RequestAuth struct { + Type string `json:"type"` + Key1 string `json:"key1"` + Key2 string `json:"key2,omitempty"` + Timeout int `json:"timeout,omitempty"` + WhiteList []string `json:"whiteList,omitempty"` + SignArg string `json:"signArg,omitempty"` + TimeArg string `json:"timeArg,omitempty"` + TimestampFormat string `json:"timestampFormat"` + + // Deprecated, please use TimestampFormat as replacement. + TimestampMetric int `json:"-"` +} + +// HTTPSConfig defined a struct for configuration about HTTPS +type HTTPSConfig struct { + Enabled bool `json:"enabled"` + CertId string `json:"certId,omitempty"` + HttpRedirect bool `json:"httpRedirect"` + HttpRedirectCode int `json:"httpRedirectCode,omitempty"` + HttpsRedirect bool `json:"httpsRedirect"` + HttpsRedirectCode int `json:"httpsRedirectCode"` + Http2Enabled bool `json:"http2Enabled"` + SslVersion string `json:"sslVersion,omitempty"` + VerifyClient bool `json:"verifyClient"` + SslProtocols []string `json:"sslProtocols,omitempty"` + + // Deprecated: You can no longer use this field, + // The better choice is use SetOriginProtocol/GetOriginProtocol. + HttpOrigin bool `json:"-"` +} + +// SeoSwitch defined a struct for SEO setting +type SeoSwitch struct { + DirectlyOrigin string `json:"diretlyOrigin"` + PushRecord string `json:"pushRecord"` +} + +// TrafficLimit defined a struct for configure the traffic limitation +type TrafficLimit struct { + Enabled bool `json:"enable"` + LimitRate int `json:"limitRate,omitempty"` + LimitStartHour int `json:"limitStartHour"` + LimitEndHour int `json:"limitEndHour"` + LimitRateAfter int `json:"limitRateAfter,omitempty"` + TrafficLimitArg string `json:"trafficLimitArg,omitempty"` + TrafficLimitUnit string `json:"trafficLimitUnit,omitempty"` +} + +// HttpHeader defined a struct for a operation about HTTP header +type HttpHeader struct { + Type string `json:"type"` + Header string `json:"header"` + Value string `json:"value"` + Action string `json:"action,omitempty"` + Describe string `json:"describe,omitempty"` +} + +// RefererACL defined a struct for referer ACL setting +type RefererACL struct { + BlackList []string `json:"blackList"` + WhiteList []string `json:"whiteList"` + AllowEmpty bool `json:"allowEmpty"` +} + +// IpACL defined a struct for black IP and white IP +type IpACL struct { + BlackList []string `json:"blackList"` + WhiteList []string `json:"whiteList"` +} + +// UaACL defined a struct for black UA and white UA +type UaACL struct { + BlackList []string `json:"blackList"` + WhiteList []string `json:"whiteList"` +} + +// ErrorPage defined a struct for redirecting to the custom page when error occur +type ErrorPage struct { + Code int `json:"code"` + RedirectCode int `json:"redirectCode,omitempty"` + Url string `json:"url"` +} + +// MediaCfg defined a struct for a media dragging config +type MediaCfg struct { + FileSuffix []string `json:"fileSuffix"` + StartArgName string `json:"startArgName,omitempty"` + EndArgName string `json:"endArgName,omitempty"` + DragMode string `json:"dragMode"` +} + +// MediaDragConf defined a struct for dragging configs about 'Mp4' and 'Flv' +type MediaDragConf struct { + Mp4 *MediaCfg `json:"mp4,omitempty"` + Flv *MediaCfg `json:"flv,omitempty"` +} + +// ClientIp defined a struct for how to get client IP +type ClientIp struct { + Enabled bool `json:"enabled"` + Name string `json:"name,omitempty"` +} + +// RetryOrigin defined a struct for how to retry origin servers +type RetryOrigin struct { + Codes []int `json:"codes"` +} + +// AccessLimit defined a struct for access restriction in one client +type AccessLimit struct { + Enabled bool `json:"enabled"` + Limit int `json:"limit,omitempty"` +} + +// CacheUrlArgs defined a struct for cache keys +type CacheUrlArgs struct { + CacheFullUrl bool `json:"cacheFullUrl"` + CacheUrlArgs []string `json:"cacheUrlArgs,omitempty"` +} + +// CorsCfg defined a struct for cors setting +type CorsCfg struct { + IsAllow bool + Origins []string +} + +// OriginProtocol defined a struct for originProtocol setting +type OriginProtocol struct { + Value string `json:"value"` +} + +// OriginTimeout defined a struct for originTimeout setting +type OriginTimeout struct { + ConnectTimeout int `json:"connectTimeout"` + LoadTimeout int `json:"loadTimeout"` +} + +// Compress defined a struct for page compression function +type Compress struct { + Allow string `json:"allow"` + Type string `json:"type,omitempty"` +} + +// Ipv6Dispatch defined a struct for ipv6 setting +type Ipv6Dispatch struct { + Enable bool `json:"enable"` +} + +// GetDomainConfig - get the configuration for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/2jwvyf39o +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *DomainConfig: the configuration about the specified domain +// - error: nil if success otherwise the specific error +func GetDomainConfig(cli bce.Client, domain string) (*DomainConfig, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + + config := &DomainConfig{} + + err := httpRequest(cli, "GET", urlPath, nil, nil, config) + if err != nil { + return nil, err + } + + return config, nil +} + +// SetDomainOrigin - set the origin setting for the new +// For details, please refer https://cloud.baidu.com/doc/CDN/s/xjxzi7729 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - origins: the origin servers +// - defaultHost: the default host +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetDomainOrigin(cli bce.Client, domain string, origins []OriginPeer, defaultHost string) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "origin": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + Origin []OriginPeer `json:"origin"` + DefaultHost string `json:"defaultHost"` + }{ + Origin: origins, + DefaultHost: defaultHost, + }, nil) + + return err +} + +// SetOriginProtocol - set the http protocol back to backend server. +// The valid "originProtocol" must be "http", "https" or "*", +// "http" means send the HTTP request to the backend server, +// "https" means send the HTTPS request to the backend server, +// "*" means send the request follow the client's requesting protocol. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7k9jdhhlm +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - originProtocol: the protocol used for back to the backend server +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetOriginProtocol(cli bce.Client, domain string, originProtocol string) error { + validOriginProtocols := map[string]bool{ + "http": true, + "https": false, + "*": true, + } + if _, ok := validOriginProtocols[originProtocol]; !ok { + return fmt.Errorf("invalid originProtocol \"%s\", "+ + "valid value must be \"http\", \"https\" or \"*\"", originProtocol) + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "originProtocol": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, map[string]interface{}{ + "originProtocol": map[string]string{ + "value": originProtocol, + }, + }, nil) + + return err +} + +// GetOriginProtocol - get the protocol used for back to the backend server. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/dk9jdoob4 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - string: the protocol used for back to the backend server, it's value must be "http", "https" or "*" +// - error: nil if success otherwise the specific error +func GetOriginProtocol(cli bce.Client, domain string) (string, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "originProtocol": "", + } + + respObj := &struct { + OriginProtocol struct { + Value string `json:"value"` + } `json:"originProtocol"` + }{} + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return "", err + } + if respObj.OriginProtocol.Value == "" { + return "http", nil + } + return respObj.OriginProtocol.Value, nil +} + +// SetDomainSeo - set SEO setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Jjxziuq4y +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - seoSwitch: the setting about SEO +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetDomainSeo(cli bce.Client, domain string, seoSwitch *SeoSwitch) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "seoSwitch": "", + } + + respObj := &struct { + Status string `json:"status"` + }{} + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + SeoSwitch *SeoSwitch `json:"seoSwitch"` + }{ + SeoSwitch: seoSwitch, + }, respObj) + if err != nil { + return err + } + + return nil +} + +// GetDomainSeo - retrieve the setting about SEO +// There are two types of data that the server responds to +// 1. `{"seoSwitch":[]}` indicates no setting about SEO +// 2. `{"seoSwitch":{"diretlyOrigin":"ON","pushRecord":"OFF"}}` indicates it had normal setting about SEO +// So the code need to handle the complex affairs +// +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Djxzjfz8f +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *SeoSwitch: the setting about SEO +// - error: nil if success otherwise the specific error +func GetDomainSeo(cli bce.Client, domain string) (*SeoSwitch, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "seoSwitch": "", + } + + var respMap map[string]interface{} + + err := httpRequest(cli, "GET", urlPath, params, nil, &respMap) + if err != nil { + return nil, err + } + + if _, ok := respMap["seoSwitch"]; ok { + if _, ok := respMap["seoSwitch"].([]interface{}); !ok { + respData, _ := json.Marshal(respMap) + respObj := &struct { + SeoSwitch *SeoSwitch `json:"seoSwitch"` + }{} + err = json.Unmarshal(respData, respObj) + if err != nil { + return nil, err + } + return respObj.SeoSwitch, nil + } + } + + return nil, nil +} + +// GetCacheTTL - get the current cached setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ljxzhl9bu +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - []CacheTTL: the cache setting list +// - error: nil if success otherwise the specific error +func GetCacheTTL(cli bce.Client, domain string) ([]CacheTTL, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cacheTTL": "", + } + + respObj := &struct { + CacheTTLs []CacheTTL `json:"cacheTTL"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.CacheTTLs, nil +} + +// SetCacheTTL - add some rules for cached setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/wjxzhgxnx +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - cacheTTLs: the cache setting list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetCacheTTL(cli bce.Client, domain string, cacheTTLs []CacheTTL) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cacheTTL": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + CacheTTLs []CacheTTL `json:"cacheTTL"` + }{ + CacheTTLs: cacheTTLs, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetRefererACL - set a rule for filter some HTTP request, blackList and whiteList only one can be set +// For details, please refer https://cloud.baidu.com/doc/CDN/s/yjxzhvf21 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - blackList: the forbidden host +// - whiteList: the available host +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetRefererACL(cli bce.Client, domain string, blackList []string, whiteList []string, isAllowEmpty bool) error { + if len(blackList) != 0 && len(whiteList) != 0 { + return errors.New("blackList and whiteList cannot exist at the same time") + } + + refererACLObj := &RefererACL{ + AllowEmpty: isAllowEmpty, + } + + if blackList != nil { + refererACLObj.BlackList = blackList + } else if whiteList != nil { + refererACLObj.WhiteList = whiteList + } else { + return errors.New("blackList and whiteList cannot be nil at the same time") + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "refererACL": "", + } + err := httpRequest(cli, "PUT", urlPath, params, &struct { + RefererACL *RefererACL `json:"refererACL"` + }{ + RefererACL: refererACLObj, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetRefererACL - get referer ACL setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ujzkotvtb +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *api.RefererACL: referer ACL setting +// - error: nil if success otherwise the specific error +func GetRefererACL(cli bce.Client, domain string) (*RefererACL, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "refererACL": "", + } + + refererACLObj := &RefererACL{} + + err := httpRequest(cli, "GET", urlPath, params, nil, &struct { + RefererACL *RefererACL `json:"refererACL"` + }{ + RefererACL: refererACLObj, + }) + if err != nil { + return nil, err + } + + return refererACLObj, nil +} + +// SetRefererACL - set a rule for filter some HTTP request, blackList and whiteList only one can be set +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jxzhwc4d +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - blackList: the forbidden ip +// - whiteList: the available ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetIpACL(cli bce.Client, domain string, blackList []string, whiteList []string) error { + if len(blackList) != 0 && len(whiteList) != 0 { + return errors.New("blackList and whiteList cannot exist at the same time") + } + + ipACLObj := &IpACL{} + + if blackList != nil { + ipACLObj.BlackList = blackList + } else if whiteList != nil { + ipACLObj.WhiteList = whiteList + } else { + return errors.New("blackList and whiteList cannot be nil at the same time") + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "ipACL": "", + } + err := httpRequest(cli, "PUT", urlPath, params, &struct { + IpACL *IpACL `json:"ipACL"` + }{ + IpACL: ipACLObj, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetIpACL - get black IP or white IP +// For details, please refer https://cloud.baidu.com/doc/CDN/s/jjzkp5ku7 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *api.IpACL: ip setting +// - error: nil if success otherwise the specific error +func GetIpACL(cli bce.Client, domain string) (*IpACL, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "ipACL": "", + } + + ipACLObj := &IpACL{} + err := httpRequest(cli, "GET", urlPath, params, nil, &struct { + IpACL *IpACL `json:"ipACL"` + }{ + IpACL: ipACLObj, + }) + + if err != nil { + return nil, err + } + + return ipACLObj, nil +} + +// SetUaACL - set a rule for filter the specified HTTP header named "User-Agent" +// For details, please refer https://cloud.baidu.com/doc/CDN/s/uk88i2a86 +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - blackList: the forbidden UA +// - whiteList: the available UA +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetUaACL(cli bce.Client, domain string, blackList []string, whiteList []string) error { + if len(blackList) != 0 && len(whiteList) != 0 { + return errors.New("blackList and whiteList cannot exist at the same time") + } + + uaAclObj := &UaACL{} + + if blackList != nil { + uaAclObj.BlackList = blackList + } else if whiteList != nil { + uaAclObj.WhiteList = whiteList + } else { + return errors.New("blackList and whiteList cannot be nil at the same time") + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "uaAcl": "", + } + err := httpRequest(cli, "PUT", urlPath, params, &struct { + UaACL *UaACL `json:"uaAcl"` + }{ + UaACL: uaAclObj, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetUaACL - get black UA or white UA +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ak88ix19h +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// +// RETURNS: +// - *api.UaACL: filter config for UA +// - error: nil if success otherwise the specific error +func GetUaACL(cli bce.Client, domain string) (*UaACL, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "uaAcl": "", + } + + uaACLObj := &UaACL{} + err := httpRequest(cli, "GET", urlPath, params, nil, &struct { + UaACL *UaACL `json:"uaAcl"` + }{ + UaACL: uaACLObj, + }) + + if err != nil { + return nil, err + } + + return uaACLObj, nil +} + +// Deprecated +// SetLimitRate - set limited speed +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - limitRate: the limited rate, "1024" means the transmittal speed is less than 1024 Byte/s +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetLimitRate(cli bce.Client, domain string, limitRate int) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "limitRate": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + LimitRate int `json:"limitRate"` + }{ + LimitRate: limitRate, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetTrafficLimit - set the traffic limitation for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ujxzi418e +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - trafficLimit: config of traffic limitation +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetTrafficLimit(cli bce.Client, domain string, trafficLimit *TrafficLimit) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "trafficLimit": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + TrafficLimit *TrafficLimit `json:"trafficLimit"` + }{ + TrafficLimit: trafficLimit, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetTrafficLimit - get the traffic limitation of the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7k4npdru0 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *TrafficLimit: config of traffic limitation +// - error: nil if success otherwise the specific error +func GetTrafficLimit(cli bce.Client, domain string) (*TrafficLimit, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "trafficLimit": "", + } + + respObj := &struct { + TrafficLimit TrafficLimit `json:"trafficLimit"` + }{} + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return &respObj.TrafficLimit, nil +} + +// SetDomainHttps - set a rule for speed HTTPS' request +// For details, please refer https://cloud.baidu.com/doc/CDN/s/rjy6v3tnr +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - httpsConfig: the rules about the HTTP configure +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetDomainHttps(cli bce.Client, domain string, httpsConfig *HTTPSConfig) error { + if httpsConfig.HttpRedirect && httpsConfig.HttpsRedirect { + return errors.New("httpRedirect and httpsRedirect can not be true at the same time") + } + if httpsConfig.HttpRedirect { + if httpsConfig.HttpRedirectCode != 0 && httpsConfig.HttpRedirectCode != 301 && httpsConfig.HttpRedirectCode != 302 { + return errors.New("invalid httpRedirectCode") + } + } + + if httpsConfig.HttpsRedirect { + if httpsConfig.HttpsRedirectCode != 0 && httpsConfig.HttpsRedirectCode != 301 && httpsConfig.HttpsRedirectCode != 302 { + return errors.New("invalid httpsRedirectCode") + } + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "https": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + HttpsConfig *HTTPSConfig `json:"https"` + }{ + HttpsConfig: httpsConfig, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetDomainHttps - get the setting about HTTPS +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *HTTPSConfig: the rules about the HTTP configure +// - error: nil if success otherwise the specific error +func GetDomainHttps(cli bce.Client, domain string) (*HTTPSConfig, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "https": "", + } + + respObj := &struct { + HttpsConfig *HTTPSConfig `json:"https"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.HttpsConfig, nil +} + +// SetOCSP - set "OCSP" for the specified domain, +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Pkf2c0ugn +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - enabled: true for "OCSP" opening otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetOCSP(cli bce.Client, domain string, enabled bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "ocsp": "", + } + + reqObj := map[string]interface{}{ + "ocsp": enabled, + } + err := httpRequest(cli, "PUT", urlPath, params, reqObj, nil) + if err != nil { + return err + } + + return nil +} + +// GetOCSP - get "OCSP" switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Xkhyjzcvd +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true for "OCSP" opening otherwise closed +// - error: nil if success otherwise the specific error +func GetOCSP(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "ocsp": "", + } + + respObj := &struct { + OfflineMode bool `json:"ocsp"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return false, err + } + + return respObj.OfflineMode, nil +} + +// SetDomainRequestAuth - set the authorized rules for requesting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/njxzi59g9 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - requestAuth: the rules about the auth +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetDomainRequestAuth(cli bce.Client, domain string, requestAuth *RequestAuth) error { + if requestAuth != nil && requestAuth.TimestampMetric != 0 { + return errors.New("TimestampMetric is deprecated, please use TimestampFormat as replacement") + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "requestAuth": "", + } + + var body interface{} + body = &struct { + RequestAuth *RequestAuth `json:"requestAuth"` + }{ + RequestAuth: requestAuth, + } + + err := httpRequest(cli, "PUT", urlPath, params, body, nil) + if err != nil { + return err + } + + return nil +} + +// SetFollowProtocol - set whether using the same protocol or not when back to the sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/9jxzi89k2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - isFollowProtocol: true in using the same protocol or not when back to the sourced server, false for other +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetFollowProtocol(cli bce.Client, domain string, isFollowProtocol bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "followProtocol": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + FollowProtocol bool `json:"followProtocol"` + }{ + FollowProtocol: isFollowProtocol, + }, nil) + if err != nil { + return err + } + + return nil +} + +// SetHttpHeader -set some HTTP headers which can be added or deleted when response form CDN edge node +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Jjxzil1sd +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - httpHeaders: the HTTP headers' setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetHttpHeader(cli bce.Client, domain string, httpHeaders []HttpHeader) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "httpHeader": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + HttpHeaders []HttpHeader `json:"httpHeader"` + }{ + HttpHeaders: httpHeaders, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetHttpHeader - get the HTTP headers' setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/6jxzip3wn +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - []HttpHeader: the HTTP headers in setting +func GetHttpHeader(cli bce.Client, domain string) ([]HttpHeader, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "httpHeader": "", + } + + respObj := &struct { + HttpHeaders []HttpHeader `json:"httpHeader"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.HttpHeaders, nil +} + +// SetErrorPage - set the page that redirected to when error occurred +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ejy6vc4yb +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - errorPages: the custom pages' setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetErrorPage(cli bce.Client, domain string, errorPages []ErrorPage) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "errorPage": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + ErrorPage []ErrorPage `json:"errorPage"` + }{ + ErrorPage: errorPages, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetErrorPage - get the custom pages' setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qjy6vfk2u +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - []ErrorPage: the pages' setting +// - error: nil if success otherwise the specific error +func GetErrorPage(cli bce.Client, domain string) ([]ErrorPage, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "errorPage": "", + } + + respObj := &struct { + ErrorPage []ErrorPage `json:"errorPage"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.ErrorPage, nil +} + +// SetCacheShared - set sharing cache with the other domain. +// For example, 1.test.com shared cache with 2.test.com. +// First, we query http://2.test.com/index.html and got missed. +// Secondly, we query http://1.test.com/index.html and got hit +// because of the CacheShared setting before. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/0kf272ds7 +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - cacheSharedConfig: enabled sets true for shared with the specified domain, otherwise no shared. +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetCacheShared(cli bce.Client, domain string, cacheSharedConfig *CacheShared) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cacheShare": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, map[string]interface{}{ + "cacheShare": cacheSharedConfig, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetCacheShared - get shared cache setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Mjy6vo9z2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *CacheShared: shared cache setting +// - error: nil if success otherwise the specific error +func GetCacheShared(cli bce.Client, domain string) (*CacheShared, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cacheShare": "", + } + + respObj := &struct { + CacheShared CacheShared `json:"cacheShare"` + }{} + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return &respObj.CacheShared, nil +} + +// SetMediaDrag - set the media setting about mp4 and flv +// For details, please refer https://cloud.baidu.com/doc/CDN/s/4jy6v6xk3 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - mediaDragConf: media setting about mp4 and flv +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetMediaDrag(cli bce.Client, domain string, mediaDragConf *MediaDragConf) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "mediaDrag": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + MediaDragConf *MediaDragConf `json:"mediaDragConf"` + }{ + MediaDragConf: mediaDragConf, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetMediaDrag - get the media setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ojy6v9q8f +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *MediaDragConf: the media setting about mp4 and flv +// - error: nil if success otherwise the specific error +func GetMediaDrag(cli bce.Client, domain string) (*MediaDragConf, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "mediaDrag": "", + } + + respObj := &struct { + MediaDragConf *MediaDragConf `json:"mediaDragConf"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.MediaDragConf, nil +} + +// SetFileTrim - trim the text file or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Xjy6vimct +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - fileTrim: true means trimming the text file, false means do nothing +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetFileTrim(cli bce.Client, domain string, fileTrim bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "fileTrim": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + FileTrim bool `json:"fileTrim"` + }{ + FileTrim: fileTrim, + }, nil) + if err != nil { + return err + } + + return nil +} + +// GetFileTrim - get the trim setting about text file +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ujy6vjxnl +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true means trimming the text file, false means do nothing +// - error: nil if success otherwise the specific error +func GetFileTrim(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "fileTrim": "", + } + + respObj := &struct { + FileTrim bool `json:"fileTrim"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return false, err + } + + return respObj.FileTrim, nil +} + +// SetIPv6 - open/close IPv6 +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qkggncsxp +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - enabled: true for setting IPv6 switch on otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetIPv6(cli bce.Client, domain string, enabled bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "ipv6Dispatch": "", + } + + reqObj := map[string]interface{}{ + "ipv6Dispatch": map[string]interface{}{ + "enable": enabled, + }, + } + err := httpRequest(cli, "PUT", urlPath, params, reqObj, nil) + if err != nil { + return err + } + + return nil +} + +// GetIPv6 - get IPv6 switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ykggnobxd +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true for setting IPv6 switch on otherwise closed +// - error: nil if success otherwise the specific error +func GetIPv6(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "ipv6Dispatch": "", + } + + respObj := &struct { + Ipv6Dispatch struct { + Enabled bool `json:"enable"` + } `json:"ipv6Dispatch"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return false, err + } + + return respObj.Ipv6Dispatch.Enabled, nil +} + +// SetQUIC - open or close QUIC. open QUIC require enabled HTTPS first +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Qkggmoz7p +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - enabled: true for QUIC opening otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetQUIC(cli bce.Client, domain string, enabled bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "quic": "", + } + + reqObj := map[string]interface{}{ + "quic": enabled, + } + err := httpRequest(cli, "PUT", urlPath, params, reqObj, nil) + if err != nil { + return err + } + + return nil +} + +// GetQUIC - get QUIC switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/pkggn6l1f +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true for QUIC opening otherwise closed +// - error: nil if success otherwise the specific error +func GetQUIC(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "quic": "", + } + + respObj := &struct { + QUIC bool `json:"quic"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return false, err + } + + return respObj.QUIC, nil +} + +// SetOfflineMode - set "offlineMode" for the specified domain, +// setting true means also response old cached object when got origin server error +// instead of response error to client directly. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/xkhopuj48 +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - enabled: true for offlineMode opening otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetOfflineMode(cli bce.Client, domain string, enabled bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "offlineMode": "", + } + + reqObj := map[string]interface{}{ + "offlineMode": enabled, + } + err := httpRequest(cli, "PUT", urlPath, params, reqObj, nil) + if err != nil { + return err + } + + return nil +} + +// GetOfflineMode - get "offlineMode" switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/tkhopvlkj +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true for offlineMode opening otherwise closed +// - error: nil if success otherwise the specific error +func GetOfflineMode(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "offlineMode": "", + } + + respObj := &struct { + OfflineMode bool `json:"offlineMode"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return false, err + } + + return respObj.OfflineMode, nil +} + +// SetMobileAccess - distinguish the client or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Mjy6vmv6g +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - distinguishClient: true means distinguishing the client, false means not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetMobileAccess(cli bce.Client, domain string, distinguishClient bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "mobileAccess": "", + } + + type mobileAccess struct { + DistinguishClient bool `json:"distinguishClient"` + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + MobileAccess *mobileAccess `json:"mobileAccess"` + }{ + MobileAccess: &mobileAccess{ + DistinguishClient: distinguishClient, + }, + }, nil) + + return err +} + +// GetMobileAccess - get the setting about distinguishing the client or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Mjy6vo9z2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true means distinguishing the client, false means not +// - error: nil if success otherwise the specific error +func GetMobileAccess(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "mobileAccess": "", + } + + respObj := &struct { + MobileAccess *struct { + DistinguishClient bool `json:"distinguishClient"` + } `json:"mobileAccess"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return false, err + } + + return respObj.MobileAccess.DistinguishClient, nil +} + +// SetClientIp - set the specified HTTP header for the origin server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Kjy6umyrm +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - clientIp: header setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetClientIp(cli bce.Client, domain string, clientIp *ClientIp) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "clientIp": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + ClientIp *ClientIp `json:"clientIp"` + }{ + ClientIp: clientIp, + }, nil) + + return err +} + +// GetClientIp - get the setting about getting client IP +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jy6urcq5 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *ClientIp: the HTTP header setting for origin server to get client IP +// - error: nil if success otherwise the specific error +func GetClientIp(cli bce.Client, domain string) (*ClientIp, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "clientIp": "", + } + + respObj := &struct { + ClientIp *ClientIp `json:"clientIp"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.ClientIp, nil +} + +// SetRetryOrigin - set the policy for retry origin servers if got failed +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ukhopl3bq +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - retryOrigin: retry policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetRetryOrigin(cli bce.Client, domain string, retryOrigin *RetryOrigin) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "retryOrigin": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + RetryOrigin *RetryOrigin `json:"retryOrigin"` + }{ + RetryOrigin: retryOrigin, + }, nil) + + return err +} + +// GetRetryOrigin - get the policy for retry origin servers +// For details, please refer https://cloud.baidu.com/doc/CDN/s/bkhoppbhd +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *RetryOrigin: policy of retry origin servers +// - error: nil if success otherwise the specific error +func GetRetryOrigin(cli bce.Client, domain string) (*RetryOrigin, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "retryOrigin": "", + } + + respObj := &struct { + RetryOrigin *RetryOrigin `json:"retryOrigin"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.RetryOrigin, nil +} + +// SetAccessLimit - set the qps for on one client +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Kjy6v02wt +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - accessLimit: the access setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetAccessLimit(cli bce.Client, domain string, accessLimit *AccessLimit) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "accessLimit": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + AccessLimit *AccessLimit `json:"accessLimit"` + }{ + AccessLimit: accessLimit, + }, nil) + + return err +} + +// GetAccessLimit - get the qps setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/rjy6v3tnr +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *AccessLimit: the access setting +// - error: nil if success otherwise the specific error +func GetAccessLimit(cli bce.Client, domain string) (*AccessLimit, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "accessLimit": "", + } + + respObj := &struct { + AccessLimit *AccessLimit `json:"accessLimit"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.AccessLimit, nil +} + +// SetCacheUrlArgs - tell the CDN system cache the url's params or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/vjxzho0kx +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - cacheFullUrl: whether cache the full url or not, full url means include params, also some extra params can be avoided +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetCacheUrlArgs(cli bce.Client, domain string, cacheFullUrl *CacheUrlArgs) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cacheFullUrl": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, cacheFullUrl, nil) + + return err +} + +// GetCacheUrlArgs - get the cached rules +// For details, please refer https://cloud.baidu.com/doc/CDN/s/sjxzhsb6h +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *CacheUrlArgs: the details about cached rules +// - error: nil if success otherwise the specific error +func GetCacheUrlArgs(cli bce.Client, domain string) (*CacheUrlArgs, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cacheFullUrl": "", + } + + respObj := &CacheUrlArgs{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + if err != nil { + return nil, err + } + + return respObj, nil +} + +// SetTlsVersions - set some TLS versions that you want +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - tlsVersions: TLS version settings +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetTlsVersions(cli bce.Client, domain string, tlsVersions []string) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "tlsVersions": "", + } + + reqData := &struct { + Data []string `json:"data"` + }{ + Data: tlsVersions, + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + TlsVersions interface{} `json:"tlsVersions"` + }{ + TlsVersions: reqData, + }, nil) + + return err +} + +// SetCors - set about Cross-origin resource sharing +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Rjxzi1cfs +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - isAllow: true means allow Cors, false means not allow +// - originList: the origin setting, it's invalid when isAllow is false +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetCors(cli bce.Client, domain string, isAllow bool, originList []string) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cors": "", + } + + allow := "off" + var origins []string + origins = []string{} + + if isAllow { + allow = "on" + origins = originList + } + + reqData := &struct { + Allow string `json:"allow"` + OriginList []string `json:"originList"` + }{ + Allow: allow, + OriginList: origins, + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + Cors interface{} `json:"cors"` + }{ + Cors: reqData, + }, nil) + + return err +} + +// GetCors - get the Cors setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/tjxzi2d7t +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - *CorsCfg: the Cors setting +// - error: nil if success otherwise the specific error +func GetCors(cli bce.Client, domain string) (*CorsCfg, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "cors": "", + } + + respObj := &struct { + Allow string `json:"allow"` + OriginList []string `json:"originList,omitempty"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, &struct { + Cors interface{} `json:"cors"` + }{ + Cors: respObj, + }) + + if err != nil { + return nil, err + } + + corsCfg := &CorsCfg{ + IsAllow: false, + Origins: respObj.OriginList, + } + + if strings.ToUpper(respObj.Allow) == "ON" { + corsCfg.IsAllow = true + } + + return corsCfg, nil +} + +// SetRangeSwitch - set the range setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Fjxziabst +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - enabled: true means enable range cached, false means disable range cached +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetRangeSwitch(cli bce.Client, domain string, enabled bool) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "rangeSwitch": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + RangeSwitch bool `json:"rangeSwitch"` + }{ + RangeSwitch: enabled, + }, nil) + + return err +} + +// GetRangeSwitch - get the range setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jxzid6o9 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - bool: true means enable range cached, false means disable range cached +// - error: nil if success otherwise the specific error +func GetRangeSwitch(cli bce.Client, domain string) (bool, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "rangeSwitch": "", + } + + respObj := &struct { + RangeSwitch string `json:"rangeSwitch"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, respObj) + + if err != nil { + return false, err + } + + enabled := false + if strings.ToUpper(respObj.RangeSwitch) == "ON" { + enabled = true + } + + return enabled, nil +} + +// SetContentEncoding - set Content-Encoding +// For details, please refer https://cloud.baidu.com/doc/CDN/s/0jyqyahsb +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - enabled: true means using the specified encoding algorithm indicated by "encodingType" in transferring, +// false means disable encoding +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetContentEncoding(cli bce.Client, domain string, enabled bool, encodingType string) error { + if enabled && encodingType != "gzip" && encodingType != "br" && encodingType != "all" { + errMsg := fmt.Sprintf("invalid encoding type \"%s\" for setting Content-Encoding,"+ + " it must in \"gzip\", \"br\" and \"all\"", encodingType) + return errors.New(errMsg) + } + + if !enabled { + encodingType = "" + } + + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "compress": "", + } + + respObj := &struct { + Allow bool `json:"allow"` + Type string `json:"type,omitempty"` + }{ + Allow: enabled, + Type: encodingType, + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + ContentEncoding interface{} `json:"compress"` + }{ + ContentEncoding: respObj, + }, nil) + + return err +} + +// GetContentEncoding - get the setting about Content-Encoding +// For details, please refer https://cloud.baidu.com/doc/CDN/s/bjyqycw8g +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - string: the encoding algorithm for transferring, empty means disable encoding in transferring +// - error: nil if success otherwise the specific error +func GetContentEncoding(cli bce.Client, domain string) (string, error) { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "compress": "", + } + + respObj := &struct { + Allow string `json:"allow"` + Type string `json:"type,omitempty"` + }{} + + err := httpRequest(cli, "GET", urlPath, params, nil, &struct { + ContentEncoding interface{} `json:"compress"` + }{ + ContentEncoding: respObj, + }) + + if err != nil { + return "", err + } + + contentEncoding := respObj.Type + if respObj.Allow == "off" { + contentEncoding = "" + } + + return contentEncoding, nil +} diff --git a/bce-sdk-go/services/cdn/api/dsa.go b/bce-sdk-go/services/cdn/api/dsa.go new file mode 100644 index 0000000..bee1b07 --- /dev/null +++ b/bce-sdk-go/services/cdn/api/dsa.go @@ -0,0 +1,115 @@ +package api + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// DSARule defined a struct for DSA urls +type DSARule struct { + Type string `json:"type"` + Value string `json:"value"` +} + +// DSADomain defined a struct about the specified domain's DSA setting +type DSADomain struct { + Domain string `json:"domain"` + Rules []DSARule `json:"rules"` + ModifyTime string `json:"modifyTime"` + Comment string `json:"comment"` +} + +// DSAConfig defined a struct for DSA configuration +type DSAConfig struct { + Enabled bool `json:"enabled"` + Rules []DSARule `json:"rules"` + Comment string `json:"comment,omitempty"` +} + +func setDsa(cli bce.Client, action string) error { + err := httpRequest(cli, "PUT", "/v2/dsa", nil, &struct { + Action string `json:"action"` + }{ + Action: action, + }, nil) + if err != nil { + return err + } + + return nil +} + +// EnableDsa - enable DSA +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7jwvyf1h5 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - error: nil if success otherwise the specific error +func EnableDsa(cli bce.Client) error { + return setDsa(cli, "enable") +} + +// DisableDsa - disable DSA +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7jwvyf1h5 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - error: nil if success otherwise the specific error +func DisableDsa(cli bce.Client) error { + return setDsa(cli, "disable") +} + +// ListDsaDomains - retrieve all the domains in DSA service +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf1sq +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - []DSADomain: the details about DSA domains +// - error: nil if success otherwise the specific error +func ListDsaDomains(cli bce.Client) ([]DSADomain, error) { + respObj := &struct { + Domains []DSADomain `json:"domains"` + }{} + + err := httpRequest(cli, "GET", "/v2/dsa/domain", nil, nil, respObj) + if err != nil { + return nil, err + } + + return respObj.Domains, nil +} + +// SetDsaConfig - set the DSA configuration +// For details, please refer https://cloud.baidu.com/doc/CDN/s/0jwvyf26d +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - dsaConfig: the specified configuration for the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SetDsaConfig(cli bce.Client, domain string, dsaConfig *DSAConfig) error { + urlPath := fmt.Sprintf("/v2/domain/%s/config", domain) + params := map[string]string{ + "dsa": "", + } + + err := httpRequest(cli, "PUT", urlPath, params, &struct { + Dsa *DSAConfig `json:"dsa"` + }{ + Dsa: dsaConfig, + }, nil) + if err != nil { + return err + } + + return nil +} diff --git a/bce-sdk-go/services/cdn/api/log.go b/bce-sdk-go/services/cdn/api/log.go new file mode 100644 index 0000000..0555c2e --- /dev/null +++ b/bce-sdk-go/services/cdn/api/log.go @@ -0,0 +1,169 @@ +package api + +import ( + "errors" + "fmt" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/util" +) + +type LogBase struct { + Domain string `json:"domain"` + Url string `json:"url"` + Name string `json:"name"` + Size int64 `json:"size"` +} + +// TimeInterval defined a struct contains the started time and the end time +type TimeInterval struct { + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` +} + +// LogEntry defined a struct for log information +type LogEntry struct { + *LogBase + *TimeInterval +} + +// LogQueryData defined a struct for query conditions +type LogQueryData struct { + TimeInterval + Type int `json:"type,omitempty"` + Domains []string `json:"domains,omitempty"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` +} + +// GetDomainLog -get one domain's log urls +// For details, please refer https://cloud.baidu.com/doc/CDN/s/cjwvyf0r9 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - timeInterval: the specified time interval +// +// RETURNS: +// - []LogEntry: the log detail list +// - error: nil if success otherwise the specific error +func GetDomainLog(cli bce.Client, domain string, timeInterval TimeInterval) ([]LogEntry, error) { + if err := checkTimeInterval(timeInterval, 14*24*60*60); err != nil { + return nil, err + } + + urlPath := fmt.Sprintf("/v2/log/%s/log", domain) + params := map[string]string{} + params["startTime"] = timeInterval.StartTime + params["endTime"] = timeInterval.EndTime + + respObj := &struct { + Logs []LogEntry `json:"logs"` + }{} + + if err := httpRequest(cli, "GET", urlPath, params, nil, respObj); err != nil { + return nil, err + } + + for i, _ := range respObj.Logs { + respObj.Logs[i].Domain = domain + } + + return respObj.Logs, nil +} + +// GetMultiDomainLog - get many domains' log urls +// For details, please refer https://cloud.baidu.com/doc/CDN/API.html#.49.B0.4F.9D.D3.1A.FB.6F.59.A6.8A.B6.08.E9.BC.EF +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryData: the querying conditions +// - error: nil if success otherwise the specific error +func GetMultiDomainLog(cli bce.Client, queryData *LogQueryData) ([]LogEntry, error) { + if queryData == nil { + return nil, errors.New("queryData could not be nil") + } + if err := checkTimeInterval(queryData.TimeInterval, 180*24*60*60); err != nil { + return nil, err + } + + if queryData.PageNo == 0 { + queryData.PageNo = 1 + } + if queryData.PageNo < 0 { + return nil, errors.New("invalid queryData.PageNo, it should be larger than 0") + } + + if queryData.PageSize < 0 { + return nil, errors.New("invalid queryData.PageSize, it should be larger than 0") + } + + respObj := &struct { + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + TotalCount int `json:"totalCount"` + Urls []struct { + *LogBase + LogTimeBegin string `json:"logTimeBegin"` + LogTimeEnd string `json:"logTimeEnd"` + } `json:"urls"` + }{} + + err := httpRequest(cli, "POST", "/v2/log/list", nil, queryData, respObj) + if err != nil { + return nil, err + } + + result := make([]LogEntry, 0, len(respObj.Urls)) + + for i, _ := range respObj.Urls { + log := LogEntry{ + LogBase: respObj.Urls[i].LogBase, + TimeInterval: &TimeInterval{ + StartTime: respObj.Urls[i].LogTimeBegin, + EndTime: respObj.Urls[i].LogTimeEnd, + }, + } + result = append(result, log) + } + + return result, nil +} + +func checkTimeInterval(timeInterval TimeInterval, maxTimeRange int64) error { + if timeInterval.StartTime == "" { + return errors.New("lack of startTime") + } + + if timeInterval.EndTime == "" { + return errors.New("lack of endTime") + } + + st, err := util.ParseISO8601Date(timeInterval.StartTime) + if err != nil { + return errors.New(fmt.Sprintf("invalid startTime, %s", err.Error())) + } + startTs := st.Unix() + + et, err := util.ParseISO8601Date(timeInterval.EndTime) + if err != nil { + return errors.New(fmt.Sprintf("invalid endTime, %s", err.Error())) + } + endTs := et.Unix() + + if startTs > endTs { + return errors.New(fmt.Sprintf("startTime shouble be less than endTime")) + } + + curTs := time.Now().Unix() + if curTs-startTs > maxTimeRange { + return errors.New(fmt.Sprintf("only the first %d seconds of log files can be downloaded, please reset startTime", maxTimeRange)) + } + + if startTs > curTs { + return errors.New("startTime could not larger than current time") + } + + return nil +} diff --git a/bce-sdk-go/services/cdn/api/stat.go b/bce-sdk-go/services/cdn/api/stat.go new file mode 100644 index 0000000..b59049f --- /dev/null +++ b/bce-sdk-go/services/cdn/api/stat.go @@ -0,0 +1,767 @@ +package api + +import ( + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + statisticsObjectKey = "/v2/stat/query" + statisticsBillingKey = "/v2/billing" +) + +// QueryCondition defined a struct for query condition +type QueryCondition struct { + EndTime string `json:"endTime,omitempty"` + StartTime string `json:"startTime,omitempty"` + Period int `json:"period,omitempty"` + KeyType int `json:"key_type"` + Key []string `json:"key,omitempty"` + GroupBy string `json:"groupBy,omitempty"` +} + +type DetailBase struct { + Timestamp string `json:"timestamp"` + Key string `json:"key,omitempty"` +} + +// NetSite defined a struct for the ISP's information +type NetSite struct { + Location string `json:"location"` + Isp string `json:"isp"` +} + +type AvgSpeedRegionData struct { + *NetSite + AvgSpeed int64 `json:"avgspeed"` +} + +type AvgSpeedDetail struct { + *DetailBase + AvgSpeed int64 `json:"avgspeed"` +} + +type AvgSpeedRegionDetail struct { + *DetailBase + Distribution []AvgSpeedRegionData `json:"distribution"` +} + +type PvDetail struct { + *DetailBase + Pv int64 `json:"pv"` + Qps int64 `json:"qps"` +} + +type PVRegionData struct { + *NetSite + Pv int64 `json:"pv"` + Qps int64 `json:"qps"` +} + +type PvRegionDetail struct { + *DetailBase + Distribution []PVRegionData `json:"distribution"` +} + +type UvDetail struct { + *DetailBase + Uv int64 `json:"uv"` +} + +type FlowDetail struct { + *DetailBase + Flow float64 `json:"flow"` + Bps int64 `json:"bps"` +} + +type FlowRegionData struct { + *NetSite + Flow float64 `json:"flow"` + Bps int64 `json:"bps"` +} + +type FlowRegionDetail struct { + *DetailBase + Distribution []FlowRegionData `json:"distribution"` +} + +type HitDetail struct { + *DetailBase + HitRate float64 `json:"hitrate"` +} + +type KvCounter struct { + Name int64 `json:"name"` + Count int64 `json:"count"` +} + +type HttpCodeDetail struct { + *DetailBase + Counters []KvCounter `json:"counters"` +} + +type HttpCodeRegionData struct { + *NetSite + Counters []KvCounter `json:"counters"` +} + +type HttpCodeRegionDetail struct { + *DetailBase + Distribution []HttpCodeRegionData `json:"distribution"` +} + +type TopNCounter struct { + Name string `json:"name"` + Pv int64 `json:"pv"` + Flow float64 `json:"flow"` +} + +type TopNDetail struct { + *DetailBase + TotalPv int64 `json:"total_pv"` + TotalFlow float64 `json:"total_flow"` + Counters []TopNCounter `json:"counters"` +} + +type ErrorKvCounter struct { + Code string `json:"code"` + Counters []KvCounter `json:"counters"` +} + +type ErrorDetail struct { + *DetailBase + Counters []ErrorKvCounter `json:"counters"` +} + +// GetAvgSpeed - get the average speed +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E5%B9%B3%E5%9D%87%E9%80%9F%E7%8E%87 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []AvgSpeedDetail: the detail list about the average speed +// - error: nil if success otherwise the specific error +func GetAvgSpeed(cli bce.Client, queryCondition *QueryCondition) ([]AvgSpeedDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []AvgSpeedDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: "avg_speed", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetAvgSpeed - get the average speed filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83%E6%9F%A5%E8%AF%A2%E5%B9%B3%E5%9D%87%E9%80%9F%E7%8E%87 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []AvgSpeedRegionDetail: the detail list about the average speed +// - error: nil if success otherwise the specific error +func GetAvgSpeedByRegion(cli bce.Client, queryCondition *QueryCondition, prov string, isp string) ([]AvgSpeedRegionDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []AvgSpeedRegionDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Prov string `json:"prov,omitempty"` + Isp string `json:"isp,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Prov: prov, + Isp: isp, + Metric: "avg_speed_region", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetPv - get the PV data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#pvqps%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - level: the node level, the available values are "edge", "internal" and "all" +// +// RETURNS: +// - []PvDetail: the detail list about page view +// - error: nil if success otherwise the specific error +func GetPv(cli bce.Client, queryCondition *QueryCondition, level string) ([]PvDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []PvDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Level string `json:"level,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Level: level, + Metric: "pv", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetSrcPv - get the PV data in back to the sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%9B%9E%E6%BA%90pvqps%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []PvDetail: the detail list about page view +// - error: nil if success otherwise the specific error +func GetSrcPv(cli bce.Client, queryCondition *QueryCondition) ([]PvDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []PvDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: "pv_src", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetAvgPvByRegion - get the PV data filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2pvqps%E5%88%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []PvRegionDetail: the detail list about page view +// - error: nil if success otherwise the specific error +func GetPvByRegion(cli bce.Client, queryCondition *QueryCondition, prov string, isp string) ([]PvRegionDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []PvRegionDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Prov string `json:"prov,omitempty"` + Isp string `json:"isp,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Prov: prov, + Isp: isp, + Metric: "pv_region", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetUv - get the UV data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#uv%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []UvDetail: the detail list about unique visitor +// - error: nil if success otherwise the specific error +func GetUv(cli bce.Client, queryCondition *QueryCondition) ([]UvDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []UvDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Level string `json:"level,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: "uv", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetFlow - get the flow data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%B5%81%E9%87%8F%E3%80%81%E5%B8%A6%E5%AE%BD +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []FlowDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func GetFlow(cli bce.Client, queryCondition *QueryCondition, level string) ([]FlowDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []FlowDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Level string `json:"level,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Level: level, + Metric: "flow", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetFlowByProtocol - get the flow data filter by protocol +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%B5%81%E9%87%8F%E3%80%81%E5%B8%A6%E5%AE%BD%E5%88%86%E5%8D%8F%E8%AE%AE +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - protocol: the specified HTTP protocol, like "http" or "https", "all" means both "http" and "https" +// +// RETURNS: +// - []FlowDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func GetFlowByProtocol(cli bce.Client, queryCondition *QueryCondition, protocol string) ([]FlowDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []FlowDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Protocol string `json:"protocol,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Protocol: protocol, + Metric: "flow_protocol", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetFlowByRegion - get the flow data filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%B5%81%E9%87%8F%E3%80%81%E5%B8%A6%E5%AE%BD%EF%BC%88%E5%88%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83%EF%BC%89 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []FlowRegionDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func GetFlowByRegion(cli bce.Client, queryCondition *QueryCondition, prov string, isp string) ([]FlowRegionDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []FlowRegionDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Prov string `json:"prov,omitempty"` + Isp string `json:"isp,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Prov: prov, + Isp: isp, + Metric: "flow_region", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetSrcFlow - get the flow data in backed to sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E5%9B%9E%E6%BA%90%E6%B5%81%E9%87%8F%E3%80%81%E5%9B%9E%E6%BA%90%E5%B8%A6%E5%AE%BD +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []FlowDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func GetSrcFlow(cli bce.Client, queryCondition *QueryCondition) ([]FlowDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []FlowDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Protocol string `json:"protocol,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: "src_flow", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +func getHit(cli bce.Client, queryCondition *QueryCondition, metric string) ([]HitDetail, error) { + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []HitDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Protocol string `json:"protocol,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: metric, + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetRealHit - get the detail about byte hit rate +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%AD%97%E8%8A%82%E5%91%BD%E4%B8%AD%E7%8E%87%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HitDetail: the detail list about byte rate +// - error: nil if success otherwise the specific error +func GetRealHit(cli bce.Client, queryCondition *QueryCondition) ([]HitDetail, error) { + return getHit(cli, queryCondition, "real_hit") +} + +// GetPvHit - get the detail about PV hit rate +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E8%AF%B7%E6%B1%82%E5%91%BD%E4%B8%AD%E7%8E%87%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HitDetail: the detail list about pv rate +// - error: nil if success otherwise the specific error +func GetPvHit(cli bce.Client, queryCondition *QueryCondition) ([]HitDetail, error) { + return getHit(cli, queryCondition, "pv_hit") +} + +func getHttpCode(cli bce.Client, queryCondition *QueryCondition, metric string) ([]HttpCodeDetail, error) { + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []HttpCodeDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Protocol string `json:"protocol,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: metric, + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetHttpCode - get the http code's statistics +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E7%8A%B6%E6%80%81%E7%A0%81%E7%BB%9F%E8%AE%A1%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HttpCodeDetail: the detail list about http code +// - error: nil if success otherwise the specific error +func GetHttpCode(cli bce.Client, queryCondition *QueryCondition) ([]HttpCodeDetail, error) { + return getHttpCode(cli, queryCondition, "httpcode") +} + +// GetSrcHttpCode - get the http code's statistics in backed to sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%9B%9E%E6%BA%90%E7%8A%B6%E6%80%81%E7%A0%81%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HttpCodeDetail: the detail list about http code +// - error: nil if success otherwise the specific error +func GetSrcHttpCode(cli bce.Client, queryCondition *QueryCondition) ([]HttpCodeDetail, error) { + return getHttpCode(cli, queryCondition, "src_httpcode") +} + +// GetHttpCodeByRegion - get the http code's statistics filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E7%8A%B6%E6%80%81%E7%A0%81%E7%BB%9F%E8%AE%A1%E6%9F%A5%E8%AF%A2%EF%BC%88%E5%88%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83%EF%BC%89 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []HttpCodeRegionDetail: the detail list about http code +// - error: nil if success otherwise the specific error +func GetHttpCodeByRegion(cli bce.Client, queryCondition *QueryCondition, prov string, isp string) ([]HttpCodeRegionDetail, error) { + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []HttpCodeRegionDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Prov string `json:"prov,omitempty"` + Isp string `json:"isp,omitempty"` + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Prov: prov, + Isp: isp, + Metric: "httpcode_region", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +func getTopN(cli bce.Client, queryCondition *QueryCondition, httpCode string, metric string) ([]TopNDetail, error) { + extra, err := strconv.ParseInt(httpCode, 10, 64) + if err != nil { + extra = 0 + } + + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []TopNDetail `json:"details"` + }{} + + err = httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Protocol string `json:"protocol,omitempty"` + Metric string `json:"metric"` + Extra int64 `json:"extra,omitempty"` + }{ + QueryCondition: queryCondition, + Metric: metric, + Extra: extra, + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetTopNUrls - get the top N urls that requested +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#topn-urls +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - httpCode: the specified HTTP code, like "200" +// +// RETURNS: +// - []TopNDetail: the top N urls' detail +// - error: nil if success otherwise the specific error +func GetTopNUrls(cli bce.Client, queryCondition *QueryCondition, httpCode string) ([]TopNDetail, error) { + return getTopN(cli, queryCondition, httpCode, "top_urls") +} + +// GetTopNReferers - get the top N urls that brought by requested +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#topn-referers +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - httpCode: the specified HTTP code, like "200" +// +// RETURNS: +// - []TopNDetail: the top N referer urls' detail +// - error: nil if success otherwise the specific error +func GetTopNReferers(cli bce.Client, queryCondition *QueryCondition, httpCode string) ([]TopNDetail, error) { + return getTopN(cli, queryCondition, httpCode, "top_referers") +} + +// GetTopNDomains - get the top N domains that requested +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#topn-domains +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// - httpCode: the specified HTTP code, like "200" +// +// RETURNS: +// - []TopNDetail: the top N domains' detail +// - error: nil if success otherwise the specific error +func GetTopNDomains(cli bce.Client, queryCondition *QueryCondition, httpCode string) ([]TopNDetail, error) { + return getTopN(cli, queryCondition, httpCode, "top_domains") +} + +// GetError - get the error code's data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#cdn%E9%94%99%E8%AF%AF%E7%A0%81%E5%88%86%E7%B1%BB%E7%BB%9F%E8%AE%A1%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - queryCondition: the querying conditions +// +// RETURNS: +// - []ErrorDetail: the top N error details +// - error: nil if success otherwise the specific error +func GetError(cli bce.Client, queryCondition *QueryCondition) ([]ErrorDetail, error) { + respObj := &struct { + Status string `json:"status"` + Count int64 `json:"count"` + Details []ErrorDetail `json:"details"` + }{} + + err := httpRequest(cli, "POST", statisticsObjectKey, nil, &struct { + *QueryCondition + Metric string `json:"metric"` + }{ + QueryCondition: queryCondition, + Metric: "error", + }, respObj) + if err != nil { + return nil, err + } + + return respObj.Details, nil +} + +// GetPeak95Bandwidth - get peak 95 bandwidth for the specified tags or domains. +// For details, pleader refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%9C%8895%E5%B3%B0%E5%80%BC%E5%B8%A6%E5%AE%BD +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - startTime: start time which in `YYYY-mm-ddTHH:ii:ssZ` style +// - endTime: end time which in `YYYY-mm-ddTHH:ii:ssZ` style +// - domains: a list of domains, only one of `tags` and `domains` can contains item +// - tags: a list of tag names, only one of `tags` and `domains` can contains item +// +// RETURNS: +// - string: the peak95 time which in `YYYY-mm-ddTHH:ii:ssZ` style +// - int64: peak95 bandwidth +// - error: nil if success otherwise the specific error +func GetPeak95Bandwidth(cli bce.Client, startTime, endTime string, domains, tags []string) (peak95Time string, peak95Band int64, err error) { + respObj := &struct { + Details struct { + Bandwidth int64 `json:"bill_band"` + Time string `json:"bill_time"` + } `json:"billing_details"` + }{} + + tagOrDomains, withTag := domains, false + if len(tags) != 0 { + tagOrDomains, withTag = tags, true + } + err = httpRequest(cli, "POST", statisticsBillingKey, nil, map[string]interface{}{ + "domains": strings.Join(tagOrDomains, ","), + "type": "peak95", + "withTag": withTag, + "byTime": true, + "startTime": startTime, + "endTime": endTime, + }, respObj) + if err != nil { + return + } + return respObj.Details.Time, respObj.Details.Bandwidth, nil +} diff --git a/bce-sdk-go/services/cdn/api/tool.go b/bce-sdk-go/services/cdn/api/tool.go new file mode 100644 index 0000000..1af347f --- /dev/null +++ b/bce-sdk-go/services/cdn/api/tool.go @@ -0,0 +1,93 @@ +package api + +import "github.com/baidubce/bce-sdk-go/bce" + +// IpInfo defined a struct for IP info +type IpInfo struct { + IP string `json:"ip"` + IsCdnIp bool `json:"cdnIP"` + Isp string `json:"isp"` + Region string `json:"region"` +} + +// BackOriginNode defined a struct for CDN node which may request the origin server if cache missed. +type BackOriginNode struct { + CNNAME string `json:"cnname"` + IP string `json:"ip"` + Level string `json:"level"` + City string `json:"city"` + Province string `json:"province"` + ISP string `json:"isp"` +} + +// GetIpInfo - retrieves information about the specified IP +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyeunq#%E5%8D%95%E4%B8%AAip%E6%9F%A5%E8%AF%A2%E6%8E%A5%E5%8F%A3 +// +// PARAMS: +// - cli: the client agent can execute sending request +// - ip: the specified ip addr +// - action: the action for operating the ip addr +// +// RETURNS: +// - *IpInfo: the information about the specified ip addr +// - error: nil if success otherwise the specific error +func GetIpInfo(cli bce.Client, ip string, action string) (*IpInfo, error) { + params := map[string]string{ + "ip": ip, + "action": action, + } + + respObj := &IpInfo{} + err := httpRequest(cli, "GET", "/v2/utils", params, nil, respObj) + if err != nil { + return nil, err + } + respObj.IP = ip + return respObj, nil +} + +// GetIpListInfo - retrieves information about the specified IP list +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyeunq#ip-list-%E6%9F%A5%E8%AF%A2%E6%8E%A5%E5%8F%A3 +// +// PARAMS: +// - cli: the client agent can execute sending request +// - ips: IP list +// - action: the action for operating the ip addr +// +// RETURNS: +// - []IpInfo: IP list's information +// - error: nil if success otherwise the specific error +func GetIpListInfo(cli bce.Client, ips []string, action string) ([]IpInfo, error) { + reqObj := map[string]interface{}{ + "ips": ips, + "action": action, + } + + var respObj []IpInfo + err := httpRequest(cli, "POST", "/v2/utils/ips", nil, reqObj, &respObj) + if err != nil { + return nil, err + } + return respObj, nil +} + +// GetBackOriginNodes - get CDN nodes that may request the origin server if cache missed +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyeunq#%E7%99%BE%E5%BA%A6%E5%9B%9E%E6%BA%90ip%E5%9C%B0%E5%9D%80%E6%AE%B5%E6%9F%A5%E8%AF%A2%E6%8E%A5%E5%8F%A3 +// +// PARAMS: +// - cli: the client agent can execute sending request +// +// RETURNS: +// - []BackOriginNode: list of CDN node +// - error: nil if success otherwise the specific error +func GetBackOriginNodes(cli bce.Client) ([]BackOriginNode, error) { + respObj := &struct { + Status int `json:"status"` + BackOriginNodes []BackOriginNode `json:"details"` + }{} + err := httpRequest(cli, "GET", "/v2/nodes/list", nil, nil, &respObj) + if err != nil { + return nil, err + } + return respObj.BackOriginNodes, nil +} diff --git a/bce-sdk-go/services/cdn/api/util.go b/bce-sdk-go/services/cdn/api/util.go new file mode 100644 index 0000000..36af003 --- /dev/null +++ b/bce-sdk-go/services/cdn/api/util.go @@ -0,0 +1,80 @@ +package api + +import ( + "bytes" + "encoding/json" + "errors" + + "github.com/baidubce/bce-sdk-go/bce" +) + +// SendCustomRequest - send a HTTP request, and response data or error, it use the default times for retrying +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - method: the HTTP requested method, e.g. "GET", "POST", "PUT" ... +// - urlPath: a path component, consisting of a sequence of path segments separated by a slash ( / ). +// - params: the query params, which will be append to the query path, and separate by "&" +// e.g. http://www.baidu.com?query_param1=value1&query_param2=value2 +// - reqHeaders: the request http headers +// - bodyObj: the HTTP requested body content transferred to a goland object +// - respObj: the HTTP response content transferred to a goland object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func SendCustomRequest(cli bce.Client, method string, urlPath string, params, reqHeaders map[string]string, bodyObj interface{}, respObj interface{}) error { + if method != "GET" && method != "POST" && method != "PUT" && method != "DELETE" { + return errors.New("invalid http method") + } + + req := &bce.BceRequest{} + req.SetUri(urlPath) + req.SetMethod(method) + req.SetParams(params) + req.SetHeaders(reqHeaders) + + if bodyObj != nil { + bodyBytes, err := newBodyFromJsonObj(bodyObj) + if err != nil { + return err + } + req.SetBody(bodyBytes) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + defer func() { + reader := resp.Body() + if reader != nil { + _ = reader.Close() + } + }() + + buf := new(bytes.Buffer) + _, _ = buf.ReadFrom(resp.Body()) + respBodyBytes := buf.Bytes() + + if respObj != nil { + err := json.Unmarshal(respBodyBytes, respObj) + if err != nil { + return err + } + } + + return nil +} + +func httpRequest(cli bce.Client, method string, urlPath string, params map[string]string, bodyObj interface{}, respObj interface{}) error { + return SendCustomRequest(cli, method, urlPath, params, nil, bodyObj, respObj) +} + +func newBodyFromJsonObj(obj interface{}) (*bce.Body, error) { + data, err := json.Marshal(obj) + if err != nil { + return nil, err + } + + return bce.NewBodyFromBytes(data) +} diff --git a/bce-sdk-go/services/cdn/client.go b/bce-sdk-go/services/cdn/client.go new file mode 100644 index 0000000..be69932 --- /dev/null +++ b/bce-sdk-go/services/cdn/client.go @@ -0,0 +1,1387 @@ +package cdn + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/cdn/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "cdn.baidubce.com" +) + +// Client of CDN service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the CDN service client with default configuration +// Use `cli.Config.xxx` to access the config or change it to non-default value +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// SendCustomRequest - send a HTTP request, and response data or error, it use the default times for retrying +// +// PARAMS: +// - method: the HTTP requested method, e.g. "GET", "POST", "PUT" ... +// - urlPath: a path component, consisting of a sequence of path segments separated by a slash ( / ). +// - params: the query params, which will be append to the query path, and separate by "&" +// e.g. http://www.baidu.com?query_param1=value1&query_param2=value2 +// - reqHeaders: the request http headers +// - bodyObj: the HTTP requested body content transferred to a goland object +// - respObj: the HTTP response content transferred to a goland object +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SendCustomRequest(method string, urlPath string, params, reqHeaders map[string]string, bodyObj interface{}, respObj interface{}) error { + return api.SendCustomRequest(cli, method, urlPath, params, reqHeaders, bodyObj, respObj) +} + +// ListDomains - list all domains that in CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN/s/sjwvyewt1 +// +// PARAMS: +// - marker: a marker is a start point of searching +// +// RETURNS: +// - []string: domains belongs to the user +// - string: a marker for next searching, empty if is in the end +// - error: nil if success otherwise the specific error +func (cli *Client) ListDomains(marker string) ([]string, string, error) { + return api.ListDomains(cli, marker) +} + +// GetDomainStatus - get domains' details +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyewf1 +// +// PARAMS: +// - status: the specified running status, the available values are "RUNNING", "STOPPED", OPERATING or "ALL" +// - rule: the regex matching rule +// +// RETURNS: +// - []DomainStatus: domain details list +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainStatus(status string, rule string) ([]api.DomainStatus, error) { + return api.GetDomainStatus(cli, status, rule) +} + +// IsValidDomain - check the specified domain whether it can be added to CDN service or not. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qjwvyexh6 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *DomainValidInfo: available information about the specified domain +// - error: nil if success otherwise the specific error +func (cli *Client) IsValidDomain(domain string) (*api.DomainValidInfo, error) { + return api.IsValidDomain(cli, domain) +} + +// CreateDomain - add a specified domain into CDN service +// For details, please refer https://cloud.baidu.com/doc/CDN/s/gjwvyex4o +// +// PARAMS: +// - domain: the specified domain +// - originInit: initialized data for a CDN domain +// +// RETURNS: +// - *DomainCreatedInfo: the details about created a CDN domain +// - error: nil if success otherwise the specific error +func (cli *Client) CreateDomain(domain string, originInit *api.OriginInit) (*api.DomainCreatedInfo, error) { + return api.CreateDomain(cli, domain, originInit) +} + +// EnableDomain - enable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Jjwvyexv8 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) EnableDomain(domain string) error { + return api.EnableDomain(cli, domain) +} + +// DisableDomain - disable a specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/9jwvyew3e +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) DisableDomain(domain string) error { + return api.DisableDomain(cli, domain) +} + +// DeleteDomain - delete a specified domain from BCE CDN system. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Njwvyey7f +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) DeleteDomain(domain string) error { + return api.DeleteDomain(cli, domain) +} + +// GetIpInfo - retrieves information about the specified IP +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyeunq +// +// PARAMS: +// - ip: the specified ip addr +// - action: the action for operating the ip addr +// +// RETURNS: +// - *IpInfo: the information about the specified ip addr +// - error: nil if success otherwise the specific error +func (cli *Client) GetIpInfo(ip string, action string) (*api.IpInfo, error) { + return api.GetIpInfo(cli, ip, action) +} + +// GetIpListInfo - retrieves information about the specified IP list +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jwvyeunq#ip-list-%E6%9F%A5%E8%AF%A2%E6%8E%A5%E5%8F%A3 +// +// PARAMS: +// - ips: IP list +// - action: the action for operating the ip addr +// +// RETURNS: +// - []IpInfo: IP list's information +// - error: nil if success otherwise the specific error +func (cli *Client) GetIpListInfo(ips []string, action string) ([]api.IpInfo, error) { + return api.GetIpListInfo(cli, ips, action) +} + +// GetBackOriginNodes - get CDN nodes that may request the origin server if cache missed +// +// RETURNS: +// - []BackOriginNode: list of CDN node +// - error: nil if success otherwise the specific error +func (cli *Client) GetBackOriginNodes() ([]api.BackOriginNode, error) { + return api.GetBackOriginNodes(cli) +} + +// GetDomainConfig - get the configuration for the specified domain. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/2jwvyf39o +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *DomainConfig: the configuration about the specified domain +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainConfig(domain string) (*api.DomainConfig, error) { + return api.GetDomainConfig(cli, domain) +} + +// SetDomainOrigin - set the origin setting for the new +// For details, please refer https://cloud.baidu.com/doc/CDN/s/xjxzi7729 +// +// PARAMS: +// - domain: the specified domain +// - origins: the origin servers +// - defaultHost: the default host +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDomainOrigin(domain string, origins []api.OriginPeer, defaultHost string) error { + return api.SetDomainOrigin(cli, domain, origins, defaultHost) +} + +// SetOriginProtocol - set the http protocol back to backend server. +// The valid "originProtocol" must be "http", "https" or "*", +// "http" means send the HTTP request to the backend server, +// "https" means send the HTTPS request to the backend server, +// "*" means send the request follow the client's requesting protocol. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7k9jdhhlm +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// - originProtocol: the protocol used for back to the backend server +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetOriginProtocol(domain string, originProtocol string) error { + return api.SetOriginProtocol(cli, domain, originProtocol) +} + +// GetOriginProtocol - get the protocol used for back to the backend server. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/dk9jdoob4 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - domain: the specified domain +// +// RETURNS: +// - string: the protocol used for back to the backend server, it's value must be "http", "https" or "*" +// - error: nil if success otherwise the specific error +func (cli *Client) GetOriginProtocol(domain string) (string, error) { + return api.GetOriginProtocol(cli, domain) +} + +// SetDomainSeo - set SEO setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Jjxziuq4y +// +// PARAMS: +// - domain: the specified domain +// - seoSwitch: the setting about SEO +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDomainSeo(domain string, seoSwitch *api.SeoSwitch) error { + return api.SetDomainSeo(cli, domain, seoSwitch) +} + +// GetDomainSeo - retrieve the setting about SEO +// There are two types of data that the server responds to +// 1. `{"seoSwitch":[]}` indicates no setting about SEO +// 2. `{"seoSwitch":{"diretlyOrigin":"ON","pushRecord":"OFF"}}` indicates it had normal setting about SEO. +// So the code need to handle the complex affairs +// +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Djxzjfz8f +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *SeoSwitch: the setting about SEO +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainSeo(domain string) (*api.SeoSwitch, error) { + return api.GetDomainSeo(cli, domain) +} + +// GetCacheTTL - get the current cached setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ljxzhl9bu +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - []CacheTTL: the cache setting list +// - error: nil if success otherwise the specific error +func (cli *Client) GetCacheTTL(domain string) ([]api.CacheTTL, error) { + return api.GetCacheTTL(cli, domain) +} + +// SetCacheTTL - add some rules for cached setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/wjxzhgxnx +// +// PARAMS: +// - domain: the specified domain +// - cacheTTLs: the cache setting list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetCacheTTL(domain string, cacheTTLs []api.CacheTTL) error { + return api.SetCacheTTL(cli, domain, cacheTTLs) +} + +// SetRefererACL - set a rule for filter some HTTP request, blackList and whiteList only one can be set +// For details, please refer https://cloud.baidu.com/doc/CDN/s/yjxzhvf21 +// +// PARAMS: +// - domain: the specified domain +// - blackList: the forbidden host +// - whiteList: the available host +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetRefererACL(domain string, blackList []string, whiteList []string, isAllowEmpty bool) error { + return api.SetRefererACL(cli, domain, blackList, whiteList, isAllowEmpty) +} + +// GetRefererACL - get referer ACL setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ujzkotvtb +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *api.RefererACL: referer ACL setting +// - error: nil if success otherwise the specific error +func (cli *Client) GetRefererACL(domain string) (*api.RefererACL, error) { + return api.GetRefererACL(cli, domain) +} + +// SetIpACL - set a rule for filter some HTTP request, blackList and whiteList only one can be set +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jxzhwc4d +// +// PARAMS: +// - domain: the specified domain +// - blackList: the forbidden ip +// - whiteList: the available ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetIpACL(domain string, blackList []string, whiteList []string) error { + return api.SetIpACL(cli, domain, blackList, whiteList) +} + +// GetIpACL - get black IP or white IP +// For details, please refer https://cloud.baidu.com/doc/CDN/s/jjzkp5ku7 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *api.IpACL: ip setting +// - error: nil if success otherwise the specific error +func (cli *Client) GetIpACL(domain string) (*api.IpACL, error) { + return api.GetIpACL(cli, domain) +} + +// SetUaACL - set a rule for filter the specified HTTP header named "User-Agent" +// For details, please refer https://cloud.baidu.com/doc/CDN/s/uk88i2a86 +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// - blackList: the forbidden UA +// - whiteList: the available UA +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetUaACL(domain string, blackList []string, whiteList []string) error { + return api.SetUaACL(cli, domain, blackList, whiteList) +} + +// GetUaACL - get black UA or white UA +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ak88ix19h +// +// PARAMS: +// - cli: the client agent can execute sending request +// - domain: the specified domain +// +// RETURNS: +// - *api.UaACL: filter config for UA +// - error: nil if success otherwise the specific error +func (cli *Client) GetUaACL(domain string) (*api.UaACL, error) { + return api.GetUaACL(cli, domain) +} + +// Deprecated, please use SetTrafficLimit as substitute +// SetLimitRate - set limited speed +// +// PARAMS: +// - domain: the specified domain +// - limitRate: the limited rate, "1024" means the transmittal speed is less than 1024 Byte/s +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetLimitRate(domain string, limitRate int) error { + return api.SetLimitRate(cli, domain, limitRate) +} + +// SetTrafficLimit - set the traffic limitation for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ujxzi418e +// +// PARAMS: +// - domain: the specified domain +// - trafficLimit: config of traffic limitation +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetTrafficLimit(domain string, trafficLimit *api.TrafficLimit) error { + return api.SetTrafficLimit(cli, domain, trafficLimit) +} + +// GetTrafficLimit - get the traffic limitation of the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7k4npdru0 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *TrafficLimit: config of traffic limitation +// - error: nil if success otherwise the specific error +func (cli *Client) GetTrafficLimit(domain string) (*api.TrafficLimit, error) { + return api.GetTrafficLimit(cli, domain) +} + +// SetDomainHttps - set a rule for speed HTTPS' request +// For details, please refer https://cloud.baidu.com/doc/CDN/s/rjy6v3tnr +// +// PARAMS: +// - domain: the specified domain +// - httpsConfig: the rules about the HTTP configure +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDomainHttps(domain string, httpsConfig *api.HTTPSConfig) error { + return api.SetDomainHttps(cli, domain, httpsConfig) +} + +// GetDomainHttps - get the setting about HTTPS +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *HTTPSConfig: the rules about the HTTP configure +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainHttps(domain string) (*api.HTTPSConfig, error) { + return api.GetDomainHttps(cli, domain) +} + +// PutCert - put the certificate data for the specified domain to server, you can also enable HTTPS or not. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qjzuz2hp8 +// +// PARAMS: +// - domain: the specified domain +// - userCert: certificate data +// - httpsEnabled: "ON" for enable HTTPS, "OFF" for disable HTTPS, otherwise invalid. +// +// RETURNS: +// - string: certId +// - error: nil if success otherwise the specific error +func (cli *Client) PutCert(domain string, userCert *api.UserCertificate, httpsEnabled string) (certId string, err error) { + return api.PutCert(cli, domain, userCert, httpsEnabled) +} + +// GetCert - query the certificate data for the specified domain. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/kjzuvz70t +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *CertificateDetail: certificate details +// - error: nil if success otherwise the specific error +func (cli *Client) GetCert(domain string) (certDetail *api.CertificateDetail, err error) { + return api.GetCert(cli, domain) +} + +// DeleteCert - delete the certificate data for the specified domain. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ljzuylmee +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *CertificateDetail: certificate details +// - error: nil if success otherwise the specific error +func (cli *Client) DeleteCert(domain string) error { + return api.DeleteCert(cli, domain) +} + +// SetOCSP - set "OCSP" for the specified domain, +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Pkf2c0ugn +// +// PARAMS: +// - domain: the specified domain +// - enabled: true for "OCSP" opening otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetOCSP(domain string, enabled bool) error { + return api.SetOCSP(cli, domain, enabled) +} + +// GetOCSP - get "OCSP" switch details for the specified domain +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true for "OCSP" opening otherwise closed +// - error: nil if success otherwise the specific error +func (cli *Client) GetOCSP(domain string) (bool, error) { + return api.GetOCSP(cli, domain) +} + +// SetDomainRequestAuth - set the authorized rules for requesting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/njxzi59g9 +// +// PARAMS: +// - domain: the specified domain +// - requestAuth: the rules about the auth +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDomainRequestAuth(domain string, requestAuth *api.RequestAuth) error { + return api.SetDomainRequestAuth(cli, domain, requestAuth) +} + +// Deprecated: We suggest use the SetOriginProtocol as an alternative +// SetFollowProtocol - set whether using the same protocol or not when back to the sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/9jxzi89k2 +// +// PARAMS: +// - domain: the specified domain +// - isFollowProtocol: true in using the same protocol or not when back to the sourced server, false for other +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetFollowProtocol(domain string, isFollowProtocol bool) error { + return api.SetFollowProtocol(cli, domain, isFollowProtocol) +} + +// SetHttpHeader -set some HTTP headers which can be added or deleted when response form CDN edge node +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Jjxzil1sd +// +// PARAMS: +// - domain: the specified domain +// - httpHeaders: the HTTP headers' setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetHttpHeader(domain string, httpHeaders []api.HttpHeader) error { + return api.SetHttpHeader(cli, domain, httpHeaders) +} + +// GetHttpHeader - get the HTTP headers' setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/6jxzip3wn +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - []HttpHeader: the HTTP headers in setting +func (cli *Client) GetHttpHeader(domain string) ([]api.HttpHeader, error) { + return api.GetHttpHeader(cli, domain) +} + +// SetErrorPage - set the page that redirected to when error occurred +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ejy6vc4yb +// +// PARAMS: +// - domain: the specified domain +// - errorPages: the custom pages' setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetErrorPage(domain string, errorPages []api.ErrorPage) error { + return api.SetErrorPage(cli, domain, errorPages) +} + +// GetErrorPage - get the custom pages' setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qjy6vfk2u +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - []ErrorPage: the pages' setting +// - error: nil if success otherwise the specific error +func (cli *Client) GetErrorPage(domain string) ([]api.ErrorPage, error) { + return api.GetErrorPage(cli, domain) +} + +// SetCacheShared - set sharing cache with the other domain. +// For example, 1.test.com shared cache with 2.test.com. +// First, we query http://2.test.com/index.html and got missed. +// Secondly, we query http://1.test.com/index.html and got hit +// because of the CacheShared setting before. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/0kf272ds7 +// +// PARAMS: +// - domain: the specified domain +// - cacheSharedConfig: enabled sets true for shared with the specified domain, otherwise no shared. +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetCacheShared(domain string, config *api.CacheShared) error { + return api.SetCacheShared(cli, domain, config) +} + +// GetCacheShared - get shared cache setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Mjy6vo9z2 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *CacheShared: shared cache setting +// - error: nil if success otherwise the specific error +func (cli *Client) GetCacheShared(domain string) (*api.CacheShared, error) { + return api.GetCacheShared(cli, domain) +} + +// SetMediaDrag - set the media setting about mp4 and flv +// For details, please refer https://cloud.baidu.com/doc/CDN/s/4jy6v6xk3 +// +// PARAMS: +// - domain: the specified domain +// - mediaDragConf: media setting about mp4 and flv +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetMediaDrag(domain string, mediaDragConf *api.MediaDragConf) error { + return api.SetMediaDrag(cli, domain, mediaDragConf) +} + +// GetMediaDrag - get the media setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ojy6v9q8f +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *MediaDragConf: the media setting about mp4 and flv +// - error: nil if success otherwise the specific error +func (cli *Client) GetMediaDrag(domain string) (*api.MediaDragConf, error) { + return api.GetMediaDrag(cli, domain) +} + +// SetFileTrim - trim the text file or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Xjy6vimct +// +// PARAMS: +// - domain: the specified domain +// - fileTrim: true means trimming the text file, false means do nothing +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetFileTrim(domain string, fileTrim bool) error { + return api.SetFileTrim(cli, domain, fileTrim) +} + +// GetFileTrim - get the trim setting about text file +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ujy6vjxnl +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true means trimming the text file, false means do nothing +// - error: nil if success otherwise the specific error +func (cli *Client) GetFileTrim(domain string) (bool, error) { + return api.GetFileTrim(cli, domain) +} + +// SetIPv6 - open/close IPv6 +// For details, please refer https://cloud.baidu.com/doc/CDN/s/qkggncsxp +// +// PARAMS: +// - domain: the specified domain +// - enabled: true for setting IPv6 switch on otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetIPv6(domain string, enabled bool) error { + return api.SetIPv6(cli, domain, enabled) +} + +// GetIPv6 - get IPv6 switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Ykggnobxd +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true for setting IPv6 switch on otherwise closed +// - error: nil if success otherwise the specific error +func (cli *Client) GetIPv6(domain string) (bool, error) { + return api.GetIPv6(cli, domain) +} + +// SetQUIC - open or close QUIC. open QUIC require enabled HTTPS first +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Qkggmoz7p +// +// PARAMS: +// - domain: the specified domain +// - enabled: true for QUIC opening otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetQUIC(domain string, enabled bool) error { + return api.SetQUIC(cli, domain, enabled) +} + +// GetQUIC - get QUIC switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/pkggn6l1f +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true for QUIC opening otherwise closed +// - error: nil if success otherwise the specific error +func (cli *Client) GetQUIC(domain string) (bool, error) { + return api.GetQUIC(cli, domain) +} + +// SetOfflineMode - set "offlineMode" for the specified domain, +// setting true means also response old cached object when got origin server error +// instead of response error to client directly. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/xkhopuj48 +// +// PARAMS: +// - domain: the specified domain +// - enabled: true for offlineMode opening otherwise closed +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetOfflineMode(domain string, enabled bool) error { + return api.SetOfflineMode(cli, domain, enabled) +} + +// GetOfflineMode - get "offlineMode" switch details for the specified domain +// For details, please refer https://cloud.baidu.com/doc/CDN/s/tkhopvlkj +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true for offlineMode opening otherwise closed +// - error: nil if success otherwise the specific error +func (cli *Client) GetOfflineMode(domain string) (bool, error) { + return api.GetOfflineMode(cli, domain) +} + +// SetMobileAccess - distinguish the client or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Mjy6vmv6g +// +// PARAMS: +// - domain: the specified domain +// - distinguishClient: true means distinguishing the client, false means not +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetMobileAccess(domain string, distinguishClient bool) error { + return api.SetMobileAccess(cli, domain, distinguishClient) +} + +// GetMobileAccess - get the setting about distinguishing the client or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Mjy6vo9z2 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true means distinguishing the client, false means not +// - error: nil if success otherwise the specific error +func (cli *Client) GetMobileAccess(domain string) (bool, error) { + return api.GetMobileAccess(cli, domain) +} + +// SetClientIp - set the specified HTTP header for the origin server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Kjy6umyrm +// +// PARAMS: +// - domain: the specified domain +// - clientIp: header setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetClientIp(domain string, clientIp *api.ClientIp) error { + return api.SetClientIp(cli, domain, clientIp) +} + +// GetClientIp - get the setting about getting client IP +// For details, please refer https://cloud.baidu.com/doc/CDN/s/8jy6urcq5 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *ClientIp: the HTTP header setting for origin server to get client IP +// - error: nil if success otherwise the specific error +func (cli *Client) GetClientIp(domain string) (*api.ClientIp, error) { + return api.GetClientIp(cli, domain) +} + +// SetRetryOrigin - set the policy for retry origin servers if got failed +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ukhopl3bq +// +// PARAMS: +// - domain: the specified domain +// - retryOrigin: retry policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetRetryOrigin(domain string, retryOrigin *api.RetryOrigin) error { + return api.SetRetryOrigin(cli, domain, retryOrigin) +} + +// GetRetryOrigin - get the policy for retry origin servers +// For details, please refer https://cloud.baidu.com/doc/CDN/s/bkhoppbhd +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *RetryOrigin: policy of retry origin servers +// - error: nil if success otherwise the specific error +func (cli *Client) GetRetryOrigin(domain string) (*api.RetryOrigin, error) { + return api.GetRetryOrigin(cli, domain) +} + +// SetAccessLimit - set the qps for on one client +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Kjy6v02wt +// +// PARAMS: +// - domain: the specified domain +// - accessLimit: the access setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetAccessLimit(domain string, accessLimit *api.AccessLimit) error { + return api.SetAccessLimit(cli, domain, accessLimit) +} + +// GetAccessLimit - get the qps setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/rjy6v3tnr +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *AccessLimit: the access setting +// - error: nil if success otherwise the specific error +func (cli *Client) GetAccessLimit(domain string) (*api.AccessLimit, error) { + return api.GetAccessLimit(cli, domain) +} + +// SetCacheUrlArgs - tell the CDN system cache the url's params or not +// For details, please refer https://cloud.baidu.com/doc/CDN/s/vjxzho0kx +// +// PARAMS: +// - domain: the specified domain +// - cacheFullUrl: whether cache the full url or not, full url means include params, also some extra params can be avoided +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetCacheUrlArgs(domain string, cacheFullUrl *api.CacheUrlArgs) error { + return api.SetCacheUrlArgs(cli, domain, cacheFullUrl) +} + +// GetCacheUrlArgs - get the cached rules +// For details, please refer https://cloud.baidu.com/doc/CDN/s/sjxzhsb6h +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *CacheUrlArgs: the details about cached rules +// - error: nil if success otherwise the specific error +func (cli *Client) GetCacheUrlArgs(domain string) (*api.CacheUrlArgs, error) { + return api.GetCacheUrlArgs(cli, domain) +} + +// SetCors - set about Cross-origin resource sharing +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Rjxzi1cfs +// PARAMS: +// - domain: the specified domain +// - isAllow: true means allow Cors, false means not allow +// - originList: the origin setting, it's invalid when isAllow is false +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetCors(domain string, isAllow bool, originList []string) error { + return api.SetCors(cli, domain, isAllow, originList) +} + +// GetCors - get the Cors setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/tjxzi2d7t +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - *CorsCfg: the Cors setting +// - error: nil if success otherwise the specific error +func (cli *Client) GetCors(domain string) (*api.CorsCfg, error) { + return api.GetCors(cli, domain) +} + +// SetRangeSwitch - set the range setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Fjxziabst +// +// PARAMS: +// - domain: the specified domain +// - enabled: true means enable range cached, false means disable range cached +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetRangeSwitch(domain string, enabled bool) error { + return api.SetRangeSwitch(cli, domain, enabled) +} + +// GetRangeSwitch - get the range setting +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jxzid6o9 +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - bool: true means enable range cached, false means disable range cached +// - error: nil if success otherwise the specific error +func (cli *Client) GetRangeSwitch(domain string) (bool, error) { + return api.GetRangeSwitch(cli, domain) +} + +// SetContentEncoding - set Content-Encoding +// For details, please refer https://cloud.baidu.com/doc/CDN/s/0jyqyahsb +// +// PARAMS: +// - domain: the specified domain +// - enabled: true means using the specified encoding algorithm indicated by "encodingType" in transferring, +// false means disable encoding +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetContentEncoding(domain string, enabled bool, encodingType string) error { + return api.SetContentEncoding(cli, domain, enabled, encodingType) +} + +// GetContentEncoding - get the setting about Content-Encoding +// For details, please refer https://cloud.baidu.com/doc/CDN/s/bjyqycw8g +// +// PARAMS: +// - domain: the specified domain +// +// RETURNS: +// - string: the encoding algorithm for transferring, empty means disable encoding in transferring +// - error: nil if success otherwise the specific error +func (cli *Client) GetContentEncoding(domain string) (string, error) { + return api.GetContentEncoding(cli, domain) +} + +// Purge - tells the CDN system to purge the specified files +// For more details, please refer https://cloud.baidu.com/doc/CDN/s/ijwvyeyyj +// +// PARAMS: +// - tasks: the tasks about purging the files from the CDN nodes +// +// RETURNS: +// - PurgedId: an ID representing a purged task, using it to search the task progress +// - error: nil if success otherwise the specific error. +func (cli *Client) Purge(tasks []api.PurgeTask) (api.PurgedId, error) { + return api.Purge(cli, tasks) +} + +// GetPurgedStatus - get the purged progress +// For details, please refer https://cloud.baidu.com/doc/CDN/s/ujwvyezqm +// +// PARAMS: +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url +// +// RETURNS: +// - *PurgedStatus: the details about the purged +// - error: nil if success otherwise the specific error +func (cli *Client) GetPurgedStatus(queryData *api.CStatusQueryData) (*api.PurgedStatus, error) { + return api.GetPurgedStatus(cli, queryData) +} + +// Prefetch - tells the CDN system to prefetch the specified files +// For details, please refer https://cloud.baidu.com/doc/CDN/s/Rjwvyf0ff +// +// PARAMS: +// - tasks: the tasks about prefetch the files from the CDN nodes +// - error: nil if success otherwise the specific error +func (cli *Client) Prefetch(tasks []api.PrefetchTask) (api.PrefetchId, error) { + return api.Prefetch(cli, tasks) +} + +// GetPrefetchStatus - get the prefetch progress +// For details, please refer https://cloud.baidu.com/doc/CDN/s/4jwvyf01w +// +// PARAMS: +// - queryData: querying conditions, it contains the time interval, the task ID and the specified url. +// +// RETURNS: +// - *PrefetchStatus: the details about the prefetch +// - error: nil if success otherwise the specific error +func (cli *Client) GetPrefetchStatus(queryData *api.CStatusQueryData) (*api.PrefetchStatus, error) { + return api.GetPrefetchStatus(cli, queryData) +} + +// GetQuota - get the quota about purge and prefetch +// For details, please refer https://cloud.baidu.com/doc/CDN/s/zjwvyeze3 +// +// RETURNS: +// - QuotaDetail: the quota details about a specified user +// - error: nil if success otherwise the specific error +func (cli *Client) GetQuota() (*api.QuotaDetail, error) { + return api.GetQuota(cli) +} + +// GetCacheOpRecords get the history operating records +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jypnzjqt +// +// PARAMS: +// - queryData: querying conditions, it contains the time interval, the task type and the specified url +// +// RETURNS: +// - *RecordDetails: the details about the records +// - error: nil if success otherwise the specific error +func (cli *Client) GetCacheOpRecords(queryData *api.CRecordQueryData) (*api.RecordDetails, error) { + return api.GetCacheOpRecords(cli, queryData) +} + +// EnableDsa - enable DSA +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7jwvyf1h5 +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) EnableDsa() error { + return api.EnableDsa(cli) +} + +// DisableDsa - disable DSA +// For details, please refer https://cloud.baidu.com/doc/CDN/s/7jwvyf1h5 +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) DisableDsa() error { + return api.DisableDsa(cli) +} + +// ListDsaDomains - retrieve all the domains in DSA service +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf1sq +// +// RETURNS: +// - []DSADomain: the details about DSA domains +// - error: nil if success otherwise the specific error +func (cli *Client) ListDsaDomains() ([]api.DSADomain, error) { + return api.ListDsaDomains(cli) +} + +// SetDsaConfig - set the DSA configuration +// For details, please refer https://cloud.baidu.com/doc/CDN/s/0jwvyf26d +// +// PARAMS: +// - domain: the specified domain +// - dsaConfig: the specified configuration for the specified domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) SetDsaConfig(domain string, dsaConfig *api.DSAConfig) error { + return api.SetDsaConfig(cli, domain, dsaConfig) +} + +// GetDomainLog -get one domain's log urls +// For details, please refer https://cloud.baidu.com/doc/CDN/s/cjwvyf0r9 +// +// PARAMS: +// - domain: the specified domain +// - timeInterval: the specified time interval +// +// RETURNS: +// - []LogEntry: the log detail list +// - error: nil if success otherwise the specific error +func (cli *Client) GetDomainLog(domain string, timeInterval api.TimeInterval) ([]api.LogEntry, error) { + return api.GetDomainLog(cli, domain, timeInterval) +} + +// GetMultiDomainLog - get many domains' log urls +// For details, please refer https://cloud.baidu.com/doc/CDN/s/cjwvyf0r9 +// +// PARAMS: +// - queryData: the querying conditions +// - error: nil if success otherwise the specific error +func (cli *Client) GetMultiDomainLog(queryData *api.LogQueryData) ([]api.LogEntry, error) { + return api.GetMultiDomainLog(cli, queryData) +} + +// GetAvgSpeed - get the average speed +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E5%B9%B3%E5%9D%87%E9%80%9F%E7%8E%87 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []AvgSpeedDetail: the detail list about the average speed +// - error: nil if success otherwise the specific error +func (cli *Client) GetAvgSpeed(queryCondition *api.QueryCondition) ([]api.AvgSpeedDetail, error) { + return api.GetAvgSpeed(cli, queryCondition) +} + +// GetAvgSpeed - get the average speed filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83%E6%9F%A5%E8%AF%A2%E5%B9%B3%E5%9D%87%E9%80%9F%E7%8E%87 +// +// PARAMS: +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []AvgSpeedRegionDetail: the detail list about the average speed +// - error: nil if success otherwise the specific error +func (cli *Client) GetAvgSpeedByRegion(queryCondition *api.QueryCondition, prov string, isp string) ([]api.AvgSpeedRegionDetail, error) { + return api.GetAvgSpeedByRegion(cli, queryCondition, prov, isp) +} + +// GetPv - get the PV data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#pvqps%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// - level: the node level, the available values are "edge", "internal" and "all" +// +// RETURNS: +// - []PvDetail: the detail list about page view +// - error: nil if success otherwise the specific error +func (cli *Client) GetPv(queryCondition *api.QueryCondition, level string) ([]api.PvDetail, error) { + return api.GetPv(cli, queryCondition, level) +} + +// GetSrcPv - get the PV data in back to the sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%9B%9E%E6%BA%90pvqps%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []PvDetail: the detail list about page view +// - error: nil if success otherwise the specific error +func (cli *Client) GetSrcPv(queryCondition *api.QueryCondition) ([]api.PvDetail, error) { + return api.GetSrcPv(cli, queryCondition) +} + +// GetAvgPvByRegion - get the PV data filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2pvqps%E5%88%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83 +// +// PARAMS: +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []PvRegionDetail: the detail list about page view +// - error: nil if success otherwise the specific error +func (cli *Client) GetPvByRegion(queryCondition *api.QueryCondition, prov string, isp string) ([]api.PvRegionDetail, error) { + return api.GetPvByRegion(cli, queryCondition, prov, isp) +} + +// GetUv - get the UV data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#uv%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []UvDetail: the detail list about unique visitor +// - error: nil if success otherwise the specific error +func (cli *Client) GetUv(queryCondition *api.QueryCondition) ([]api.UvDetail, error) { + return api.GetUv(cli, queryCondition) +} + +// GetFlow - get the flow data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%B5%81%E9%87%8F%E3%80%81%E5%B8%A6%E5%AE%BD +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []FlowDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func (cli *Client) GetFlow(queryCondition *api.QueryCondition, level string) ([]api.FlowDetail, error) { + return api.GetFlow(cli, queryCondition, level) +} + +// GetFlowByProtocol - get the flow data filter by protocol +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%B5%81%E9%87%8F%E3%80%81%E5%B8%A6%E5%AE%BD%E5%88%86%E5%8D%8F%E8%AE%AE +// +// PARAMS: +// - queryCondition: the querying conditions +// - protocol: the specified HTTP protocol, like "http" or "https", "all" means both "http" and "https" +// +// RETURNS: +// - []FlowDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func (cli *Client) GetFlowByProtocol(queryCondition *api.QueryCondition, protocol string) ([]api.FlowDetail, error) { + return api.GetFlowByProtocol(cli, queryCondition, protocol) +} + +// GetFlowByRegion - get the flow data filter by location. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%B5%81%E9%87%8F%E3%80%81%E5%B8%A6%E5%AE%BD%EF%BC%88%E5%88%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83%EF%BC%89 +// +// PARAMS: +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []FlowRegionDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func (cli *Client) GetFlowByRegion(queryCondition *api.QueryCondition, prov string, isp string) ([]api.FlowRegionDetail, error) { + return api.GetFlowByRegion(cli, queryCondition, prov, isp) +} + +// GetSrcFlow - get the flow data in backed to sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E5%9B%9E%E6%BA%90%E6%B5%81%E9%87%8F%E3%80%81%E5%9B%9E%E6%BA%90%E5%B8%A6%E5%AE%BD +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []FlowDetail: the detail list about flow +// - error: nil if success otherwise the specific error +func (cli *Client) GetSrcFlow(queryCondition *api.QueryCondition) ([]api.FlowDetail, error) { + return api.GetSrcFlow(cli, queryCondition) +} + +// GetRealHit - get the detail about byte hit rate +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%AD%97%E8%8A%82%E5%91%BD%E4%B8%AD%E7%8E%87%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HitDetail: the detail list about byte rate +// - error: nil if success otherwise the specific error +func (cli *Client) GetRealHit(queryCondition *api.QueryCondition) ([]api.HitDetail, error) { + return api.GetRealHit(cli, queryCondition) +} + +// GetPvHit - get the detail about PV hit rate. +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E8%AF%B7%E6%B1%82%E5%91%BD%E4%B8%AD%E7%8E%87%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HitDetail: the detail list about pv rate +// - error: nil if success otherwise the specific error +func (cli *Client) GetPvHit(queryCondition *api.QueryCondition) ([]api.HitDetail, error) { + return api.GetPvHit(cli, queryCondition) +} + +// GetHttpCode - get the http code's statistics +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E7%8A%B6%E6%80%81%E7%A0%81%E7%BB%9F%E8%AE%A1%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HttpCodeDetail: the detail list about http code +// - error: nil if success otherwise the specific error +func (cli *Client) GetHttpCode(queryCondition *api.QueryCondition) ([]api.HttpCodeDetail, error) { + return api.GetHttpCode(cli, queryCondition) +} + +// GetSrcHttpCode - get the http code's statistics in backed to sourced server +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E5%9B%9E%E6%BA%90%E7%8A%B6%E6%80%81%E7%A0%81%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []HttpCodeDetail: the detail list about http code +// - error: nil if success otherwise the specific error +func (cli *Client) GetSrcHttpCode(queryCondition *api.QueryCondition) ([]api.HttpCodeDetail, error) { + return api.GetSrcHttpCode(cli, queryCondition) +} + +// GetHttpCodeByRegion - get the http code's statistics filter by location +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E7%8A%B6%E6%80%81%E7%A0%81%E7%BB%9F%E8%AE%A1%E6%9F%A5%E8%AF%A2%EF%BC%88%E5%88%86%E5%AE%A2%E6%88%B7%E7%AB%AF%E8%AE%BF%E9%97%AE%E5%88%86%E5%B8%83%EF%BC%89 +// +// PARAMS: +// - queryCondition: the querying conditions +// - prov: the specified area, like "beijing" +// - isp: the specified ISP, like "ct" +// +// RETURNS: +// - []HttpCodeRegionDetail: the detail list about http code +// - error: nil if success otherwise the specific error +func (cli *Client) GetHttpCodeByRegion(queryCondition *api.QueryCondition, prov string, isp string) ([]api.HttpCodeRegionDetail, error) { + return api.GetHttpCodeByRegion(cli, queryCondition, prov, isp) +} + +// GetTopNUrls - get the top N urls that requested +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#topn-urls +// +// PARAMS: +// - queryCondition: the querying conditions +// - httpCode: the specified HTTP code, like "200" +// +// RETURNS: +// - []TopNDetail: the top N urls' detail +// - error: nil if success otherwise the specific error +func (cli *Client) GetTopNUrls(queryCondition *api.QueryCondition, httpCode string) ([]api.TopNDetail, error) { + return api.GetTopNUrls(cli, queryCondition, httpCode) +} + +// GetTopNReferers - get the top N urls that brought by requested +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#topn-referers +// +// PARAMS: +// - queryCondition: the querying conditions +// - httpCode: the specified HTTP code, like "200" +// +// RETURNS: +// - []TopNDetail: the top N referer urls' detail +// - error: nil if success otherwise the specific error +func (cli *Client) GetTopNReferers(queryCondition *api.QueryCondition, httpCode string) ([]api.TopNDetail, error) { + return api.GetTopNReferers(cli, queryCondition, httpCode) +} + +// GetTopNDomains - get the top N domains that equested +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#topn-domains +// +// PARAMS: +// - queryCondition: the querying conditions +// - httpCode: the specified HTTP code, like "200" +// +// RETURNS: +// - []TopNDetail: the top N domains' detail +// - error: nil if success otherwise the specific error +func (cli *Client) GetTopNDomains(queryCondition *api.QueryCondition, httpCode string) ([]api.TopNDetail, error) { + return api.GetTopNDomains(cli, queryCondition, httpCode) +} + +// GetError - get the error code's data +// For details, please refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#cdn%E9%94%99%E8%AF%AF%E7%A0%81%E5%88%86%E7%B1%BB%E7%BB%9F%E8%AE%A1%E6%9F%A5%E8%AF%A2 +// +// PARAMS: +// - queryCondition: the querying conditions +// +// RETURNS: +// - []ErrorDetail: the top N error details +// - error: nil if success otherwise the specific error +func (cli *Client) GetError(queryCondition *api.QueryCondition) ([]api.ErrorDetail, error) { + return api.GetError(cli, queryCondition) +} + +// GetPeak95Bandwidth - get peak 95 bandwidth for the specified tags or domains. +// For details, pleader refer https://cloud.baidu.com/doc/CDN/s/5jwvyf8zn#%E6%9F%A5%E8%AF%A2%E6%9C%8895%E5%B3%B0%E5%80%BC%E5%B8%A6%E5%AE%BD +// +// PARAMS: +// - startTime: start time which in `YYYY-mm-ddTHH:ii:ssZ` style +// - endTime: end time which in `YYYY-mm-ddTHH:ii:ssZ` style +// - domains: a list of domains, only one of `tags` and `domains` can contains item +// - tags: a list of tag names, only one of `tags` and `domains` can contains item +// +// RETURNS: +// - string: the peak95 time which in `YYYY-mm-ddTHH:ii:ssZ` style +// - int64: peak95 bandwidth +// - error: nil if success otherwise the specific error +func (cli *Client) GetPeak95Bandwidth(startTime, endTime string, domains, tags []string) (string, int64, error) { + return api.GetPeak95Bandwidth(cli, startTime, endTime, domains, tags) +} diff --git a/bce-sdk-go/services/cdn/client_test.go b/bce-sdk-go/services/cdn/client_test.go new file mode 100644 index 0000000..b7d84d6 --- /dev/null +++ b/bce-sdk-go/services/cdn/client_test.go @@ -0,0 +1,1049 @@ +package cdn + +import ( + "encoding/json" + "fmt" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/cdn/api" + "github.com/baidubce/bce-sdk-go/util" +) + +const ( + testAuthorityDomain = "your_valid_domain" + testEndpoint = "cdn.baidubce.com" + testAK = "your_access_key_id" + testSK = "your_secret_key_id" + + // set testConfigOk true for unit test + testConfigOk = false +) + +var testCli *Client + +func TestMain(m *testing.M) { + if !testConfigOk { + fmt.Printf("TestMain terminated, please check testing config") + return + } + + var err error + testCli, err = NewClient(testAK, testSK, testEndpoint) + if err != nil { + fmt.Printf("TestMain terminated, err:%+v\n", err) + return + } + + if err := prepareForTest(testAuthorityDomain); err != nil { + fmt.Printf("TestMain terminated, error:%s", err.Error()) + return + } + + m.Run() +} + +func prepareForTest(domain string) error { + _, _ = testCli.CreateDomain(testAuthorityDomain, &api.OriginInit{ + Origin: []api.OriginPeer{ + { + Peer: "1.2.3.4", + Host: "1.2.3.4", + }, + }, + }) + + domainStatus, err := testCli.GetDomainStatus("ALL", "") + if err != nil { + return err + } + + for _, item := range domainStatus { + if item.Domain == domain { + return nil + } + } + + return fmt.Errorf("prepare failed, invalid domain:%s", domain) +} + +func checkClientErr(t *testing.T, funcName string, err error) { + //time.Sleep(time.Second * 1) + if funcName == "" { + t.Fatalf(`error param when called checkClientErr, the funcName is ""`) + } + + if !testConfigOk { + t.Logf("Configuration did not complete initialization\n") + return + } + + if err == nil { + return + } + + e, ok := err.(*bce.BceServiceError) + if !ok { + t.Fatalf("%s: %v\n", funcName, err) + return + } + + // `AccessDenied` indicates unauthorized AK/SK. + // `InvalidArgument` indicates sending the error params to server. + // `NotFound` indicates using error method. + if e.Code == "AccessDenied" || e.Code == "InvalidArgument" || e.Code == "NotFound" { + t.Fatalf("%s: %v\n", funcName, err) + } + + // we do not judge the errors in business logic. + t.Logf("%s: UT is ok, but there is a logic error:\n%s", funcName, err.Error()) +} + +func TestSendCustomRequest(t *testing.T) { + method := "GET" + urlPath := fmt.Sprintf("/v2/domain/%s/valid", testAuthorityDomain) + var params map[string]string + reqHeaders := map[string]string{ + "X-Test": "go-sdk-test", + } + var bodyObj interface{} + var respObj interface{} + err := testCli.SendCustomRequest(method, urlPath, params, reqHeaders, bodyObj, &respObj) + t.Logf("respObj details:\n\ttype:%T\n\tvalue:%+v", respObj, respObj) + checkClientErr(t, "SendCustomRequest", err) +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Test function about operating domain. +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +func TestListDomains(t *testing.T) { + domains, _, err := testCli.ListDomains("") + + t.Logf("domains: %v", domains) + checkClientErr(t, "ListDomains", err) +} + +func TestGetDomainStatus(t *testing.T) { + domainStatus, err := testCli.GetDomainStatus("ALL", "") + + t.Logf("domainStatus: %v", domainStatus) + checkClientErr(t, "GetDomainStatus", err) +} + +func TestIsValidDomain(t *testing.T) { + domainValidInfo, err := testCli.IsValidDomain(testAuthorityDomain) + + t.Logf("domainValidInfo: %v", domainValidInfo) + checkClientErr(t, "IsValidDomain", err) +} + +func TestCreateDomain(t *testing.T) { + domainCreatedInfo, err := testCli.CreateDomain(testAuthorityDomain, &api.OriginInit{ + Origin: []api.OriginPeer{ + { + Peer: "1.2.3.4", + Host: "1.2.3.4", + }, + }, + }) + + t.Logf("domainCreatedInfo: %v", domainCreatedInfo) + checkClientErr(t, "CreateDomain", err) +} + +func TestDisableDomain(t *testing.T) { + err := testCli.DisableDomain(testAuthorityDomain) + checkClientErr(t, "DisableDomain", err) +} + +func TestEnableDomain(t *testing.T) { + err := testCli.EnableDomain(testAuthorityDomain) + checkClientErr(t, "EnableDomain", err) +} + +// ignore delete +//func TestDeleteDomain(t *testing.T) { +// err := testCli.DeleteDomain(testAuthorityDomain) +// checkClientErr(t, "TestDeleteDomain", err) +//} + +func TestGetIpInfo(t *testing.T) { + ipInfo, err := testCli.GetIpInfo("116.114.98.35", "describeIp") + t.Logf("ipInfo: %v", ipInfo) + checkClientErr(t, "GetIpInfo", err) +} + +func TestGetIpListInfo(t *testing.T) { + ipsInfo, err := testCli.GetIpListInfo([]string{"116.114.98.35", "59.24.3.174"}, "describeIp") + t.Logf("ipsInfo: %+v", ipsInfo) + checkClientErr(t, "GetIpListInfo", err) +} + +func TestGetBackOriginNodes(t *testing.T) { + backOriginNodes, err := testCli.GetBackOriginNodes() + t.Logf("backOriginNodes: %+v", backOriginNodes) + checkClientErr(t, "GetBackOriginNodes", err) +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Test function about CRUD domain config. +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +func TestGetDomainConfig(t *testing.T) { + domainConfig, err := testCli.GetDomainConfig(testAuthorityDomain) + + data, _ := json.Marshal(domainConfig) + t.Logf("domainConfig: %s", string(data)) + checkClientErr(t, "GetDomainConfig", err) +} + +func TestSetDomainOrigin(t *testing.T) { + err := testCli.SetDomainOrigin(testAuthorityDomain, []api.OriginPeer{ + { + Peer: "1.1.1.1", + Host: "www.baidu.com", + Backup: true, + Follow302: true, + }, + { + Peer: "http://2.2.2.2", + Host: "www.baidu.com", + Backup: false, + Follow302: true, + }, + }, "www.baidu.com") + + checkClientErr(t, "SetDomainOrigin", err) +} + +func TestClientSetOriginProtocol(t *testing.T) { + err := testCli.SetOriginProtocol(testAuthorityDomain, "*") + checkClientErr(t, "SetOriginProtocol", err) +} + +func TestClientGetOriginProtocol(t *testing.T) { + originProtocol, err := testCli.GetOriginProtocol(testAuthorityDomain) + t.Logf("originProtocol: %s", originProtocol) + checkClientErr(t, "GetDomainSeo", err) +} + +func TestSetDomainSeo(t *testing.T) { + err := testCli.SetDomainSeo(testAuthorityDomain, &api.SeoSwitch{ + DirectlyOrigin: "ON", + PushRecord: "OFF", + }) + + checkClientErr(t, "SetDomainSeo", err) +} + +func TestGetDomainSeo(t *testing.T) { + seoSwitch, err := testCli.GetDomainSeo(testAuthorityDomain) + + data, _ := json.Marshal(seoSwitch) + t.Logf("seoSwitch: %s", string(data)) + checkClientErr(t, "GetDomainSeo", err) +} + +func TestGetCacheTTL(t *testing.T) { + cacheTTls, err := testCli.GetCacheTTL(testAuthorityDomain) + + data, _ := json.Marshal(cacheTTls) + t.Logf("cacheTTls: %s", string(data)) + checkClientErr(t, "GetCacheTTL", err) +} + +func TestSetCacheTTL(t *testing.T) { + err := testCli.SetCacheTTL(testAuthorityDomain, []api.CacheTTL{ + { + Type: "suffix", + Value: ".jpg", + TTL: 420000, + Weight: 30, + }, + { + Type: "suffix", + Value: ".mp4", + TTL: 10000, + }, + }) + + checkClientErr(t, "SetCacheTTL", err) +} + +func TestSetRefererACL(t *testing.T) { + // set white referer list + err := testCli.SetRefererACL(testAuthorityDomain, nil, []string{ + "a.bbbbbb.c", + "*.baidu.com.*", + }, true) + + checkClientErr(t, "SetRefererACL", err) + + // set black referer list + err = testCli.SetRefererACL(testAuthorityDomain, []string{ + "a.b.c", + "*.xxxxx.com.*", + }, nil, true) + checkClientErr(t, "SetRefererACL", err) +} + +func TestGetRefererACL(t *testing.T) { + refererACL, err := testCli.GetRefererACL(testAuthorityDomain) + data, _ := json.Marshal(refererACL) + t.Logf("refererACL: %s", string(data)) + checkClientErr(t, "GetRefererACL", err) +} + +func TestSetIpACL(t *testing.T) { + err := testCli.SetIpACL(testAuthorityDomain, []string{ + "5.5.5.5", + "6.6.6.6", + }, nil) + + checkClientErr(t, "SetIpACL", err) + + err = testCli.SetIpACL(testAuthorityDomain, nil, []string{ + "1.2.3.4/24", + }) + + checkClientErr(t, "SetIpACL", err) +} + +func TestGetIpACL(t *testing.T) { + ipACL, err := testCli.GetIpACL(testAuthorityDomain) + data, _ := json.Marshal(ipACL) + t.Logf("ipACL: %s", string(data)) + checkClientErr(t, "GetIpACL", err) +} + +func TestSetUaACL(t *testing.T) { + err := testCli.SetUaACL(testAuthorityDomain, []string{ + "Test-Bad-UA", + }, nil) + + checkClientErr(t, "SetUaACL", err) + + err = testCli.SetUaACL(testAuthorityDomain, nil, []string{ + "curl/7.73.0", + }) + + checkClientErr(t, "SetUaACL", err) +} + +func TestGetUaACL(t *testing.T) { + uaACL, err := testCli.GetUaACL(testAuthorityDomain) + data, _ := json.Marshal(uaACL) + t.Logf("uaACL: %s", string(data)) + checkClientErr(t, "GetUaACL", err) +} + +func TestSetTrafficLimit(t *testing.T) { + trafficLimit := &api.TrafficLimit{ + Enabled: false, + LimitRate: 10000, + LimitStartHour: 10, + LimitEndHour: 12, + TrafficLimitUnit: "k", + } + err := testCli.SetTrafficLimit(testAuthorityDomain, trafficLimit) + checkClientErr(t, "SetTrafficLimit", err) +} + +func TestGetTrafficLimit(t *testing.T) { + trafficLimit, err := testCli.GetTrafficLimit(testAuthorityDomain) + + data, _ := json.Marshal(trafficLimit) + t.Logf("trafficLimit: %s", string(data)) + checkClientErr(t, "GetTrafficLimit", err) +} + +func TestSetDomainHttps(t *testing.T) { + err := testCli.SetDomainHttps(testAuthorityDomain, &api.HTTPSConfig{ + Enabled: true, + CertId: "ssl-xxxxxx", + Http2Enabled: true, + HttpRedirect: true, + HttpRedirectCode: 301, + }) + + checkClientErr(t, "SetDomainHttps", err) +} + +func TestPutCert(t *testing.T) { + privateKey := "证书私钥数据" + certData := "证书内容(一般需要包含证书链信息)" + certId, err := testCli.PutCert(testAuthorityDomain, &api.UserCertificate{ + CertName: "test", + ServerData: certData, + PrivateData: privateKey, + }, "ON") + + t.Logf("TestPutCert got certId %s", certId) + checkClientErr(t, "TestPutCert", err) +} + +func TestGetCert(t *testing.T) { + detail, err := testCli.GetCert(testAuthorityDomain) + data, _ := json.Marshal(detail) + t.Logf("TestGetCert: %s", string(data)) + checkClientErr(t, "TestGetCert", err) +} + +func TestDeleteCert(t *testing.T) { + err := testCli.DeleteCert(testAuthorityDomain) + checkClientErr(t, "TestGetCert", err) +} + +func TestSetOCSP(t *testing.T) { + err := testCli.SetOCSP(testAuthorityDomain, false) + checkClientErr(t, "SetOCSP", err) +} + +func TestGetOCSP(t *testing.T) { + ocspSwitch, err := testCli.GetOCSP(testAuthorityDomain) + + t.Logf("ocspSwitch: %v", ocspSwitch) + checkClientErr(t, "GetOCSP", err) +} + +func TestSetDomainRequestAuth(t *testing.T) { + var err error + err = testCli.SetDomainRequestAuth(testAuthorityDomain, &api.RequestAuth{ + Type: "c", + Key1: "secretekey1", + Key2: "secretekey2", + Timeout: 1800, + WhiteList: []string{ + "/crossdomain.xml", + }, + SignArg: "sign", + TimeArg: "t", + TimestampFormat: "hex", + }) + checkClientErr(t, "SetDomainRequestAuth", err) + + err = testCli.SetDomainRequestAuth(testAuthorityDomain, &api.RequestAuth{ + Type: "b", + Key1: "secretekey1", + Key2: "secretekey2", + Timeout: 3600, + WhiteList: []string{ + "/crossdomain.xml", + }, + TimestampFormat: "yyyyMMDDhhmm", + }) + checkClientErr(t, "SetDomainRequestAuth", err) + + // Type A does not support TimestampMetric 'yyyyMMDDhhmm', SetDomainRequestAuth would return error. + err = testCli.SetDomainRequestAuth(testAuthorityDomain, &api.RequestAuth{ + Type: "a", + Key1: "secretekey1", + Key2: "secretekey2", + Timeout: 3600, + WhiteList: []string{ + "/crossdomain.xml", + }, + TimestampFormat: "yyyyMMDDhhmm", + }) + if err == nil { + t.Fatalf(`Type A support TimestampMetric 'yyyyMMDDhhmm' is unexpected`) + } +} + +func TestSetFollowProtocol(t *testing.T) { + err := testCli.SetFollowProtocol(testAuthorityDomain, true) + checkClientErr(t, "SetFollowProtocol", err) +} + +func TestSetHttpHeader(t *testing.T) { + err := testCli.SetHttpHeader(testAuthorityDomain, []api.HttpHeader{ + { + Type: "origin", + Header: "x-auth-cn", + Value: "xxxxxxxxx", + Action: "remove", + }, + { + Type: "response", + Header: "content-type", + Value: "application/octet-stream", + Action: "add", + }, + }) + + checkClientErr(t, "SetHttpHeader", err) +} + +func TestGetHttpHerder(t *testing.T) { + headers, err := testCli.GetHttpHeader(testAuthorityDomain) + + data, _ := json.Marshal(headers) + t.Logf("headers: %s", string(data)) + checkClientErr(t, "GetHttpHeader", err) +} + +func TestSetErrorPage(t *testing.T) { + err := testCli.SetErrorPage(testAuthorityDomain, []api.ErrorPage{ + { + Code: 510, + RedirectCode: 302, + Url: "/customer_404.html", + }, + { + Code: 403, + Url: "/custom_403.html", + }, + }) + + checkClientErr(t, "SetErrorPage", err) +} + +func TestGetErrorPage(t *testing.T) { + errorPages, err := testCli.GetErrorPage(testAuthorityDomain) + + data, _ := json.Marshal(errorPages) + t.Logf("errorPages: %s", string(data)) + checkClientErr(t, "GetErrorPage", err) +} + +func TestSetCacheCached(t *testing.T) { + err := testCli.SetCacheShared(testAuthorityDomain, &api.CacheShared{ + Enabled: false, + }) + checkClientErr(t, "SetCacheShared", err) +} + +func TestGetCacheCached(t *testing.T) { + cacheSharedConfig, err := testCli.GetCacheShared(testAuthorityDomain) + data, _ := json.Marshal(cacheSharedConfig) + t.Logf("cacheSharedConfig: %s", string(data)) + checkClientErr(t, "GetCacheShared", err) +} + +func TestSetMediaDrag(t *testing.T) { + err := testCli.SetMediaDrag(testAuthorityDomain, &api.MediaDragConf{ + Mp4: &api.MediaCfg{ + DragMode: "second", + FileSuffix: []string{ + "mp4", + "m4a", + "m4z", + }, + StartArgName: "startIndex", + }, + Flv: &api.MediaCfg{ + DragMode: "byteAV", + FileSuffix: []string{}, + }, + }) + + checkClientErr(t, "SetMediaDrag", err) +} + +func TestGetMediaDrag(t *testing.T) { + mediaDragConf, err := testCli.GetMediaDrag(testAuthorityDomain) + + data, _ := json.Marshal(mediaDragConf) + t.Logf("mediaDragConf: %s", string(data)) + checkClientErr(t, "GetMediaDrag", err) +} + +func TestSetFileTrim(t *testing.T) { + err := testCli.SetFileTrim(testAuthorityDomain, true) + checkClientErr(t, "SetFileTrim", err) +} + +func TestGetFileTrim(t *testing.T) { + fileTrim, err := testCli.GetFileTrim(testAuthorityDomain) + + t.Logf("fileTrim: %v", fileTrim) + checkClientErr(t, "GetFileTrim", err) +} + +func TestSetIPv6(t *testing.T) { + err := testCli.SetIPv6(testAuthorityDomain, false) + checkClientErr(t, "SetIPv6", err) +} + +func TestGetIPv6(t *testing.T) { + ipv6Switch, err := testCli.GetIPv6(testAuthorityDomain) + + t.Logf("ipv6Switch: %v", ipv6Switch) + checkClientErr(t, "GetIPv6", err) +} + +func TestSetQUIC(t *testing.T) { + err := testCli.SetQUIC(testAuthorityDomain, false) + checkClientErr(t, "SetQUIC", err) +} + +func TestGetQUIC(t *testing.T) { + quicSwitch, err := testCli.GetQUIC(testAuthorityDomain) + + t.Logf("quicSwitch: %v", quicSwitch) + checkClientErr(t, "GetQUIC", err) +} + +func TestSetOfflineMode(t *testing.T) { + err := testCli.SetOfflineMode(testAuthorityDomain, true) + checkClientErr(t, "SetOfflineMode", err) +} + +func TestGetOfflineMode(t *testing.T) { + offlineMode, err := testCli.GetOfflineMode(testAuthorityDomain) + + t.Logf("offlineMode: %v", offlineMode) + checkClientErr(t, "GetOfflineMode", err) +} + +func TestSetMobileAccess(t *testing.T) { + err := testCli.SetMobileAccess(testAuthorityDomain, true) + checkClientErr(t, "SetMobileAccess", err) +} + +func TestGetMobileAccess(t *testing.T) { + distinguishClient, err := testCli.GetMobileAccess(testAuthorityDomain) + + t.Logf("distinguishClient: %v", distinguishClient) + checkClientErr(t, "GetMobileAccess", err) +} + +func TestSetClientIp(t *testing.T) { + err := testCli.SetClientIp(testAuthorityDomain, &api.ClientIp{ + Enabled: true, + Name: "X-Real-IP", + }) + + checkClientErr(t, "SetClientIp", err) +} + +func TestGetClientIp(t *testing.T) { + clientIp, err := testCli.GetClientIp(testAuthorityDomain) + + data, _ := json.Marshal(clientIp) + t.Logf("clientIp: %s", data) + checkClientErr(t, "GetClientIp", err) +} + +func TestSetRetryOrigin(t *testing.T) { + err := testCli.SetRetryOrigin(testAuthorityDomain, &api.RetryOrigin{ + Codes: []int{429, 500, 502, 503}, + }) + + checkClientErr(t, "SetRetryOrigin", err) +} + +func TestGetRetryOrigin(t *testing.T) { + retryOrigin, err := testCli.GetRetryOrigin(testAuthorityDomain) + + data, _ := json.Marshal(retryOrigin) + t.Logf("retryOrigin: %s", data) + checkClientErr(t, "GetRetryOrigin", err) +} + +func TestSetAccessLimit(t *testing.T) { + err := testCli.SetAccessLimit(testAuthorityDomain, &api.AccessLimit{ + Enabled: true, + Limit: 200, + }) + + checkClientErr(t, "SetAccessLimit", err) +} + +func TestGetAccessLimit(t *testing.T) { + accessLimit, err := testCli.GetAccessLimit(testAuthorityDomain) + + data, _ := json.Marshal(accessLimit) + t.Logf("accessLimit: %s", data) + checkClientErr(t, "GetAccessLimit", err) +} + +func TestSetCacheUrlArgs(t *testing.T) { + err := testCli.SetCacheUrlArgs(testAuthorityDomain, &api.CacheUrlArgs{ + CacheFullUrl: false, + CacheUrlArgs: []string{"1", "2"}, + }) + + checkClientErr(t, "SetCacheUrlArgs", err) +} + +func TestGetCacheUrlArgs(t *testing.T) { + cacheUrlArgs, err := testCli.GetCacheUrlArgs(testAuthorityDomain) + + data, _ := json.Marshal(cacheUrlArgs) + t.Logf("cacheUrlArgs: %s", string(data)) + checkClientErr(t, "GetCacheUrlArgs", err) +} + +func TestSetCors(t *testing.T) { + err := testCli.SetCors(testAuthorityDomain, true, []string{ + "http://www.baidu.com", + "http://*.bce.com", + }) + + checkClientErr(t, "SetCors", err) +} + +func TestGetCors(t *testing.T) { + cors, err := testCli.GetCors(testAuthorityDomain) + + data, _ := json.Marshal(cors) + t.Logf("cors: %s", string(data)) + checkClientErr(t, "GetCors", err) +} + +func TestSetRangeSwitch(t *testing.T) { + err := testCli.SetRangeSwitch(testAuthorityDomain, false) + + checkClientErr(t, "SetRangeSwitch", err) +} + +func TestGetRangeSwitch(t *testing.T) { + rangeSwitch, err := testCli.GetRangeSwitch(testAuthorityDomain) + + t.Logf("rangeSwitch: %+v", rangeSwitch) + checkClientErr(t, "GetRangeSwitch", err) +} + +func TestSetContentEncoding(t *testing.T) { + err := testCli.SetContentEncoding(testAuthorityDomain, true, "br") + checkClientErr(t, "SetContentEncoding", err) +} + +func TestGetContentEncoding(t *testing.T) { + contentEncoding, err := testCli.GetContentEncoding(testAuthorityDomain) + t.Logf("contentEncoding: %+v", contentEncoding) + checkClientErr(t, "GetContentEncoding", err) +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Test function about purge/prefetch. +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +func TestPurge(t *testing.T) { + purgedId, err := testCli.Purge([]api.PurgeTask{ + { + Url: "http://my.domain.com/path/to/purge/2.data", + }, + { + Url: "http://my.domain.com/path/to/purege/html/", + Type: "directory", + }, + }) + + t.Logf("purgedId: %s", string(purgedId)) + checkClientErr(t, "Purge", err) +} + +func TestGetPurgedStatus(t *testing.T) { + purgedStatus, err := testCli.GetPurgedStatus(nil) + + data, _ := json.Marshal(purgedStatus) + t.Logf("purgedStatus: %s", string(data)) + checkClientErr(t, "GetPurgedStatus", err) +} + +func TestPrefetch(t *testing.T) { + prefetchId, err := testCli.Prefetch([]api.PrefetchTask{ + { + Url: "http://my.domain.com/path/to/purge/1.data", + }, + }) + + t.Logf("prefetchId: %s", string(prefetchId)) + checkClientErr(t, "Prefetch", err) +} + +func TestGetPrefetchStatus(t *testing.T) { + prefetchStatus, err := testCli.GetPrefetchStatus(nil) + + data, _ := json.Marshal(prefetchStatus) + t.Logf("prefetchStatus: %s", string(data)) + checkClientErr(t, "GetPrefetchStatus", err) +} + +func TestGetQuota(t *testing.T) { + quotaDetail, err := testCli.GetQuota() + + data, _ := json.Marshal(quotaDetail) + t.Logf("quotaDetail: %s", string(data)) + checkClientErr(t, "GetQuota", err) +} + +func TestGetCacheOpRecords(t *testing.T) { + recordDetails, err := testCli.GetCacheOpRecords(&api.CRecordQueryData{ + StartTime: "2019-08-12T12:00:00Z", + EndTime: "2019-08-14T12:00:00Z", + }) + data, _ := json.Marshal(recordDetails) + t.Logf("GetCacheOpRecords: %s", string(data)) + checkClientErr(t, "GetCacheOpRecords", err) +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Test function about DSA. +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +func TestEnableDsa(t *testing.T) { + err := testCli.EnableDsa() + checkClientErr(t, "EnableDsa", err) +} + +func TestDisableDsa(t *testing.T) { + err := testCli.DisableDsa() + checkClientErr(t, "DisableDsa", err) +} + +func TestListDsaDomains(t *testing.T) { + dsaDomains, err := testCli.ListDsaDomains() + data, _ := json.Marshal(dsaDomains) + fmt.Println(string(data)) + checkClientErr(t, "ListDsaDomains", err) +} + +func TestSetDsaConfig(t *testing.T) { + err := testCli.SetDsaConfig(testAuthorityDomain, &api.DSAConfig{ + Enabled: true, + Rules: []api.DSARule{ + { + Type: "suffix", + Value: ".mp4;.jpg;.php", + }, + { + Type: "path", + Value: "/path", + }, + { + Type: "exactPath", + Value: "/path/to/file.mp4", + }, + }, + Comment: "test", + }) + + checkClientErr(t, "SetDsaConfig", err) +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Test function about log. +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +func TestGetDomainLog(t *testing.T) { + endTs := time.Now().Unix() + startTs := endTs - 24*60*60 + endTime := util.FormatISO8601Date(endTs) + startTime := util.FormatISO8601Date(startTs) + domainLogs, err := testCli.GetDomainLog(testAuthorityDomain, api.TimeInterval{ + StartTime: startTime, + EndTime: endTime, + }) + + data, _ := json.Marshal(domainLogs) + t.Logf("domainLogs: %s", string(data)) + checkClientErr(t, "GetDomainLog", err) +} + +func TestGetMultiDomainLog(t *testing.T) { + endTs := time.Now().Unix() + startTs := endTs - 24*60*60 + endTime := util.FormatISO8601Date(endTs) + startTime := util.FormatISO8601Date(startTs) + + domainLogs, err := testCli.GetMultiDomainLog(&api.LogQueryData{ + TimeInterval: api.TimeInterval{ + StartTime: startTime, + EndTime: endTime, + }, + Type: 1, + Domains: []string{"1.baidu.com", "2.baidu.com"}, + }) + + data, _ := json.Marshal(domainLogs) + t.Logf("domainLogs: %s", string(data)) + checkClientErr(t, "GetMultiDomainLog", err) +} + +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +// Test function about query statistics. +// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// +func TestGetAvgSpeed(t *testing.T) { + queryCondition := &api.QueryCondition{} + avgSpeedDetails, err := testCli.GetAvgSpeed(queryCondition) + + data, _ := json.Marshal(avgSpeedDetails) + t.Logf("avgSpeedDetails: %s", string(data)) + checkClientErr(t, "GetAvgSpeed", err) +} + +func TestGetAvgSpeedByRegion(t *testing.T) { + queryCondition := &api.QueryCondition{} + avgSpeedDetails, err := testCli.GetAvgSpeedByRegion(queryCondition, "beijing", "") + + data, _ := json.Marshal(avgSpeedDetails) + t.Logf("avgSpeedDetails: %s", string(data)) + checkClientErr(t, "GetAvgSpeedByRegion", err) +} + +func TestGetPv(t *testing.T) { + queryCondition := &api.QueryCondition{} + pvDetails, err := testCli.GetPv(queryCondition, "all") + + data, _ := json.Marshal(pvDetails) + t.Logf("pvDetails: %s", string(data)) + checkClientErr(t, "GetPv", err) +} + +func TestGetSrcPv(t *testing.T) { + queryCondition := &api.QueryCondition{} + pvDetails, err := testCli.GetSrcPv(queryCondition) + + data, _ := json.Marshal(pvDetails) + t.Logf("pvDetails: %s", string(data)) + checkClientErr(t, "GetSrcPv", err) +} + +func TestGetPvInRegion(t *testing.T) { + queryCondition := &api.QueryCondition{} + pvRegionDetails, err := testCli.GetPvByRegion(queryCondition, "beijing", "") + + data, _ := json.Marshal(pvRegionDetails) + t.Logf("pvRegionDetails: %s", string(data)) + checkClientErr(t, "GetPvByRegion", err) +} + +func TestGetUv(t *testing.T) { + queryCondition := &api.QueryCondition{} + uvDetails, err := testCli.GetUv(queryCondition) + + data, _ := json.Marshal(uvDetails) + t.Logf("uvDetails: %s", string(data)) + checkClientErr(t, "GetUv", err) +} + +func TestGetFlow(t *testing.T) { + queryCondition := &api.QueryCondition{ + StartTime: "2019-06-16T16:00:00Z", + EndTime: "2019-06-19T16:00:00Z", + Period: 86400, + KeyType: 0, + Key: []string{testAuthorityDomain}, + GroupBy: "key", + } + flowDetails, err := testCli.GetFlow(queryCondition, "all") + + data, _ := json.Marshal(flowDetails) + t.Logf("flowDetails: %s", string(data)) + checkClientErr(t, "GetFlow", err) +} + +func TestGetFlowByProtocol(t *testing.T) { + queryCondition := &api.QueryCondition{} + flowDetails, err := testCli.GetFlowByProtocol(queryCondition, "all") + + data, _ := json.Marshal(flowDetails) + t.Logf("flowDetails: %s", string(data)) + checkClientErr(t, "GetFlowByProtocol", err) +} + +func TestGetFlowByRegion(t *testing.T) { + queryCondition := &api.QueryCondition{} + flowRegionDetails, err := testCli.GetFlowByRegion(queryCondition, "beijing", "") + + data, _ := json.Marshal(flowRegionDetails) + t.Logf("flowRegionDetails: %s", string(data)) + checkClientErr(t, "GetFlowByRegion", err) +} + +func TestGetSrcFlow(t *testing.T) { + queryCondition := &api.QueryCondition{} + flowDetails, err := testCli.GetSrcFlow(queryCondition) + + data, _ := json.Marshal(flowDetails) + t.Logf("flowDetails: %s", string(data)) + checkClientErr(t, "GetFlowByRegion", err) +} + +func TestGetRealHit(t *testing.T) { + queryCondition := &api.QueryCondition{} + hitDetails, err := testCli.GetRealHit(queryCondition) + + data, _ := json.Marshal(hitDetails) + t.Logf("hitDetails: %s", string(data)) + checkClientErr(t, "GetRealHit", err) +} + +func TestGetPvHit(t *testing.T) { + queryCondition := &api.QueryCondition{} + hitDetails, err := testCli.GetPvHit(queryCondition) + + data, _ := json.Marshal(hitDetails) + t.Logf("hitDetails: %s", string(data)) + checkClientErr(t, "GetPvHit", err) +} + +func TestGetHttpCode(t *testing.T) { + queryCondition := &api.QueryCondition{} + httpCodeDetails, err := testCli.GetHttpCode(queryCondition) + + data, _ := json.Marshal(httpCodeDetails) + t.Logf("httpCodeDetails: %s", string(data)) + checkClientErr(t, "GetHttpCode", err) +} + +func TestGetSrcHttpCode(t *testing.T) { + queryCondition := &api.QueryCondition{} + httpCodeDetails, err := testCli.GetSrcHttpCode(queryCondition) + + data, _ := json.Marshal(httpCodeDetails) + t.Logf("httpCodeDetails: %s", string(data)) + checkClientErr(t, "GetSrcHttpCode", err) +} + +func TestGetHttpCodeByRegion(t *testing.T) { + queryCondition := &api.QueryCondition{} + httpCodeDetails, err := testCli.GetHttpCodeByRegion(queryCondition, "beijing", "") + + data, _ := json.Marshal(httpCodeDetails) + t.Logf("httpCodeDetails: %s", string(data)) + checkClientErr(t, "GetHttpCodeByRegion", err) +} + +func TestGetTopNUrls(t *testing.T) { + queryCondition := &api.QueryCondition{} + topNUrls, err := testCli.GetTopNUrls(queryCondition, "200") + + data, _ := json.Marshal(topNUrls) + t.Logf("topNUrls: %s", string(data)) + checkClientErr(t, "GetTopNUrls", err) +} + +func TestGetTopNReferers(t *testing.T) { + queryCondition := &api.QueryCondition{} + topNReferers, err := testCli.GetTopNReferers(queryCondition, "") + + data, _ := json.Marshal(topNReferers) + t.Logf("topNReferers: %s", string(data)) + checkClientErr(t, "GetTopNReferers", err) +} + +func TestGetTopNDomains(t *testing.T) { + queryCondition := &api.QueryCondition{} + topNDomains, err := testCli.GetTopNDomains(queryCondition, "") + + data, _ := json.Marshal(topNDomains) + t.Logf("topNDomains: %s", string(data)) + checkClientErr(t, "GetTopNDomains", err) +} + +func TestGetError(t *testing.T) { + queryCondition := &api.QueryCondition{} + errorDetails, err := testCli.GetError(queryCondition) + + data, _ := json.Marshal(errorDetails) + t.Logf("errorDetails: %s", string(data)) + checkClientErr(t, "GetErrorCount", err) +} + +func TestGetPeak95Bandwidth(t *testing.T) { + peak95Time, peak95Band, err := testCli.GetPeak95Bandwidth( + "2020-05-01T00:00:00Z", "2020-05-10T00:00:00Z", []string{"www.test.com"}, nil) + t.Logf("peak95Time %s, peak95Band %d", peak95Time, peak95Band) + checkClientErr(t, "TestGetPeak95Bandwidth", err) +} diff --git a/bce-sdk-go/services/cert/cert.go b/bce-sdk-go/services/cert/cert.go new file mode 100644 index 0000000..2b78978 --- /dev/null +++ b/bce-sdk-go/services/cert/cert.go @@ -0,0 +1,164 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// cert.go - the certificate APIs definition supported by the Cert service +package cert + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateCert - create a cert with the specific parameters +// +// PARAMS: +// - args: the arguments to create a cert +// +// RETURNS: +// - *CreateCertResult: the result of create Cert, contains new Cert's ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateCert(args *CreateCertArgs) (*CreateCertResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.CertName == "" { + return nil, fmt.Errorf("unset CertName") + } + + if args.CertServerData == "" { + return nil, fmt.Errorf("unset CertServerData") + } + + if args.CertPrivateData == "" { + return nil, fmt.Errorf("unset CertPrivateData") + } + + result := &CreateCertResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getCertUri()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateCertName - update a cert's name +// +// PARAMS: +// - id: the specific cert's ID +// - args: the arguments to update a cert's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateCertName(id string, args *UpdateCertNameArgs) error { + if args == nil || args.CertName == "" { + return fmt.Errorf("unset CertName") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getCertUriWithId(id)). + WithQueryParam("certName", ""). + WithBody(args). + Do() +} + +// ListCerts - list all certs +// +// RETURNS: +// - *ListCertResult: the result of list all certs, contains all certs' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListCerts() (*ListCertResult, error) { + result := &ListCertResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getCertUri()). + WithResult(result). + Do() + + return result, err +} + +// GetCertMeta - get a specific cert's meta +// +// PARAMS: +// - id: the specific cert's ID +// +// RETURNS: +// - *CertificateMeta: the specific cert's meta with +// - error: nil if success otherwise the specific error +func (c *Client) GetCertMeta(id string) (*CertificateMeta, error) { + result := &CertificateMeta{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getCertUriWithId(id)). + WithResult(result). + Do() + + return result, err +} + +// DeleteCert - delete a specific cert +// +// PARAMS: +// - id: the specific cert's ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteCert(id string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getCertUriWithId(id)). + Do() +} + +// UpdateCertData - update a specific cert's data, include update key +// +// PARAMS: +// - id: the specific cert's ID +// - args: the arguments to update a specific cert +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateCertData(id string, args *UpdateCertDataArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.CertName == "" { + return fmt.Errorf("unset CertName") + } + + if args.CertServerData == "" { + return fmt.Errorf("unset CertServerData") + } + + if args.CertPrivateData == "" { + return fmt.Errorf("unset CertPrivateData") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getCertUriWithId(id)). + WithQueryParam("certData", ""). + WithBody(args). + Do() + + return err +} diff --git a/bce-sdk-go/services/cert/client.go b/bce-sdk-go/services/cert/client.go new file mode 100644 index 0000000..cf81967 --- /dev/null +++ b/bce-sdk-go/services/cert/client.go @@ -0,0 +1,50 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for Cert service + +// Package cert defines the Cert services of BCE. The supported APIs are all defined in sub-package +package cert + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + DEFAULT_ENDPOINT = "certificate.baidubce.com" + REQUEST_CERT_URL = "/certificate" +) + +// Client of Cert service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getCertUri() string { + return URI_PREFIX + REQUEST_CERT_URL +} + +func getCertUriWithId(id string) string { + return URI_PREFIX + REQUEST_CERT_URL + "/" + id +} diff --git a/bce-sdk-go/services/cert/client_test.go b/bce-sdk-go/services/cert/client_test.go new file mode 100644 index 0000000..4594855 --- /dev/null +++ b/bce-sdk-go/services/cert/client_test.go @@ -0,0 +1,124 @@ +package cert + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + CERT_CLIENT *Client + CERT_ID string + + // set these values before start test + testCertServerData = `` + testCertPrivateData = `` + + testUpdateCertServerData = `` + testUpdateCertPrivateData = `` +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + CERT_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateCert(t *testing.T) { + args := &CreateCertArgs{ + CertName: "sdkCreateTest", + CertServerData: testCertServerData, + CertPrivateData: testCertPrivateData, + } + createResult, err := CERT_CLIENT.CreateCert(args) + ExpectEqual(t.Errorf, nil, err) + + CERT_ID = createResult.CertId +} + +func TestClient_ListCerts(t *testing.T) { + _, err := CERT_CLIENT.ListCerts() + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetCertMeta(t *testing.T) { + result, err := CERT_CLIENT.GetCertMeta(CERT_ID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "sdkCreateTest", result.CertName) + ExpectEqual(t.Errorf, 1, result.CertType) +} + +func TestClient_UpdateCertName(t *testing.T) { + args := &UpdateCertNameArgs{ + CertName: "sdkUpdateNameTest", + } + err := CERT_CLIENT.UpdateCertName(CERT_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateCertData(t *testing.T) { + args := &UpdateCertDataArgs{ + CertName: "sdkTest", + CertServerData: testUpdateCertServerData, + CertPrivateData: testUpdateCertPrivateData, + } + err := CERT_CLIENT.UpdateCertData(CERT_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteCert(t *testing.T) { + err := CERT_CLIENT.DeleteCert(CERT_ID) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/cert/model.go b/bce-sdk-go/services/cert/model.go new file mode 100644 index 0000000..edeb463 --- /dev/null +++ b/bce-sdk-go/services/cert/model.go @@ -0,0 +1,57 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package cert + +type CreateCertArgs struct { + CertName string `json:"certName"` + CertServerData string `json:"certServerData"` + CertPrivateData string `json:"certPrivateData"` + CertLinkData string `json:"certLinkData,omitempty"` + CertType int `json:"certType,omitempty"` +} + +type CreateCertResult struct { + CertName string `json:"certName"` + CertId string `json:"certId"` +} + +type UpdateCertNameArgs struct { + CertName string `json:"certName"` +} + +type CertificateMeta struct { + CertId string `json:"certId"` + CertName string `json:"certName"` + CertCommonName string `json:"certCommonName"` + CertStartTime string `json:"certStartTime"` + CertStopTime string `json:"certStopTime"` + CertCreateTime string `json:"certCreateTime"` + CertUpdateTime string `json:"certUpdateTime"` + CertType int `json:"certType"` +} + +type ListCertResult struct { + Certs []CertificateMeta `json:"certs"` +} + +type UpdateCertDataArgs struct { + CertName string `json:"certName"` + CertServerData string `json:"certServerData"` + CertPrivateData string `json:"certPrivateData"` + CertLinkData string `json:"certLinkData,omitempty"` + CertType int `json:"certType,omitempty"` +} diff --git a/bce-sdk-go/services/cfc/api/cfc.go b/bce-sdk-go/services/cfc/api/cfc.go new file mode 100644 index 0000000..b8c3de0 --- /dev/null +++ b/bce-sdk-go/services/cfc/api/cfc.go @@ -0,0 +1,762 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 api + +import ( + "encoding/base64" + "encoding/json" + "io/ioutil" + "reflect" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func ListFunctions(cli bce.Client, args *ListFunctionsArgs) (*ListFunctionsResult, error) { + op := &Operation{ + HTTPUri: getFunctionsUri(), + HTTPMethod: GET, + } + + if args.MaxItems <= 0 { + args.MaxItems = 10000 + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "FunctionVersion": args.FunctionVersion, + "Marker": args.Marker, + "MaxItems": args.MaxItems, + }, + } + result := &cfcResult{ + Result: &ListFunctionsResult{}, + } + + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListFunctionsResult); ok { + return value, nil + } + return nil, nil +} + +func GetFunction(cli bce.Client, args *GetFunctionArgs) (*GetFunctionResult, error) { + op := &Operation{ + HTTPUri: getFunctionUri(args.FunctionName), + HTTPMethod: GET, + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "Qualifier": args.Qualifier, + }, + } + result := &cfcResult{ + Result: &GetFunctionResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*GetFunctionResult); ok { + return value, nil + } + return nil, nil +} + +func CreateFunction(cli bce.Client, args *CreateFunctionArgs) (*CreateFunctionResult, error) { + op := &Operation{ + HTTPUri: getFunctionsUri(), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &CreateFunctionResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*CreateFunctionResult); ok { + return value, nil + } + return nil, nil +} + +func CreateFunctionByBlueprint(cli bce.Client, args *CreateFunctionByBlueprintArgs) (*CreateFunctionResult, error) { + op := &Operation{ + HTTPUri: getBlueprintUri(args.BlueprintID), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &CreateFunctionResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*CreateFunctionResult); ok { + return value, nil + } + return nil, nil +} + +func DeleteFunction(cli bce.Client, args *DeleteFunctionArgs) error { + op := &Operation{ + HTTPUri: getFunctionUri(args.FunctionName), + HTTPMethod: DELETE, + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "Qualifier": args.Qualifier, + }, + } + result := &cfcResult{ + Result: nil, + } + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} + +func UpdateFunctionCode(cli bce.Client, args *UpdateFunctionCodeArgs) (*UpdateFunctionCodeResult, error) { + op := &Operation{ + HTTPUri: getFunctionCodeUri(args.FunctionName), + HTTPMethod: PUT, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &UpdateFunctionCodeResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*UpdateFunctionCodeResult); ok { + return value, nil + } + return nil, nil +} + +func GetFunctionConfiguration(cli bce.Client, args *GetFunctionConfigurationArgs) (*GetFunctionConfigurationResult, error) { + op := &Operation{ + HTTPUri: getFunctionConfigurationUri(args.FunctionName), + HTTPMethod: GET, + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "Qualifier": args.Qualifier, + }, + } + result := &cfcResult{ + Result: &GetFunctionConfigurationResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*GetFunctionConfigurationResult); ok { + return value, nil + } + return nil, nil +} + +func UpdateFunctionConfiguration(cli bce.Client, args *UpdateFunctionConfigurationArgs) (*UpdateFunctionConfigurationResult, error) { + op := &Operation{ + HTTPUri: getFunctionConfigurationUri(args.FunctionName), + HTTPMethod: PUT, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &UpdateFunctionConfigurationResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*UpdateFunctionConfigurationResult); ok { + return value, nil + } + return nil, nil +} + +func SetReservedConcurrentExecutions(cli bce.Client, args *ReservedConcurrentExecutionsArgs) error { + op := &Operation{ + HTTPUri: getFunctionConCurrentUri(args.FunctionName), + HTTPMethod: PUT, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: nil, + } + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} + +func DeleteReservedConcurrentExecutions(cli bce.Client, args *DeleteReservedConcurrentExecutionsArgs) error { + op := &Operation{ + HTTPUri: getFunctionConCurrentUri(args.FunctionName), + HTTPMethod: DELETE, + } + request := &cfcRequest{ + Args: args, + } + result := &cfcResult{} + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} + +func Invocations(cli bce.Client, args *InvocationsArgs) (*InvocationsResult, error) { + if err := args.Validate(); err != nil { + return nil, err + } + if len(args.InvocationType) == 0 { + args.InvocationType = InvocationTypeRequestResponse + } + if len(args.LogType) == 0 { + args.LogType = LogTypeNone + } + + req := &bce.BceRequest{} + req.SetRequestId(args.RequestId) + req.SetUri(getInvocationsUri(args.FunctionName)) + req.SetMethod(http.POST) + req.SetParam("invocationType", string(args.InvocationType)) + req.SetParam("logType", string(args.LogType)) + if args.Qualifier != "" { + req.SetParam("qualifier", args.Qualifier) + } + + if args.Payload != nil { + var payloadBytes []byte + var err error + switch args.Payload.(type) { + case string: + payloadBytes = []byte(args.Payload.(string)) + case []byte: + payloadBytes = args.Payload.([]byte) + default: + payloadBytes, err = json.Marshal(args.Payload) + if err != nil { + return nil, err + } + } + var js interface{} + if json.Unmarshal([]byte(payloadBytes), &js) != nil { + return nil, ParseJsonError + } + requestBody, err := bce.NewBodyFromBytes(payloadBytes) + if err != nil { + return nil, err + } + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(requestBody) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + defer resp.Body().Close() + if resp.IsFail() { + return nil, resp.ServiceError() + } + body, err := ioutil.ReadAll(resp.Body()) + if err != nil { + return nil, err + } + result := &InvocationsResult{ + Payload: string(body), + } + errorStr := resp.Header("x-bce-function-error") + if len(errorStr) > 0 { + result.FunctionError = errorStr + } + logResult := resp.Header("x-bce-log-result") + if len(logResult) > 0 { + decodeBytes, err := base64.StdEncoding.DecodeString(string(logResult)) + if err != nil { + return nil, err + } + result.LogResult = string(decodeBytes) + } + return result, nil +} + +func ListVersionsByFunction(cli bce.Client, args *ListVersionsByFunctionArgs) (*ListVersionsByFunctionResult, error) { + op := &Operation{ + HTTPUri: getFunctionVersionsUri(args.FunctionName), + HTTPMethod: GET, + } + if args.MaxItems <= 0 { + args.MaxItems = 10000 + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "Marker": args.Marker, + "MaxItems": args.MaxItems, + }, + } + result := &cfcResult{ + Result: &ListVersionsByFunctionResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListVersionsByFunctionResult); ok { + return value, nil + } + return nil, nil +} + +func PublishVersion(cli bce.Client, args *PublishVersionArgs) (*PublishVersionResult, error) { + op := &Operation{ + HTTPUri: getFunctionVersionsUri(args.FunctionName), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: map[string]interface{}{ + "Description": args.Description, + "CodeSha256": args.CodeSha256, + }, + } + result := &cfcResult{ + Result: &PublishVersionResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*PublishVersionResult); ok { + return value, nil + } + return nil, nil +} + +func ListAliases(cli bce.Client, args *ListAliasesArgs) (*ListAliasesResult, error) { + op := &Operation{ + HTTPUri: getFunctionAliasesUri(args.FunctionName), + HTTPMethod: GET, + } + if args.MaxItems <= 0 { + args.MaxItems = 10000 + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "FunctionVersion": args.FunctionVersion, + "Marker": args.Marker, + "MaxItems": args.MaxItems, + }, + } + result := &cfcResult{ + Result: &ListAliasesResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListAliasesResult); ok { + return value, nil + } + return nil, nil +} + +func CreateAlias(cli bce.Client, args *CreateAliasArgs) (*CreateAliasResult, error) { + op := &Operation{ + HTTPUri: getFunctionAliasesUri(args.FunctionName), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: map[string]interface{}{ + "FunctionVersion": args.FunctionVersion, + "Name": args.Name, + "Description": args.Description, + }, + } + result := &cfcResult{ + Result: &CreateAliasResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*CreateAliasResult); ok { + return value, nil + } + return nil, nil +} + +func GetAlias(cli bce.Client, args *GetAliasArgs) (*GetAliasResult, error) { + op := &Operation{ + HTTPUri: getFunctionAliasUri(args.FunctionName, args.AliasName), + HTTPMethod: GET, + } + request := &cfcRequest{ + Args: args, + } + result := &cfcResult{ + Result: &GetAliasResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*GetAliasResult); ok { + return value, nil + } + return nil, nil +} + +func UpdateAlias(cli bce.Client, args *UpdateAliasArgs) (*UpdateAliasResult, error) { + op := &Operation{ + HTTPUri: getFunctionAliasUri(args.FunctionName, args.AliasName), + HTTPMethod: PUT, + } + request := &cfcRequest{ + Args: args, + Body: map[string]interface{}{ + "FunctionVersion": args.FunctionVersion, + "Description": args.Description, + }, + } + result := &cfcResult{ + Result: &UpdateAliasResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*UpdateAliasResult); ok { + return value, nil + } + return nil, nil +} + +func DeleteAlias(cli bce.Client, args *DeleteAliasArgs) error { + op := &Operation{ + HTTPUri: getFunctionAliasUri(args.FunctionName, args.AliasName), + HTTPMethod: DELETE, + } + request := &cfcRequest{ + Args: args, + } + result := &cfcResult{} + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} + +func ListTriggers(cli bce.Client, args *ListTriggersArgs) (*ListTriggersResult, error) { + op := &Operation{ + HTTPUri: getTriggerUri(), + HTTPMethod: GET, + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "FunctionBrn": args.FunctionBrn, + "ScopeType": args.ScopeType, + }, + } + result := &cfcResult{ + Result: &ListTriggersResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListTriggersResult); ok { + return value, nil + } + return nil, nil +} + +func CreateTrigger(cli bce.Client, args *CreateTriggerArgs) (*CreateTriggerResult, error) { + op := &Operation{ + HTTPUri: getTriggerUri(), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &CreateTriggerResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*CreateTriggerResult); ok { + return value, nil + } + return nil, nil + +} + +func UpdateTrigger(cli bce.Client, args *UpdateTriggerArgs) (*UpdateTriggerResult, error) { + op := &Operation{ + HTTPUri: getTriggerUri(), + HTTPMethod: PUT, + } + request := &cfcRequest{ + Args: args, + Body: map[string]interface{}{ + "RelationId": args.RelationId, + "Target": args.Target, + "Source": args.Source, + "Data": args.Data, + }, + } + result := &cfcResult{ + Result: &UpdateTriggerResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*UpdateTriggerResult); ok { + return value, nil + } + return nil, nil +} + +func DeleteTrigger(cli bce.Client, args *DeleteTriggerArgs) error { + op := &Operation{ + HTTPUri: getTriggerUri(), + HTTPMethod: DELETE, + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "RelationId": args.RelationId, + "Target": args.Target, + "Source": string(args.Source), + }, + } + result := &cfcResult{} + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} + +func caller(cli bce.Client, op *Operation, request *cfcRequest, response *cfcResult) error { + if request.Args != nil { + if err := request.Args.(Validator).Validate(); err != nil { + return err + } + } + req := new(bce.BceRequest) + if op.HTTPUri == "" { + return URIIllegal + } + req.SetUri(op.HTTPUri) + if op.HTTPMethod == "" { + return MethodIllegal + } + req.SetMethod(op.HTTPMethod) + if request.Params != nil { + for key, value := range request.Params { + rv := reflect.ValueOf(value) + switch rv.Kind() { + case reflect.String: + req.SetParam(key, value.(string)) + case reflect.Int: + req.SetParam(key, strconv.Itoa(value.(int))) + case reflect.Struct: + if valueBytes, err := json.Marshal(value); err != nil { + req.SetParam(key, string(valueBytes)) + } + } + } + } + if request.Body != nil { + argsBytes, err := json.Marshal(request.Body) + if err != nil { + return err + } + requestBody, err := bce.NewBodyFromBytes(argsBytes) + if err != nil { + return err + } + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(requestBody) + } + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + defer resp.Body().Close() + if resp.IsFail() { + return resp.ServiceError() + } + + if response.Result != nil { + if err := resp.ParseJsonBody(response.Result); err != nil { + return err + } + } + return nil +} + +// ListEventSource +func ListEventSource(cli bce.Client, args *ListEventSourceArgs) (*ListEventSourceResult, error) { + op := &Operation{ + HTTPUri: getEventSourceUri(), + HTTPMethod: GET, + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "FunctionName": args.FunctionName, + "Marker": args.Marker, + "MaxItems": args.MaxItems, + }, + } + result := &cfcResult{ + Result: &ListEventSourceResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListEventSourceResult); ok { + return value, nil + } + return nil, nil +} + +// GetEventSource +func GetEventSource(cli bce.Client, args *GetEventSourceArgs) (*GetEventSourceResult, error) { + op := &Operation{ + HTTPUri: getOneEventSourceUri(args.UUID), + HTTPMethod: GET, + } + request := &cfcRequest{ + Args: args, + } + result := &cfcResult{ + Result: &GetEventSourceResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*GetEventSourceResult); ok { + return value, nil + } + return nil, nil +} + +// CreateEventSource +func CreateEventSource(cli bce.Client, args *CreateEventSourceArgs) (*CreateEventSourceResult, error) { + op := &Operation{ + HTTPUri: getEventSourceUri(), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &CreateEventSourceResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*CreateEventSourceResult); ok { + return value, nil + } + return nil, nil +} + +// UpdateEventSource +func UpdateEventSource(cli bce.Client, args *UpdateEventSourceArgs) (*UpdateEventSourceResult, error) { + op := &Operation{ + HTTPUri: getOneEventSourceUri(args.UUID), + HTTPMethod: PUT, + } + request := &cfcRequest{ + Args: args, + Body: args.FuncEventSource, + } + result := &cfcResult{ + Result: &UpdateEventSourceResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*UpdateEventSourceResult); ok { + return value, nil + } + return nil, nil +} + +func DeleteEventSource(cli bce.Client, args *DeleteEventSourceArgs) error { + op := &Operation{ + HTTPUri: getOneEventSourceUri(args.UUID), + HTTPMethod: DELETE, + } + request := &cfcRequest{ + Args: args, + } + result := &cfcResult{} + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} diff --git a/bce-sdk-go/services/cfc/api/errors.go b/bce-sdk-go/services/cfc/api/errors.go new file mode 100644 index 0000000..4ec13bc --- /dev/null +++ b/bce-sdk-go/services/cfc/api/errors.go @@ -0,0 +1,32 @@ +package api + +import "errors" + +var ( + URIIllegal = errors.New("invalid request uri") + MethodIllegal = errors.New("invalid request method") + InvalidArgument = errors.New("invalid arguments") + ParseJsonError = errors.New("could not parse payload into json") +) + +const ( + requiredIllegal = "the %s field is required" + memoryRangeIllegal = "memory size %d must in %d MB ~ %d MB" + memorySizeIllegal = "memory size %d must be a multiple of %d MB" + functionNameInvalid = "the function name of %s must match " + RegularFunctionName + AliasNameInvalid = "the alias name of %s must match " + RegularAliasName + functionBRNInvalid = "the brn %s must match " + RegularFunctionBRN + FunctionCodeInvalid = "the code of function is invalidate" + VersionInvalid = "the version of function must match " + RegularVersion + QualifierInvalid = "the qualifier is not the function's version or alias" + PaginateInvalid = "the pagination must greater than 0" + EventSourceTypeNotSupport = "the event source type: %s not support" +) + +const ( + getExecutionHistoryLimitIllegal = "the limit field should be greater than 0" + flowNameInvalid = "the flow name %s must match " + RegularFlowName + executionNameInvalid = "the execution name %s must match " + RegularExecutionName + flowTypeInvalid = "the flow type %s not supported, only support: " + FlowType + executionInputInvalid = "the execution input is not valid json, err: %s" +) diff --git a/bce-sdk-go/services/cfc/api/model.go b/bce-sdk-go/services/cfc/api/model.go new file mode 100644 index 0000000..e39520c --- /dev/null +++ b/bce-sdk-go/services/cfc/api/model.go @@ -0,0 +1,520 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 api + +import ( + "time" +) + +type InvocationType string +type LogType string +type SourceType string +type TriggerType string + +const ( + InvocationTypeEvent InvocationType = "Event" + InvocationTypeRequestResponse InvocationType = "RequestResponse" + InvocationTypeDryRun InvocationType = "DryRun" + + LogTypeTail LogType = "Tail" + LogTypeNone LogType = "None" + + SourceTypeDuerOS SourceType = "dueros" + SourceTypeDuEdge SourceType = "duedge" + SourceTypeHTTP SourceType = "cfc-http-trigger/v1/CFCAPI" + SourceTypeCrontab SourceType = "cfc-crontab-trigger/v1/" + SourceTypeCDN SourceType = "cdn" + + TriggerTypeHTTP TriggerType = "cfc-http-trigger" + TriggerTypeGeneric TriggerType = "generic" + TypeEventSourceDatahubTopic = "datahub_topic" + TypeEventSourceBms = "bms" + + StartingPositionTriHorizon = "TRIM_HORIZON" + StartingPositionLatest = "LATEST" + StartingPositionAtTimeStamp = "AT_TIMESTAMP" + + DatahubTopicStartPointLatest = int64(-1) + DatahubTopicStartPointOldest = int64(-2) +) + +type Function struct { + Uid string `json:"Uid"` + Description string `json:"Description"` + FunctionBrn string `json:"FunctionBrn"` + Region string `json:"Region"` + Timeout int `json:"Timeout"` + VersionDesc string `json:"VersionDesc"` + UpdatedAt time.Time `json:"UpdatedAt"` + LastModified time.Time `json:"LastModified"` + CodeSha256 string `json:"CodeSha256"` + CodeSize int32 `json:"CodeSize"` + FunctionArn string `json:"FunctionArn"` + FunctionName string `json:"FunctionName"` + Handler string `json:"Handler"` + Version string `json:"Version"` + Runtime string `json:"Runtime"` + MemorySize int `json:"MemorySize"` + Environment *Environment `json:"Environment"` + CommitID string `json:"CommitID"` + CodeID string `json:"CodeID"` + Role string `json:"Role"` + VpcConfig *VpcConfig `json:"VpcConfig"` + LogType string `json:"LogType"` + LogBosDir string `json:"LogBosDir"` + SourceTag string `json:"SourceTag"` +} + +// functionInfo +type FunctionInfo struct { + Code *CodeStorage `json:"Code"` + Configuration *Function `json:"Configuration"` +} + +type Alias struct { + AliasBrn string `json:"AliasBrn"` + AliasArn string `json:"AliasArn"` + FunctionName string `json:"FunctionName"` + FunctionVersion string `json:"FunctionVersion"` + Name string `json:"Name"` + Description string `json:"Description"` + Uid string `json:"Uid"` + UpdatedAt time.Time `json:"UpdatedAt"` + CreatedAt time.Time `json:"CreatedAt"` +} + +type RelationInfo struct { + RelationId string `json:"RelationId"` + Sid string `json:"Sid"` + Source SourceType `json:"Source"` + Target string `json:"Target"` + Data interface{} `json:"Data"` +} + +type CodeStorage struct { + Location string `json:"Location"` + RepositoryType string `json:"RepositoryType"` +} + +type Environment struct { + Variables map[string]string +} + +type CodeFile struct { + Publish bool + DryRun bool + ZipFile []byte + BosBucket string + BosObject string +} + +type VpcConfig struct { + VpcId string + SubnetIds []string + SecurityGroupIds []string +} + +type InvocationsArgs struct { + FunctionName string + InvocationType InvocationType + LogType LogType + Qualifier string + Payload interface{} + RequestId string +} + +type InvocationsResult struct { + Payload string + FunctionError string + LogResult string +} + +type GetFunctionArgs struct { + FunctionName string + Qualifier string +} + +type GetFunctionResult struct { + Code CodeStorage + Configuration Function +} + +type ListFunctionsArgs struct { + FunctionVersion string + Marker int + MaxItems int +} + +type ListFunctionsResult struct { + Functions []*Function + NextMarker string +} + +type CreateFunctionArgs struct { + Code *CodeFile + FunctionName string + Handler string + Runtime string + MemorySize int + Timeout int + Description string + Environment *Environment + VpcConfig *VpcConfig + LogType string + LogBosDir string + ServiceName string +} + +type CreateFunctionByBlueprintArgs struct { + BlueprintID string + ServiceName string + FunctionName string + Environment *Environment +} + +type CreateFunctionResult Function + +type DeleteFunctionArgs struct { + FunctionName string + Qualifier string +} + +type GetFunctionConfigurationArgs struct { + FunctionName string + Qualifier string +} + +type GetFunctionConfigurationResult Function + +type UpdateFunctionConfigurationArgs struct { + FunctionName string + Timeout int `json:"Timeout,omitempty"` + MemorySize int `json:"MemorySize,omitempty"` + Description string + Handler string + Runtime string + Environment *Environment + VpcConfig *VpcConfig + LogType string + LogBosDir string +} + +type UpdateFunctionConfigurationResult Function + +type UpdateFunctionCodeArgs struct { + FunctionName string + ZipFile []byte + Publish bool + DryRun bool + BosBucket string + BosObject string +} + +type UpdateFunctionCodeResult Function + +type ReservedConcurrentExecutionsArgs struct { + FunctionName string + ReservedConcurrentExecutions int +} + +type DeleteReservedConcurrentExecutionsArgs struct { + FunctionName string +} + +type ListVersionsByFunctionArgs struct { + FunctionName string + Marker int + MaxItems int +} +type ListVersionsByFunctionResult struct { + Versions []*Function + NextMarker string +} + +type PublishVersionArgs struct { + FunctionName string + Description string + CodeSha256 string +} + +type PublishVersionResult Function + +type ListAliasesArgs struct { + FunctionName string + FunctionVersion string + Marker int + MaxItems int +} + +type ListAliasesResult struct { + Aliases []*Alias + NextMarker string +} + +type GetAliasArgs struct { + FunctionName string + AliasName string +} + +type GetAliasResult Alias + +type CreateAliasArgs struct { + FunctionName string + FunctionVersion string + Name string + Description string +} + +type CreateAliasResult Alias + +type UpdateAliasArgs struct { + FunctionName string + AliasName string + FunctionVersion string + Description string +} +type UpdateAliasResult Alias + +type DeleteAliasArgs struct { + FunctionName string + AliasName string +} + +type ListTriggersArgs struct { + FunctionBrn string + ScopeType string +} + +type ListTriggersResult struct { + Relation []*RelationInfo +} + +type BosEventType string + +const ( + BosEventTypePutObject BosEventType = "PutObject" + BosEventTypePostObject BosEventType = "PostObject" + BosEventTypeAppendObject BosEventType = "AppendObject" + BosEventTypeCopyObject BosEventType = "CopyObject" + BosEventTypeCompleteMultipartObject BosEventType = "CompleteMultipartUpload" +) + +type BosTriggerData struct { + Resource string + Status string + EventType []BosEventType + Name string +} + +type HttpTriggerData struct { + ResourcePath string + Method string + AuthType string +} + +type CDNEventType string + +const ( + CDNEventTypeCachedObjectsBlocked CDNEventType = "CachedObjectsBlocked" + CDNEventTypeCachedObjectsPushed CDNEventType = "CachedObjectsPushed" + CDNEventTypeCachedObjectsRefreshed CDNEventType = "CachedObjectsRefreshed" + CDNEventTypeCdnDomainCreated CDNEventType = "CdnDomainCreated" + CDNEventTypeCdnDomainDeleted CDNEventType = "CdnDomainDeleted" + CDNEventTypeLogFileCreated CDNEventType = "LogFileCreated" + CDNEventTypeCdnDomainStarted CDNEventType = "CdnDomainStarted" + CDNEventTypeCdnDomainStopped CDNEventType = "CdnDomainStopped" +) + +type CDNTriggerData struct { + EventType CDNEventType + Domains []string + Remark string + Status string +} + +type CrontabTriggerData struct { + Brn string + Enabled string + Input string + Name string + ScheduleExpression string +} + +type CFCEdgeTriggerData struct { + Domain string + EventType string + Path string +} + +type CreateTriggerArgs struct { + Target string + Source SourceType + Data interface{} +} +type CreateTriggerResult struct { + Relation *RelationInfo +} + +type UpdateTriggerArgs struct { + RelationId string + Target string + Source SourceType + Data interface{} +} +type UpdateTriggerResult struct { + Relation *RelationInfo +} + +type DeleteTriggerArgs struct { + RelationId string + Target string + Source SourceType +} + +type CreateEventSourceArgs FuncEventSource + +type CreateEventSourceResult FuncEventSource + +type DeleteEventSourceArgs struct { + UUID string +} +type UpdateEventSourceArgs struct { + UUID string + FuncEventSource FuncEventSource +} + +type UpdateEventSourceResult FuncEventSource + +type GetEventSourceArgs struct { + UUID string +} + +type GetEventSourceResult FuncEventSource + +type ListEventSourceArgs struct { + FunctionName string + Marker int + MaxItems int +} + +type ListEventSourceResult struct { + EventSourceMappings []FuncEventSource +} + +// EventSource +type FuncEventSource struct { + Uuid string `json:"UUID"` + BatchSize int // 一次最多消费多少条消息 + Enabled *bool `json:"Enabled,omitempty"` //是否开启消息触发器 + FunctionBrn string // 绑定的function brn + EventSourceBrn string // 百度消息触发器bms kafka的topic名;Datahub触发器的配置唯一标识符,无需用户传入,服务端自动生成 + FunctionArn string // 兼容aws,与FunctionBrn相同 + EventSourceArn string // 兼容aws,与EventSourceBrn相同 + Type string `json:"Type,omitempty"` // 类型 bms/datahub_topic + FunctionName string `json:"FunctionName,omitempty"` // 函数brn或者函数名 + StartingPosition string `json:"StartingPosition,omitempty"` // 百度消息触发器bms kalfka topic 起始位置 + StartingPositionTimestamp *time.Time `json:"StartingPositionTimestamp,omitempty"` // 百度消息触发器bms kalfka topic 起始时间 + StateTransitionReason string // 状态变更原因 + DatahubConfig // Datahub触发器相关配置 + + State string `json:"State"` // 消息触发器状态,开启或关闭,与aws兼容 + LastProcessingResult string `json:"LastProcessingResult"` // 最新一次触发器的执行结果 + LastModified time.Time `json:"LastModified,omitempty"` // 上次修改时间 +} + +type DatahubConfig struct { + MetaHostEndpoint string `json:"MetaHostEndpoint,omitempty"` // MetaHost endpoint + MetaHostPort int `json:"MetaHostPort,omitempty"` // MetaHost port + ClusterName string `json:"ClusterName,omitempty"` // 集群名 + PipeName string `json:"PipeName,omitempty"` // pipe名 + PipeletNum uint32 `json:"PipeletNum,omitempty"` // 订阅PipiletNum + StartPoint int64 `json:"StartPoint,omitempty"` // 起始订阅点 正常情况下id为正整数, 2个特殊的点 -1: 表示pipelet内的最新一条消息;-2: 表示pipelet内最旧的一条消息 + AclName string `json:"ACLName,omitempty"` // ACL name + AclPassword string `json:"ACLPassword,omitempty"` // ACL passwd +} + +type StartExecutionArgs struct { + FlowName string `json:"flowName,omitempty"` // flowName + ExecutionName string `json:"executionName,omitempty"` // executionName + Input string `json:"input,omitempty"` // input +} + +type Execution struct { + Name string `json:"name"` + Status string `json:"status"` + FlowName string `json:"flowName"` + FlowDefinition string `json:"flowDefinition"` + Input string `json:"input"` + Output string `json:"output"` + StartedTime int64 `json:"startedTime"` + StoppedTime int64 `json:"stoppedTime"` +} + +type ListExecutionsResult struct { + Total int `json:"total"` + Executions []Execution `json:"executions"` +} + +type GetWorkflowResult struct { + Code CodeStorage + Configuration Function +} + +type GetExecutionHistoryResult struct { + Events []*ExecutionEvent `json:"events"` +} + +type ExecutionEvent struct { + CostTime int64 `json:"costTime"` + EventDetail string `json:"eventDetail"` + EventId string `json:"eventId"` + ExecutionId string `json:"executionId"` + StateName string `json:"stateName"` + Time int64 `json:"time"` + Type string `json:"type"` +} + +type Flow struct { + Name string `json:"name"` + Type string `json:"type"` + Definition string `json:"definition"` + Description string `json:"description"` + CreatedAt string `json:"created_at"` + UpdatedAt string `json:"updated_at"` +} + +type ListFlowResult struct { + Flows []*struct { + Name string `json:"name"` + Type string `json:"type"` + LastModifiedTime string `json:"lastModifiedTime"` + Description string `json:"description"` + Definition string `json:"definition"` + CreatedTime string `json:"createdTime"` + } `json:"flows"` +} + +type CreateUpdateFlowArgs struct { + Name string `json:"name"` + Type string `json:"type"` // 当前只支持 "FDL" + Definition string `json:"definition"` + Description string `json:"description"` +} + +type GetExecutionHistoryArgs struct { + FlowName string `json:"name"` + ExecutionName string `json:"type"` + Limit int `json:"limit"` +} diff --git a/bce-sdk-go/services/cfc/api/request.go b/bce-sdk-go/services/cfc/api/request.go new file mode 100644 index 0000000..d827cc8 --- /dev/null +++ b/bce-sdk-go/services/cfc/api/request.go @@ -0,0 +1,41 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 api + +type HTTPMethod = string + +const ( + GET HTTPMethod = "GET" + PUT HTTPMethod = "PUT" + POST HTTPMethod = "POST" + DELETE HTTPMethod = "DELETE" + HEAD HTTPMethod = "HEAD" + OPTIONS HTTPMethod = "OPTIONS" +) + +type Operation struct { + HTTPMethod HTTPMethod + HTTPUri string +} + +type cfcRequest struct { + Args interface{} + Params map[string]interface{} + Body interface{} +} + +type cfcResult struct { + Result interface{} +} diff --git a/bce-sdk-go/services/cfc/api/util.go b/bce-sdk-go/services/cfc/api/util.go new file mode 100644 index 0000000..676e804 --- /dev/null +++ b/bce-sdk-go/services/cfc/api/util.go @@ -0,0 +1,189 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 api + +import ( + "fmt" + "regexp" +) + +const ( + RegularFunctionName = `^[a-zA-Z0-9-_:]+|\$LATEST$` + RegularAliasName = `^[a-zA-Z0-9-_]+$` + RegularFunctionBRN = `^(brn:(bce[a-zA-Z-]*):cfc:)([a-z]{2,5}[0-9]*:)([0-9a-z]{32}:)(function:)([a-zA-Z0-9-_]+)(:(\$LATEST|[a-zA-Z0-9-_]+))?$` + RegularVersion = `^\$LATEST|([0-9]+)$` + + RegularFlowName = `^[a-zA-Z_]{1}[a-zA-Z0-9_-]{0,63}$` + RegularExecutionName = `^[a-zA-Z_0-9]{1}[a-zA-Z0-9_-]{0,63}$` + FlowType = "FDL" + + MemoryBase = 128 + minMemoryLimit = 128 + maxMemoryLimit = 3008 +) + +func getInvocationsUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s/invocations", functionName) +} + +func getFunctionsUri() string { + return fmt.Sprintf("/v1/functions") +} + +func getFunctionUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s", functionName) +} + +func getFunctionCodeUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s/code", functionName) +} + +func getFunctionConfigurationUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s/configuration", functionName) +} + +func getFunctionConCurrentUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s/concurrency", functionName) +} + +func getFunctionVersionsUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s/versions", functionName) +} + +func getFunctionAliasesUri(functionName string) string { + return fmt.Sprintf("/v1/functions/%s/aliases", functionName) +} + +func getFunctionAliasUri(functionName string, aliasName string) string { + return fmt.Sprintf("/v1/functions/%s/aliases/%s", functionName, aliasName) +} + +func getEventSourceUri() string { + return "/v1/event-source-mappings" +} + +func getBlueprintUri(blueprintId string) string { + return fmt.Sprintf("/v1/blueprints/%s/function", blueprintId) +} + +func getExecutionStartUri() string { + return "/v1/execution/start" +} + +func getExecutionStopUri() string { + return "/v1/execution/stop" +} + +func getExecutionsUri() string { + return "/v1/executions" +} + +func getExecutionUri() string { + return "/v1/execution" +} + +func getExecutionHistory() string { + return "/v1/execution/history" +} + +func getWorkflowsUri() string { + return "/v1/flows" +} + +func getWorkflowUri() string { + return "/v1/flow" +} + +func getOneEventSourceUri(uuid string) string { + return fmt.Sprintf("/v1/event-source-mappings/%s", uuid) +} + +func getTriggerUri() string { + return fmt.Sprintf("/v1/console/relation") +} + +func validateFunctionName(name string) bool { + res, err := regexp.MatchString(RegularFunctionName, name) + if err != nil { + return false + } + return res +} + +func validateFlowName(name string) bool { + res, err := regexp.MatchString(RegularFlowName, name) + if err != nil { + return false + } + return res +} + +func validateExecutionName(name string) bool { + res, err := regexp.MatchString(RegularExecutionName, name) + if err != nil { + return false + } + return res +} + +func validateAliasName(name string) bool { + res, err := regexp.MatchString(RegularAliasName, name) + if err != nil { + return false + } + return res +} + +func validateMemorySize(size int) error { + if size%MemoryBase != 0 { + return fmt.Errorf(memorySizeIllegal, size, MemoryBase) + } + if size > maxMemoryLimit { + return fmt.Errorf(memoryRangeIllegal, size, minMemoryLimit, maxMemoryLimit) + } + if size < minMemoryLimit { + return fmt.Errorf(memoryRangeIllegal, size, minMemoryLimit, maxMemoryLimit) + } + return nil +} + +func validateFunctionBRN(brn string) bool { + res, err := regexp.MatchString(RegularFunctionBRN, brn) + if err != nil { + return false + } + return res +} + +func validateVersion(version string) bool { + res, err := regexp.MatchString(RegularVersion, version) + if err != nil { + return false + } + return res +} + +func validateQualifier(qualifier string) bool { + var res bool + res, err := regexp.MatchString(RegularAliasName, qualifier) + if err == nil && res == true { + return true + } + res, err = regexp.MatchString(RegularVersion, qualifier) + if err != nil { + return false + } + return res +} diff --git a/bce-sdk-go/services/cfc/api/validator.go b/bce-sdk-go/services/cfc/api/validator.go new file mode 100644 index 0000000..3db926d --- /dev/null +++ b/bce-sdk-go/services/cfc/api/validator.go @@ -0,0 +1,416 @@ +package api + +import ( + "encoding/json" + "fmt" +) + +type Validator interface { + Validate() error +} + +func (args InvocationsArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Qualifier != "" && !validateQualifier(args.Qualifier) { + return fmt.Errorf(QualifierInvalid) + } + return nil +} + +func (args ListFunctionsArgs) Validate() error { + if args.Marker < 0 || args.MaxItems < 0 { + return fmt.Errorf(PaginateInvalid) + } + if args.FunctionVersion != "" && !validateVersion(args.FunctionVersion) { + return fmt.Errorf(VersionInvalid) + } + return nil +} + +func (args GetFunctionArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Qualifier != "" && !validateQualifier(args.Qualifier) { + return fmt.Errorf(QualifierInvalid) + } + return nil +} + +func (args CreateFunctionArgs) Validate() error { + if args.Code == nil { + return fmt.Errorf(requiredIllegal, "Code") + } + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Handler == "" { + return fmt.Errorf(requiredIllegal, "Handler") + } + if args.Runtime == "" { + return fmt.Errorf(requiredIllegal, "Runtime") + } + if err := validateMemorySize(args.MemorySize); err != nil { + return err + } + if len(args.Code.ZipFile) == 0 && (len(args.Code.BosBucket) == 0 || len(args.Code.BosObject) == 0) { + return fmt.Errorf(FunctionCodeInvalid) + } + return nil +} + +func (args DeleteFunctionArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Qualifier != "" && !validateQualifier(args.Qualifier) { + return fmt.Errorf(QualifierInvalid) + } + return nil +} + +func (args UpdateFunctionCodeArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + return nil +} + +func (args GetFunctionConfigurationArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Qualifier != "" && !validateQualifier(args.Qualifier) { + return fmt.Errorf(QualifierInvalid) + } + return nil +} + +func (args UpdateFunctionConfigurationArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + return nil +} + +func (args ListVersionsByFunctionArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Marker < 0 || args.MaxItems < 0 { + return fmt.Errorf(PaginateInvalid) + } + return nil +} + +func (args PublishVersionArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + return nil +} + +func (args ListAliasesArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if args.Marker < 0 || args.MaxItems < 0 { + return fmt.Errorf(PaginateInvalid) + } + if args.FunctionVersion != "" && !validateVersion(args.FunctionVersion) { + return fmt.Errorf(VersionInvalid) + } + return nil +} + +func (args CreateAliasArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if args.FunctionVersion == "" { + return fmt.Errorf(requiredIllegal, "FunctionVersion") + } + if args.Name == "" { + return fmt.Errorf(requiredIllegal, "Name") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if !validateVersion(args.FunctionVersion) { + return fmt.Errorf(VersionInvalid) + } + if !validateAliasName(args.Name) { + return fmt.Errorf(AliasNameInvalid, args.FunctionName) + } + return nil +} + +func (args GetAliasArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if args.AliasName == "" { + return fmt.Errorf(requiredIllegal, "AliasName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if !validateAliasName(args.AliasName) { + return fmt.Errorf(AliasNameInvalid, args.FunctionName) + } + return nil +} + +func (args UpdateAliasArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if args.AliasName == "" { + return fmt.Errorf(requiredIllegal, "AliasName") + } + if args.FunctionVersion == "" { + return fmt.Errorf(requiredIllegal, "FunctionVersion") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if !validateAliasName(args.AliasName) { + return fmt.Errorf(AliasNameInvalid, args.FunctionName) + } + if !validateVersion(args.FunctionVersion) { + return fmt.Errorf(VersionInvalid) + } + return nil +} + +func (args DeleteAliasArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + if args.AliasName == "" { + return fmt.Errorf(requiredIllegal, "AliasName") + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + if !validateAliasName(args.AliasName) { + return fmt.Errorf(AliasNameInvalid, args.FunctionName) + } + return nil +} + +func (args ListTriggersArgs) Validate() error { + if args.FunctionBrn == "" { + return fmt.Errorf(requiredIllegal, "FunctionBrn") + } + if !validateFunctionBRN(args.FunctionBrn) { + return fmt.Errorf(functionBRNInvalid, args.FunctionBrn) + } + return nil +} + +func (args CreateTriggerArgs) Validate() error { + if args.Target == "" { + return fmt.Errorf(requiredIllegal, "Target") + } + if args.Source == "" { + return fmt.Errorf(requiredIllegal, "Source") + } + if !validateFunctionBRN(args.Target) { + return fmt.Errorf(functionBRNInvalid, args.Target) + } + + return nil +} + +func (args UpdateTriggerArgs) Validate() error { + if args.RelationId == "" { + return fmt.Errorf(requiredIllegal, "RelationId") + } + if args.Target == "" { + return fmt.Errorf(requiredIllegal, "Target") + } + if args.Source == "" { + return fmt.Errorf(requiredIllegal, "Source") + } + if !validateFunctionBRN(args.Target) { + return fmt.Errorf(functionBRNInvalid, args.Target) + } + + return nil +} + +func (args DeleteTriggerArgs) Validate() error { + if args.RelationId == "" { + return fmt.Errorf(requiredIllegal, "RelationId") + } + if args.Target == "" { + return fmt.Errorf(requiredIllegal, "Target") + } + if args.Source == "" { + return fmt.Errorf(requiredIllegal, "Source") + } + if !validateFunctionBRN(args.Target) { + return fmt.Errorf(functionBRNInvalid, args.Target) + } + return nil +} + +func (args ReservedConcurrentExecutionsArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + + if args.ReservedConcurrentExecutions < 0 || args.ReservedConcurrentExecutions > 90 { + return fmt.Errorf(requiredIllegal, "ReservedConcurrentExecutions") + } + + return nil +} + +func (args DeleteReservedConcurrentExecutionsArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + + return nil +} + +func (args ListEventSourceArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + // 先检查是否满足brn规则 再看是不是function name + if !validateFunctionBRN(args.FunctionName) || !validateFunctionName(args.FunctionName) { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + + if args.Marker < 0 || args.MaxItems < 0 { + return fmt.Errorf(PaginateInvalid) + } + return nil +} +func (args GetEventSourceArgs) Validate() error { + if args.UUID == "" { + return fmt.Errorf(requiredIllegal, "UUID") + } + return nil +} + +func (args CreateEventSourceArgs) Validate() error { + if args.FunctionName == "" { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + // 先检查是否满足brn规则 再看是不是function name + if !validateFunctionBRN(args.FunctionName) || !validateFunctionName(args.FunctionName) { + return fmt.Errorf(requiredIllegal, "FunctionName") + } + + if args.Type == TypeEventSourceDatahubTopic || args.Type == TypeEventSourceBms { + return nil + } else { + return fmt.Errorf(EventSourceTypeNotSupport, args.Type) + } +} + +func (args UpdateEventSourceArgs) Validate() error { + if args.UUID == "" { + return fmt.Errorf(requiredIllegal, "UUID") + } + if args.FuncEventSource.Type != TypeEventSourceDatahubTopic || args.FuncEventSource.Type != TypeEventSourceBms { + return nil + } else { + return fmt.Errorf(EventSourceTypeNotSupport, args.FuncEventSource.Type) + } + +} + +func (args DeleteEventSourceArgs) Validate() error { + if args.UUID == "" { + return fmt.Errorf(requiredIllegal, "UUID") + } + return nil +} + +func (args GetExecutionHistoryArgs) Validate() error { + if args.Limit <= 0 { + return fmt.Errorf(getExecutionHistoryLimitIllegal) + } + if !validateFlowName(args.FlowName) { + return fmt.Errorf(flowNameInvalid, args.FlowName) + } + if !validateExecutionName(args.ExecutionName) { + return fmt.Errorf(executionNameInvalid, args.ExecutionName) + } + return nil +} + +func (args CreateUpdateFlowArgs) Validate() error { + if !validateFlowName(args.Name) { + return fmt.Errorf(flowNameInvalid, args.Name) + } + if args.Type != "" && args.Type != "FDL" { + return fmt.Errorf(flowTypeInvalid, args.Type) + } + return nil +} + +func (args StartExecutionArgs) Validate() error { + if !validateFlowName(args.FlowName) { + return fmt.Errorf(flowNameInvalid, args.FlowName) + } + if args.ExecutionName != "" { + if !validateExecutionName(args.ExecutionName) { + return fmt.Errorf(executionNameInvalid, args.ExecutionName) + } + } + + var input = map[string]interface{}{} + err := json.Unmarshal([]byte(args.Input), &input) + if err != nil { + return fmt.Errorf(executionInputInvalid, err.Error()) + } + return nil +} + +func (args CreateFunctionByBlueprintArgs) Validate() error { + if args.BlueprintID == "" { + return fmt.Errorf(requiredIllegal, args.BlueprintID) + } + if !validateFunctionName(args.FunctionName) { + return fmt.Errorf(functionNameInvalid, args.FunctionName) + } + return nil +} diff --git a/bce-sdk-go/services/cfc/api/workflow.go b/bce-sdk-go/services/cfc/api/workflow.go new file mode 100644 index 0000000..97d57df --- /dev/null +++ b/bce-sdk-go/services/cfc/api/workflow.go @@ -0,0 +1,227 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 api + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +func StartExecution(cli bce.Client, args *StartExecutionArgs) (*Execution, error) { + op := &Operation{ + HTTPUri: getExecutionStartUri(), + HTTPMethod: POST, + } + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &Execution{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*Execution); ok { + return value, nil + } + return nil, nil +} + +func StopExecution(cli bce.Client, flowName, executionName string) (*Execution, error) { + op := &Operation{ + HTTPUri: getExecutionStopUri(), + HTTPMethod: POST, + } + request := &cfcRequest{ + Body: map[string]string{"flowName": flowName, "executionName": executionName}, + } + result := &cfcResult{ + Result: &Execution{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*Execution); ok { + return value, nil + } + return nil, nil +} + +func ListExecutions(cli bce.Client, flowName string) (*ListExecutionsResult, error) { + op := &Operation{ + HTTPUri: getExecutionsUri(), + HTTPMethod: GET, + } + request := &cfcRequest{ + Params: map[string]interface{}{"flowName": flowName}, + } + result := &cfcResult{ + Result: &ListExecutionsResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListExecutionsResult); ok { + return value, nil + } + return nil, nil +} + +func DescribeExecution(cli bce.Client, flowName, executionName string) (*Execution, error) { + op := &Operation{ + HTTPUri: getExecutionUri(), + HTTPMethod: GET, + } + request := &cfcRequest{ + Params: map[string]interface{}{ + "flowName": flowName, + "executionName": executionName, + }, + } + result := &cfcResult{ + Result: &Execution{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*Execution); ok { + return value, nil + } + return nil, nil +} + +func GetExecutionHistory(cli bce.Client, args *GetExecutionHistoryArgs) (*GetExecutionHistoryResult, error) { + op := &Operation{ + HTTPUri: getExecutionHistory(), + HTTPMethod: GET, + } + if args.Limit == 0 { + args.Limit = 100 + } + request := &cfcRequest{ + Args: args, + Params: map[string]interface{}{ + "flowName": args.FlowName, + "executionName": args.ExecutionName, + "limit": args.Limit, + }, + } + result := &cfcResult{ + Result: &GetExecutionHistoryResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*GetExecutionHistoryResult); ok { + return value, nil + } + return nil, nil +} + +func ListFlow(cli bce.Client) (*ListFlowResult, error) { + op := &Operation{ + HTTPUri: getWorkflowsUri(), + HTTPMethod: GET, + } + request := &cfcRequest{} + result := &cfcResult{ + Result: &ListFlowResult{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*ListFlowResult); ok { + return value, nil + } + return nil, nil +} + +func CreateFlow(cli bce.Client, args *CreateUpdateFlowArgs) (*Flow, error) { + op := &Operation{ + HTTPUri: getWorkflowUri(), + HTTPMethod: POST, + } + return createUpdateFlow(cli, args, op) +} + +func UpdateFlow(cli bce.Client, args *CreateUpdateFlowArgs) (*Flow, error) { + op := &Operation{ + HTTPUri: getWorkflowUri(), + HTTPMethod: PUT, + } + + return createUpdateFlow(cli, args, op) +} + +func createUpdateFlow(cli bce.Client, args *CreateUpdateFlowArgs, op *Operation) (*Flow, error) { + request := &cfcRequest{ + Args: args, + Body: args, + } + result := &cfcResult{ + Result: &Flow{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*Flow); ok { + return value, nil + } + return nil, nil +} + +func DescribeFlow(cli bce.Client, flowName string) (*Flow, error) { + op := &Operation{ + HTTPUri: getWorkflowUri(), + HTTPMethod: GET, + } + request := &cfcRequest{ + Params: map[string]interface{}{"flowName": flowName}, + } + result := &cfcResult{ + Result: &Flow{}, + } + err := caller(cli, op, request, result) + if err != nil { + return nil, err + } + if value, ok := result.Result.(*Flow); ok { + return value, nil + } + return nil, nil +} + +func DeleteFlow(cli bce.Client, flowName string) error { + op := &Operation{ + HTTPUri: getWorkflowUri(), + HTTPMethod: DELETE, + } + request := &cfcRequest{ + Params: map[string]interface{}{"flowName": flowName}, + } + result := &cfcResult{} + err := caller(cli, op, request, result) + if err != nil { + return err + } + return nil +} diff --git a/bce-sdk-go/services/cfc/client.go b/bce-sdk-go/services/cfc/client.go new file mode 100644 index 0000000..fa3c936 --- /dev/null +++ b/bce-sdk-go/services/cfc/client.go @@ -0,0 +1,525 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for CFC service + +// Package cfc defines the CFC services of BCE. The supported APIs are all defined in sub-package + +package cfc + +import ( + "errors" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/cfc/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "cfc." + bce.DEFAULT_REGION + ".baidubce.com" +) + +// Client of CFC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the CFC service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func newClient(ak, sk, token, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 || len(sk) == 0 { + return nil, errors.New("ak sk illegal") + } + if len(token) == 0 { + credentials, err = auth.NewBceCredentials(ak, sk) + } else { + credentials, err = auth.NewSessionBceCredentials(ak, sk, token) + } + if err != nil { + return nil, err + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +func NewClient(ak, sk, endpoint string) (*Client, error) { + return newClient(ak, sk, "", endpoint) +} + +// Invocations - invocation a cfc function with specific parameters +// +// PARAMS: +// - args: the arguments to invocation cfc function +// +// RETURNS: +// - *api.InvocationsResult: the result of invocation cfc function +// - error: nil if success otherwise the specific error +func (c *Client) Invocations(args *api.InvocationsArgs) (*api.InvocationsResult, error) { + return api.Invocations(c, args) +} + +// Invoke - invoke a cfc function, the same as Invocations +// +// PARAMS: +// - args: the arguments to invocation cfc function +// +// RETURNS: +// - *api.InvocationsResult: the result of invocation cfc function +// - error: nil if success otherwise the specific error +func (c *Client) Invoke(args *api.InvocationsArgs) (*api.InvocationsResult, error) { + return api.Invocations(c, args) +} + +// ListFunctions - list all functions with the specific parameters +// +// PARAMS: +// - args: the arguments to list all functions +// +// RETURNS: +// - *api.ListFunctionsResult: the result of list all functions +// - error: nil if success otherwise the specific error +func (c *Client) ListFunctions(args *api.ListFunctionsArgs) (*api.ListFunctionsResult, error) { + return api.ListFunctions(c, args) +} + +// GetFunction - get a specific cfc function +// +// PARAMS: +// - args: the arguments to get a specific cfc function +// +// RETURNS: +// - *api.GetFunctionResult: the result of get function +// - error: nil if success otherwise the specific error +func (c *Client) GetFunction(args *api.GetFunctionArgs) (*api.GetFunctionResult, error) { + return api.GetFunction(c, args) +} + +// CreateFunction - create a cfc function with specific parameters +// +// PARAMS: +// - args: the arguments to create a cfc function +// +// RETURNS: +// - *api.CreateFunctionResult: the result of create a cfc function, it contains function information +// - error: nil if success otherwise the specific error +func (c *Client) CreateFunction(args *api.CreateFunctionArgs) (*api.CreateFunctionResult, error) { + return api.CreateFunction(c, args) +} + +// CreateFunctionByBlueprint - create a cfc function by a blueprint +// +// PARAMS: +// - args: the arguments to create a cfc function +// +// RETURNS: +// - *api.CreateFunctionResult: the result of create a cfc function, it contains function information +// - error: nil if success otherwise the specific error +func (c *Client) CreateFunctionByBlueprint(args *api.CreateFunctionByBlueprintArgs) (*api.CreateFunctionResult, error) { + return api.CreateFunctionByBlueprint(c, args) +} + +// DeleteFunction - delete a specific cfc function +// +// PARAMS: +// - args: the arguments to delete cfc function +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteFunction(args *api.DeleteFunctionArgs) error { + return api.DeleteFunction(c, args) +} + +// UpdateFunctionCode - update a cfc function code +// +// PARAMS: +// - args: the arguments to update function code +// +// RETURNS: +// - *api.UpdateFunctionCodeResult: the result of update function code +// - error: nil if success otherwise the specific error +func (c *Client) UpdateFunctionCode(args *api.UpdateFunctionCodeArgs) (*api.UpdateFunctionCodeResult, error) { + return api.UpdateFunctionCode(c, args) +} + +// GetFunctionConfiguration - get a specific cfc function configuration +// +// PARAMS: +// - args: the arguments to get function configuration +// +// RETURNS: +// - *api.GetFunctionConfigurationResult: the result of function configuration +// - error: nil if success otherwise the specific error +func (c *Client) GetFunctionConfiguration(args *api.GetFunctionConfigurationArgs) (*api.GetFunctionConfigurationResult, error) { + return api.GetFunctionConfiguration(c, args) +} + +// UpdateFunctionConfiguration - update a specific cfc function configuration +// +// PARAMS: +// - args: the arguments to update cfc function +// +// RETURNS: +// - *api.UpdateFunctionConfigurationResult: the result of update function configuration +// - error: nil if success otherwise the specific error +func (c *Client) UpdateFunctionConfiguration(args *api.UpdateFunctionConfigurationArgs) (*api.UpdateFunctionConfigurationResult, error) { + return api.UpdateFunctionConfiguration(c, args) +} + +// ListVersionsByFunction - list all versions about a specific cfc function +// +// PARAMS: +// - args: the arguments to list all versions +// +// RETURNS: +// - *api.ListVersionsByFunctionResult: the result of all versions information +// - error: nil if success otherwise the specific error +func (c *Client) ListVersionsByFunction(args *api.ListVersionsByFunctionArgs) (*api.ListVersionsByFunctionResult, error) { + return api.ListVersionsByFunction(c, args) +} + +// PublishVersion - publish a cfc function as a new version +// +// PARAMS: +// - args: the arguments to publish a version +// +// RETURNS: +// - *api.PublishVersionResult: the result of publish a function version +// - error: nil if success otherwise the specific error +func (c *Client) PublishVersion(args *api.PublishVersionArgs) (*api.PublishVersionResult, error) { + return api.PublishVersion(c, args) +} + +// ListAliases - list all alias about a specific cfc function with specific parameters +// +// PARAMS: +// - args: the arguments to list all alias +// +// RETURNS: +// - *api.ListAliasesResult: the result of list all alias +// - error: nil if success otherwise the specific error +func (c *Client) ListAliases(args *api.ListAliasesArgs) (*api.ListAliasesResult, error) { + return api.ListAliases(c, args) +} + +// CreateAlias - create an alias which bind one specific cfc function version +// +// PARAMS: +// - args: the arguments to create an alias +// +// RETURNS: +// - *api.CreateAliasResult: the result of create alias +// - error: nil if success otherwise the specific error +func (c *Client) CreateAlias(args *api.CreateAliasArgs) (*api.CreateAliasResult, error) { + return api.CreateAlias(c, args) +} + +// GetAlias - get alias information which bind one cfc function +// +// PARAMS: +// - args: the arguments to get an alias +// +// RETURNS: +// - *api.GetAliasResult: the result of get alias +// - error: nil if success otherwise the specific error +func (c *Client) GetAlias(args *api.GetAliasArgs) (*api.GetAliasResult, error) { + return api.GetAlias(c, args) +} + +// UpdateAlias - update an alias configuration +// +// PARAMS: +// - args: the arguments to update an alias +// +// RETURNS: +// - *api.UpdateAliasResult: the result of update an alias +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAlias(args *api.UpdateAliasArgs) (*api.UpdateAliasResult, error) { + return api.UpdateAlias(c, args) +} + +// DeleteAlias - delete an alias +// +// PARAMS: +// - args: the arguments to delete an alias +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAlias(args *api.DeleteAliasArgs) error { + return api.DeleteAlias(c, args) +} + +// ListTriggers - list all triggers in one cfc function version +// +// PARAMS: +// - args: the arguments to list all triggers +// +// RETURNS: +// - *api.ListTriggersResult: the result of list all triggers +// - error: nil if success otherwise the specific error +func (c *Client) ListTriggers(args *api.ListTriggersArgs) (*api.ListTriggersResult, error) { + return api.ListTriggers(c, args) +} + +// CreateTrigger - create a specific trigger +// +// PARAMS: +// - args: the arguments to create a trigger +// +// RETURNS: +// - *api.CreateTriggerResult: the result of create a trigger +// - error: nil if success otherwise the specific error +func (c *Client) CreateTrigger(args *api.CreateTriggerArgs) (*api.CreateTriggerResult, error) { + return api.CreateTrigger(c, args) +} + +// UpdateTrigger - update a trigger +// +// PARAMS: +// - args: the arguments to update a trigger +// +// RETURNS: +// - *api.UpdateTriggerResult: the result of update a trigger +// - error: nil if success otherwise the specific error +func (c *Client) UpdateTrigger(args *api.UpdateTriggerArgs) (*api.UpdateTriggerResult, error) { + return api.UpdateTrigger(c, args) +} + +// DeleteTrigger - delete a trigger +// +// PARAMS: +// - args: the arguments to delete a trigger +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteTrigger(args *api.DeleteTriggerArgs) error { + return api.DeleteTrigger(c, args) +} + +// SetReservedConcurrentExecutions - set a cfc function reserved concurrent executions +// +// PARAMS: +// - args: the arguments to set reserved concurrent executions +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SetReservedConcurrentExecutions(args *api.ReservedConcurrentExecutionsArgs) error { + return api.SetReservedConcurrentExecutions(c, args) +} + +// DeleteReservedConcurrentExecutions - delete one cfc function reserved concurrent executions setting +// +// PARAMS: +// - args: the arguments to delete reserved concurrent executions setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteReservedConcurrentExecutions(args *api.DeleteReservedConcurrentExecutionsArgs) error { + return api.DeleteReservedConcurrentExecutions(c, args) +} + +// ListEventSource - list all event source mapping settings in one cfc function version +// +// PARAMS: +// - args: the arguments to list all event source mapping settings +// +// RETURNS: +// - *api.ListEventSourceResult: the result of list all event source mapping settings +// - error: nil if success otherwise the specific error +func (c *Client) ListEventSource(args *api.ListEventSourceArgs) (*api.ListEventSourceResult, error) { + return api.ListEventSource(c, args) +} + +// GetEventSource - get info for a event source mapping setting +// +// PARAMS: +// - args: the arguments to get a event source mapping setting +// +// RETURNS: +// - *api.GetEventSourceResult: the result of get a event source mapping +// - error: nil if success otherwise the specific error +func (c *Client) GetEventSource(args *api.GetEventSourceArgs) (*api.GetEventSourceResult, error) { + return api.GetEventSource(c, args) +} + +// UpdateEventSource - update a event source mapping setting +// +// PARAMS: +// - args: the arguments to update a event source mapping +// +// RETURNS: +// - *api.UpdateEventSourceResult: the result of update a event source mapping +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEventSource(args *api.UpdateEventSourceArgs) (*api.UpdateEventSourceResult, error) { + return api.UpdateEventSource(c, args) +} + +// CreateEventSource - create a event source mapping setting +// +// PARAMS: +// - args: the arguments to create a event source mapping setting +// +// RETURNS: +// - *api.CreateEventSourceResult: the result of create event source mapping setting +// - error: nil if success otherwise the specific error +func (c *Client) CreateEventSource(args *api.CreateEventSourceArgs) (*api.CreateEventSourceResult, error) { + return api.CreateEventSource(c, args) +} + +// DeleteEventSource - delete one cfc event source mapping setting +// +// PARAMS: +// - args: the arguments to delete cfc event source mapping setting +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEventSource(args *api.DeleteEventSourceArgs) error { + return api.DeleteEventSource(c, args) + +} + +// StartExecution - start an execution of a workflow +// +// PARAMS: +// - args: the arguments to start execution, include flowName、executionName(optional) and input +// input is a serialized json string, for example: "{\"fruits\":[\"apple\", \"banana\"]}". +// +// RETURNS: +// - *api.Execution: information about the execution +// - error: nil if success otherwise the specific error +func (c *Client) StartExecution(args *api.StartExecutionArgs) (*api.Execution, error) { + return api.StartExecution(c, args) +} + +// StopExecution - stop a running execution of a workflow +// +// PARAMS: +// - flowName: which flow the execution belongs to +// - executionName: which execution to stop +// +// RETURNS: +// - *api.Execution: information about the execution +// - error: nil if success otherwise the specific error +func (c *Client) StopExecution(flowName, executionName string) (*api.Execution, error) { + return api.StopExecution(c, flowName, executionName) +} + +// ListExecutions - list all executions of a flow +// +// PARAMS: +// - flowName: which flow to list executions +// +// RETURNS: +// - *api.ListExecutionsResult: information about the executions +// - error: nil if success otherwise the specific error +func (c *Client) ListExecutions(flowName string) (*api.ListExecutionsResult, error) { + return api.ListExecutions(c, flowName) +} + +// DescribeExecution - describe detail info of an execution +// +// PARAMS: +// - flowName: which flow the execution belongs to +// - executionName: which execution to get +// +// RETURNS: +// - *api.Execution: information about the execution +// - error: nil if success otherwise the specific error +func (c *Client) DescribeExecution(flowName, executionName string) (*api.Execution, error) { + return api.DescribeExecution(c, flowName, executionName) +} + +// GetExecutionHistory - get all state event detail info of an execution +// +// PARAMS: +// - args: args to get history +// +// RETURNS: +// - *api.GetExecutionHistoryResult: state history of the execution +// - error: nil if success otherwise the specific error +func (c *Client) GetExecutionHistory(args *api.GetExecutionHistoryArgs) (*api.GetExecutionHistoryResult, error) { + return api.GetExecutionHistory(c, args) +} + +// ListFlow - list all flows +// +// RETURNS: +// - *api.ListFlowResult: list of all flows +// - error: nil if success otherwise the specific error +func (c *Client) ListFlow() (*api.ListFlowResult, error) { + return api.ListFlow(c) +} + +// CreateFlow - create a flow +// +// PARAMS: +// - args: args to create a flow +// +// RETURNS: +// - *api.Flow: the created flow information +// - error: nil if success otherwise the specific error +func (c *Client) CreateFlow(args *api.CreateUpdateFlowArgs) (*api.Flow, error) { + return api.CreateFlow(c, args) +} + +// UpdateFlow - update a flow +// +// PARAMS: +// - args: args to update a flow, args.Name is the name of flow to update +// +// RETURNS: +// - *api.Flow: flow information after update +// - error: nil if success otherwise the specific error +func (c *Client) UpdateFlow(args *api.CreateUpdateFlowArgs) (*api.Flow, error) { + return api.UpdateFlow(c, args) +} + +// DescribeFlow - get information of a flow +// +// PARAMS: +// - flowName: name of the flow to describe +// +// RETURNS: +// - *api.Flow: flow information +// - error: nil if success otherwise the specific error +func (c *Client) DescribeFlow(flowName string) (*api.Flow, error) { + return api.DescribeFlow(c, flowName) +} + +// DeleteFlow - delete a flow +// +// PARAMS: +// - flowName: name of the flow to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteFlow(flowName string) error { + return api.DeleteFlow(c, flowName) +} diff --git a/bce-sdk-go/services/cfc/client_test.go b/bce-sdk-go/services/cfc/client_test.go new file mode 100644 index 0000000..01cee23 --- /dev/null +++ b/bce-sdk-go/services/cfc/client_test.go @@ -0,0 +1,747 @@ +package cfc + +import ( + "encoding/json" + "fmt" + "io/ioutil" + "os" + "path/filepath" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/services/cfc/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + CfcClient *Client + FunctionName01 string + FunctionName02 string + AliasName01 string + AliasName02 string + FunctionBRN string + CodeSha256 string + RelationId string + zipFilePython string + zipFileNodejs01 string + zipFileNodejs02 string +) + +const ( + invokeTestReturnPayload = "Hello World" +) + +var ( + logSuccess = true +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +type PayloadDemo struct { + A string + B int +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given:(%s) err(%v)\n", conf, err) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + FunctionName01 = fmt.Sprintf("sdktest-function01-%s", time.Now().Format("2006-01-02T150405")) + FunctionName02 = fmt.Sprintf("sdktest-function02-%s", time.Now().Format("2006-01-02T150405")) + zipFilePython = filepath.Join(filepath.Dir(f), "./python.zip") + zipFileNodejs01 = filepath.Join(filepath.Dir(f), "./nodejs.zip") + zipFileNodejs02 = filepath.Join(filepath.Dir(f), "./nodejs2.zip") + + AliasName01 = fmt.Sprintf("sdktest-alias01-%s", time.Now().Format("2006-01-02T150405")) + AliasName02 = fmt.Sprintf("sdktest-alias02-%s", time.Now().Format("2006-01-02T150405")) + + CfcClient, err = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + if err != nil { + panic(err) + } + log.SetLogHandler(log.FILE) + //log.SetLogHandler(log.STDERR | log.FILE) + //log.SetRotateType(log.ROTATE_SIZE) + log.SetLogLevel(log.DEBUG) +} + +func TestCreateFunction(t *testing.T) { + codeFile, err := ioutil.ReadFile(zipFilePython) + if err != nil { + t.Fatalf("err (%v)", err) + } + + codeFile2, err := ioutil.ReadFile(zipFilePython) + if err != nil { + t.Fatalf("err (%v)", err) + } + // This function return Hello World + cases := []api.CreateFunctionArgs{ + { + Code: &api.CodeFile{ZipFile: codeFile}, + FunctionName: FunctionName01, + Handler: "index.handler", + Runtime: "python2", + MemorySize: 128, + Timeout: 3, + Description: "Description", + }, + { + Code: &api.CodeFile{ZipFile: codeFile2}, + FunctionName: FunctionName02, + Handler: "index.handler", + Runtime: "nodejs8.5", + MemorySize: 256, + Timeout: 3, + Description: "Description", + }, + } + for _, args := range cases { + res, err := CfcClient.CreateFunction(&args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } + } +} + +func TestCreateFunctionByBlueprint(t *testing.T) { + cases := []api.CreateFunctionByBlueprintArgs{ + { + FunctionName: "f2", + ServiceName: "default", + BlueprintID: "6b850453-00f2-473f-8f9c-b88e1705d9e6", + Environment: &api.Environment{ + Variables: map[string]string{ + "k1": "v1", + }, + }, + }, + } + for _, args := range cases { + res, err := CfcClient.CreateFunctionByBlueprint(&args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } + } +} + +func TestListFunctions(t *testing.T) { + args := &api.ListFunctionsArgs{ + FunctionVersion: "1", + Marker: 1, + MaxItems: 2, + } + res, err := CfcClient.ListFunctions(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestGetFunction(t *testing.T) { + res, err := CfcClient.GetFunction(&api.GetFunctionArgs{ + FunctionName: FunctionName01, + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + FunctionBRN = res.Configuration.FunctionBrn + fmt.Printf(FunctionBRN) + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestInvocations(t *testing.T) { + cases := []struct { + args *api.InvocationsArgs + respPayload string + err error + }{ + { + args: &api.InvocationsArgs{ + FunctionName: FunctionName01, + InvocationType: api.InvocationTypeRequestResponse, + Payload: nil, + }, + respPayload: invokeTestReturnPayload, + err: nil, + }, + { + args: &api.InvocationsArgs{ + FunctionName: FunctionName01, + InvocationType: api.InvocationTypeEvent, + Payload: `[{"a":1},{"a":2}]`, + }, + respPayload: "", + err: nil, + }, + { + args: &api.InvocationsArgs{ + FunctionName: FunctionName01, + InvocationType: api.InvocationTypeRequestResponse, + Payload: `[{"a":,{"a":2}]`, + }, + respPayload: "", + err: fmt.Errorf("could not parse payload into json"), + }, + { + args: &api.InvocationsArgs{ + FunctionName: FunctionName01, + InvocationType: api.InvocationTypeEvent, + Payload: []byte(`{"a":1}`), + }, + respPayload: "", + err: nil, + }, + { + args: &api.InvocationsArgs{ + FunctionName: FunctionName01, + InvocationType: api.InvocationTypeRequestResponse, + Payload: []*PayloadDemo{&PayloadDemo{A: "1", B: 2}, &PayloadDemo{A: "3", B: 4}}, + }, + respPayload: invokeTestReturnPayload, + err: nil, + }, + } + for _, tc := range cases { + t.Run("invoke", func(t *testing.T) { + res, err := CfcClient.Invocations(tc.args) + if err == nil && tc.err != nil { + t.Errorf("Expected err to be %v, but got nil", tc.err) + } else if err != nil && tc.err == nil { + t.Errorf("Expected err to be nil, but got %v", err) + } else if err != nil && tc.err != nil && err.Error() != tc.err.Error() { + t.Errorf("Expected err to be %v, but got %v", tc.err, err) + } else if res != nil && res.Payload != tc.respPayload { + t.Errorf("Expected Payload to be %s, but got %s", tc.respPayload, res.Payload) + } + }) + } +} + +func TestUpdateFunctionCode(t *testing.T) { + codeFile, err := ioutil.ReadFile(zipFileNodejs02) + if err != nil { + t.Fatalf("err (%v)", err) + } + res, err := CfcClient.UpdateFunctionCode(&api.UpdateFunctionCodeArgs{ + FunctionName: FunctionName02, + ZipFile: codeFile, + Publish: false, + DryRun: false, + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestUpdateFunctionConfiguration(t *testing.T) { + res, err := CfcClient.UpdateFunctionConfiguration(&api.UpdateFunctionConfigurationArgs{ + FunctionName: FunctionName02, + Timeout: 5, + Description: "wooo cool", + Handler: "index.handler", + Runtime: "nodejs8.5", + Environment: &api.Environment{ + Variables: map[string]string{ + "name": "Test", + }, + }, + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestGetFunctionConfiguration(t *testing.T) { + res, err := CfcClient.GetFunctionConfiguration(&api.GetFunctionConfigurationArgs{ + FunctionName: FunctionName02, + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestPublishVersion(t *testing.T) { + res, err := CfcClient.GetFunction(&api.GetFunctionArgs{ + FunctionName: FunctionName02, + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + CodeSha256 = res.Configuration.CodeSha256 + fmt.Printf(FunctionBRN) + result, err := CfcClient.PublishVersion(&api.PublishVersionArgs{ + FunctionName: FunctionName02, + Description: "test", + CodeSha256: CodeSha256, + }) + if logSuccess && err == nil { + t.Logf("res %v ", result) + } +} + +func TestListVersionsByFunction(t *testing.T) { + res, err := CfcClient.ListVersionsByFunction(&api.ListVersionsByFunctionArgs{ + FunctionName: "testHelloWorld", + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestCreateAlias(t *testing.T) { + cases := []api.CreateAliasArgs{ + { + FunctionName: FunctionName02, + FunctionVersion: "$LATEST", + Name: AliasName01, + Description: "test alias", + }, + { + FunctionName: FunctionName02, + FunctionVersion: "$LATEST", + Name: AliasName02, + Description: "test alias", + }, + } + for _, args := range cases { + res, err := CfcClient.CreateAlias(&args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } + } +} + +func TestGetAlias(t *testing.T) { + args := &api.GetAliasArgs{ + FunctionName: FunctionName02, + AliasName: AliasName01, + } + res, err := CfcClient.GetAlias(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestUpdateAlias(t *testing.T) { + args := &api.UpdateAliasArgs{ + FunctionName: FunctionName02, + AliasName: AliasName01, + FunctionVersion: "$LATEST", + Description: "test alias " + AliasName01, + } + res, err := CfcClient.UpdateAlias(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestListAliases(t *testing.T) { + args := &api.ListAliasesArgs{ + FunctionName: FunctionName02, + FunctionVersion: "$LATEST", + Marker: 0, + MaxItems: 2, + } + res, err := CfcClient.ListAliases(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestDeleteAlias(t *testing.T) { + args := &api.DeleteAliasArgs{ + FunctionName: FunctionName02, + AliasName: AliasName02, + } + err := CfcClient.DeleteAlias(args) + if err != nil { + t.Fatalf("err (%v)", err) + } +} + +func TestCreateTrigger(t *testing.T) { + cases := []api.CreateTriggerArgs{ + { + Target: FunctionBRN, + Source: api.SourceTypeHTTP, + Data: struct { + ResourcePath string + Method string + AuthType string + }{ + ResourcePath: fmt.Sprintf("tr01-%s", time.Now().Format("2006-01-02T150405")), + Method: "GET", + AuthType: "anonymous", + }, + }, { + Target: FunctionBRN, + Source: api.SourceTypeHTTP, + Data: struct { + ResourcePath string + Method string + AuthType string + }{ + ResourcePath: fmt.Sprintf("tr02-%s", time.Now().Format("2006-01-02T150405")), + Method: "GET", + AuthType: "anonymous", + }, + }, + } + for _, args := range cases { + res, err := CfcClient.CreateTrigger(&args) + if err != nil { + t.Fatalf("err (%v)", err) + } + + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } + } +} + +func TestListTriggers(t *testing.T) { + args := &api.ListTriggersArgs{ + FunctionBrn: FunctionBRN, + } + res, err := CfcClient.ListTriggers(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + if len(res.Relation) > 0 { + RelationId = res.Relation[0].RelationId + } + t.Logf("res %v", res) + resStr, err := json.Marshal(res) + if err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestUpdateTrigger(t *testing.T) { + args := &api.UpdateTriggerArgs{ + RelationId: RelationId, + Target: FunctionBRN, + Source: api.SourceTypeHTTP, + Data: struct { + ResourcePath string + Method string + AuthType string + }{ + ResourcePath: fmt.Sprintf("tr99-%s", time.Now().Format("2006-01-02T150405")), + Method: "GET", + AuthType: "anonymous", + }, + } + res, err := CfcClient.UpdateTrigger(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + if res.Relation != nil { + RelationId = res.Relation.RelationId + } + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestDeleteTrigger(t *testing.T) { + listArgs := &api.ListTriggersArgs{ + FunctionBrn: FunctionBRN, + } + res, err := CfcClient.ListTriggers(listArgs) + if err != nil { + t.Fatalf("err (%v)", err) + } + if len(res.Relation) > 0 { + RelationId = res.Relation[0].RelationId + } + args := &api.DeleteTriggerArgs{ + RelationId: RelationId, + Target: FunctionBRN, + Source: api.SourceTypeHTTP, + } + t.Logf("args (%+v)", args) + err = CfcClient.DeleteTrigger(args) + if err != nil { + t.Errorf("err (%v)", err) + } +} + +func TestDeleteFunction(t *testing.T) { + args := &api.DeleteFunctionArgs{ + FunctionName: FunctionName01, + } + err := CfcClient.DeleteFunction(args) + if err != nil { + t.Logf("res (%v)", err) + } +} + +// TODO test fail +func TestListEventSource(t *testing.T) { + FunctionBRN = "" + args := &api.ListEventSourceArgs{ + FunctionName: FunctionBRN, + Marker: 0, + MaxItems: 100, + } + res, err := CfcClient.ListEventSource(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) + resStr, err := json.Marshal(res) + if err == nil { + t.Logf("res %s ", resStr) + } +} + +// test pass +func TestGetEventSource(t *testing.T) { + args := &api.GetEventSourceArgs{ + UUID: "uuid", + } + res, err := CfcClient.GetEventSource(args) + if err != nil { + t.Logf("res (%v)", err) + } + t.Logf("res %+v", res) + resStr, err := json.Marshal(res) + if err == nil { + t.Logf("res %s ", resStr) + } +} + +// test pass +func TestCreateEventSource(t *testing.T) { + unEnabled := false + FunctionBRN = "" + args := &api.CreateEventSourceArgs{ + Enabled: &unEnabled, + BatchSize: 3, + Type: api.TypeEventSourceDatahubTopic, + FunctionName: FunctionBRN, + DatahubConfig: api.DatahubConfig{ + MetaHostEndpoint: "endpoint", + MetaHostPort: 2181, + ClusterName: "clusterName", + PipeName: "pipeName", + PipeletNum: 1, + StartPoint: -1, + AclName: "aclName", + AclPassword: "aclPassword", + }, + } + res, err := CfcClient.CreateEventSource(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} +func TestUpdateEventSource(t *testing.T) { + FunctionBRN = "" + unEnabled := false + args := &api.UpdateEventSourceArgs{ + UUID: "uuid", + FuncEventSource: api.FuncEventSource{ + Enabled: &unEnabled, + BatchSize: 3, + Type: api.TypeEventSourceDatahubTopic, + FunctionName: FunctionBRN, + DatahubConfig: api.DatahubConfig{ + MetaHostEndpoint: "10.155.195.11", + MetaHostPort: 2181, + ClusterName: "clusterName", + PipeName: "pipeName", + PipeletNum: 1, + StartPoint: -1, + AclName: "aclName", + AclPassword: "aclPassword", + }, + }, + } + res, err := CfcClient.UpdateEventSource(args) + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) + resStr, err := json.MarshalIndent(res, "", " ") + if logSuccess && err == nil { + t.Logf("res %s ", resStr) + } +} + +func TestDeleteEventSource(t *testing.T) { + args := &api.DeleteEventSourceArgs{ + UUID: "uuid", + } + err := CfcClient.DeleteEventSource(args) + if err != nil { + t.Fatalf("err (%v)", err) + } +} + +func TestListFlow(t *testing.T) { + res, err := CfcClient.ListFlow() + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res.Flows[0]) +} + +func TestCreateFlow(t *testing.T) { + res, err := CfcClient.CreateFlow(&api.CreateUpdateFlowArgs{ + Name: "demo-x2", + Type: "FDL", + Definition: "name: demo\nstart: initData\nstates:\n - type: pass\n name: initData\n data:\n hello: world\n end: true", + Description: "ut test demo", + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestUpdateFlow(t *testing.T) { + res, err := CfcClient.UpdateFlow(&api.CreateUpdateFlowArgs{ + Name: "demo-x2", + Type: "FDL", + Definition: "name: demo\nstart: initData2\nstates:\n - type: pass\n name: initData2\n data:\n hello: world\n end: true", + Description: "ut test demo2", + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestDescribeFlow(t *testing.T) { + res, err := CfcClient.DescribeFlow("demo-x2") + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestDeleteFlow(t *testing.T) { + err := CfcClient.DeleteFlow("demo-x2") + if err != nil { + t.Fatalf("err (%v)", err) + } +} + +func TestStartExecution(t *testing.T) { + res, err := CfcClient.StartExecution(&api.StartExecutionArgs{ + FlowName: "demo-x2", + ExecutionName: "s3", + Input: "{\"fruits\":[\"apple\", \"banana\"]}", + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestStopExecution(t *testing.T) { + res, err := CfcClient.StopExecution("demo-x2", "s3") + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestDescribeExecution(t *testing.T) { + res, err := CfcClient.DescribeExecution("demo-x2", "s3") + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestListExecutions(t *testing.T) { + res, err := CfcClient.ListExecutions("demo-x2") + if err != nil { + t.Fatalf("err (%v)", err) + } + t.Logf("res %+v", res) +} + +func TestGetExecutionHistory(t *testing.T) { + res, err := CfcClient.GetExecutionHistory(&api.GetExecutionHistoryArgs{ + FlowName: "demo-x2", + ExecutionName: "s3", + Limit: 40, + }) + if err != nil { + t.Fatalf("err (%v)", err) + } + for _, e := range res.Events { + t.Logf("event %+v", e) + } +} diff --git a/bce-sdk-go/services/cfc/config.json b/bce-sdk-go/services/cfc/config.json new file mode 100644 index 0000000..7d314b8 --- /dev/null +++ b/bce-sdk-go/services/cfc/config.json @@ -0,0 +1,5 @@ +{ + "AK":"ak", + "SK":"sk", + "Endpoint":"endpoint" +} \ No newline at end of file diff --git a/bce-sdk-go/services/cfc/nodejs.zip b/bce-sdk-go/services/cfc/nodejs.zip new file mode 100644 index 0000000..80145cd Binary files /dev/null and b/bce-sdk-go/services/cfc/nodejs.zip differ diff --git a/bce-sdk-go/services/cfc/nodejs2.zip b/bce-sdk-go/services/cfc/nodejs2.zip new file mode 100644 index 0000000..cd06a5a Binary files /dev/null and b/bce-sdk-go/services/cfc/nodejs2.zip differ diff --git a/bce-sdk-go/services/cfc/python.zip b/bce-sdk-go/services/cfc/python.zip new file mode 100644 index 0000000..0ebb961 Binary files /dev/null and b/bce-sdk-go/services/cfc/python.zip differ diff --git a/bce-sdk-go/services/cfs/cfs.go b/bce-sdk-go/services/cfs/cfs.go new file mode 100644 index 0000000..6614d91 --- /dev/null +++ b/bce-sdk-go/services/cfs/cfs.go @@ -0,0 +1,195 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// cfs.go - the Normal CFS APIs definition supported by the CFS service + +package cfs + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateFS - create a FS Instance +// +// PARAMS: +// - args: parameters to create FS +// +// RETURNS: +// - *CreateFSResult: the result of create fs, contains new FS Instance's ID +// - error: nil if ok otherwise the specific error +func (c *Client) CreateFS(args *CreateFSArgs) (*CreateFSResult, error) { + if args == nil || len(args.Name) == 0 { + return nil, fmt.Errorf("unset fs name") + } + + if len(args.Zone) == 0 { + return nil, fmt.Errorf("unset zone") + } + + result := &CreateFSResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getCFSUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateFS - update name of a FS Instance +// +// PARAMS: +// - args: parameters to create FS +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateFS(args *UpdateFSArgs) error { + if args == nil || len(args.FSName) == 0 { + return fmt.Errorf("unset fs name") + } + if len(args.FSID) == 0 { + return fmt.Errorf("unset fs id") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getFSInstanceUri(args.FSID)). + WithBody(args). + Do() + + return err +} + +// DescribeFS - describe all FS Instances +// +// PARAMS: +// - args: parameters describe all FS Instances +// +// RETURNS: +// - *DescribeFSResult: the result FS Instances's detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeFS(args *DescribeFSArgs) (*DescribeFSResult, error) { + if args == nil { + args = &DescribeFSArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeFSResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getCFSUri()). + WithQueryParamFilter("fsId", args.FSID). + WithQueryParamFilter("userId", args.UserId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + err := request.Do() + return result, err +} + +// CreateMountTarget - create a mount target for FS Instances +// +// PARAMS: +// - args: parameters to create mount target +// +// RETURNS: +// - *CreateMountTargetResult: the result mount target's detail +// - error: nil if ok otherwise the specific error +func (c *Client) CreateMountTarget(args *CreateMountTargetArgs) (*CreateMountTargetResult, error) { + if args == nil || len(args.FSID) == 0 { + return nil, fmt.Errorf("unset fs id") + } + + if len(args.SubnetId) == 0 { + return nil, fmt.Errorf("unset subnetid") + } + + result := &CreateMountTargetResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getFSInstanceUri(args.FSID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// DescribeMountTarget - describe all mount targets +// +// PARAMS: +// - args: parameters describe all mount targets +// +// RETURNS: +// - *DescribeMountTargetResult: the result Mount target's detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeMountTarget(args *DescribeMountTargetArgs) (*DescribeMountTargetResult, error) { + if args == nil { + args = &DescribeMountTargetArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeMountTargetResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getFSInstanceUri(args.FSID)). + WithQueryParamFilter("mountId", args.MountID). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + err := request.Do() + return result, err +} + +// DropMountTarget - drop a MountTarget +// +// PARAMS: +// - args: parameters to drop mount target +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DropMountTarget(args *DropMountTargetArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getMountTargetUri(args.FSID, args.MountId)). + Do() +} + +// DropFS - drop a fs instance +// +// PARAMS: +// - args: parameters to drop fs +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DropFS(args *DropFSArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getFSInstanceUri(args.FSID)). + Do() +} diff --git a/bce-sdk-go/services/cfs/client.go b/bce-sdk-go/services/cfs/client.go new file mode 100644 index 0000000..c83ece8 --- /dev/null +++ b/bce-sdk-go/services/cfs/client.go @@ -0,0 +1,54 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for Application LoadBalance service + +// Package cfs defines the Normal CFS services of BCE. The supported APIs are all defined in sub-package +package cfs + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + DEFAULT_SERVICE_DOMAIN = "cfs." + bce.DEFAULT_REGION + ".baidubce.com" + URI_PREFIX = bce.URI_PREFIX + "v1" + REQUEST_CFS_URL = "/cfs" +) + +// Client of CFS service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getCFSUri() string { + return URI_PREFIX + REQUEST_CFS_URL +} + +func getFSInstanceUri(id string) string { + return URI_PREFIX + REQUEST_CFS_URL + "/" + id +} + +func getMountTargetUri(fs_id string, mount_id string) string { + return URI_PREFIX + REQUEST_CFS_URL + "/" + fs_id + "/" + mount_id +} diff --git a/bce-sdk-go/services/cfs/client_test.go b/bce-sdk-go/services/cfs/client_test.go new file mode 100644 index 0000000..eefc178 --- /dev/null +++ b/bce-sdk-go/services/cfs/client_test.go @@ -0,0 +1,188 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 cfs + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + CFS_CLIENT *Client + CFS_ID string + MOUNT_ID string + USER_ID string + + // set these values before start test + VPC_TEST_ID = "" + SUBNET_TEST_ID = "" + TEST_PROTOCOL = "nfs" + TEST_ZONE = "zoneA" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + USER_ID string + VPC_ID string + SUBNET_ID string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + CFS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + VPC_TEST_ID = confObj.VPC_ID + SUBNET_TEST_ID = confObj.SUBNET_ID + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateFS(t *testing.T) { + createArgs := &CreateFSArgs{ + ClientToken: getClientToken(), + Name: "sdkCFS", + VpcID: VPC_TEST_ID, + Protocol: TEST_PROTOCOL, + Zone: TEST_ZONE, + } + + createResult, err := CFS_CLIENT.CreateFS(createArgs) + ExpectEqual(t.Errorf, nil, err) + + CFS_ID = createResult.FSID +} + +func TestClient_UpdateFS(t *testing.T) { + updateArgs := &UpdateFSArgs{ + FSID: CFS_ID, + FSName: "sdCFS_newname", + } + + err := CFS_CLIENT.UpdateFS(updateArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DescribeFS(t *testing.T) { + describeArgs := &DescribeFSArgs{ + UserId: USER_ID, + } + res, err := CFS_CLIENT.DescribeFS(describeArgs) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(time.Duration(1) * time.Second) +} + +func TestClient_DescribeFSWithFS(t *testing.T) { + describeArgs := &DescribeFSArgs{ + FSID: CFS_ID, + } + res, err := CFS_CLIENT.DescribeFS(describeArgs) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(time.Duration(1) * time.Second) +} + +func TestClient_CreateMountTarget(t *testing.T) { + createArgs := &CreateMountTargetArgs{ + FSID: CFS_ID, + SubnetId: SUBNET_TEST_ID, + VpcID: VPC_TEST_ID, + } + + createResult, err := CFS_CLIENT.CreateMountTarget(createArgs) + fmt.Print(createResult) + ExpectEqual(t.Errorf, nil, err) + MOUNT_ID = createResult.MountID +} + +func TestClient_DescribeMountTarget(t *testing.T) { + describeArgs := &DescribeMountTargetArgs{ + FSID: CFS_ID, + } + res, err := CFS_CLIENT.DescribeMountTarget(describeArgs) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(time.Duration(1) * time.Second) +} + +func TestClient_DropMountTarget(t *testing.T) { + dropArgs := &DropMountTargetArgs{ + FSID: CFS_ID, + MountId: MOUNT_ID, + } + err := CFS_CLIENT.DropMountTarget(dropArgs) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(time.Duration(5) * time.Second) +} + +func TestClient_DropFS(t *testing.T) { + dropArgs := &DropFSArgs{ + FSID: CFS_ID, + } + err := CFS_CLIENT.DropFS(dropArgs) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(time.Duration(1) * time.Second) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/cfs/model.go b/bce-sdk-go/services/cfs/model.go new file mode 100644 index 0000000..56a7d33 --- /dev/null +++ b/bce-sdk-go/services/cfs/model.go @@ -0,0 +1,116 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package cfs + +import () + +type FSStatus string + +const ( + FSStatusAvailable FSStatus = "available" + FSStatusPaused FSStatus = "paused" + FSStatusUnavailable FSStatus = "unavailable" +) + +type CreateFSArgs struct { + ClientToken string `json:"-"` + Name string `json:"fsName"` + Type string `json:"type"` + Protocol string `json:"protocol"` + VpcID string `json:"vpcId,omitempty"` + Zone string `json:"zone,omitempty"` +} + +type CreateFSResult struct { + FSID string `json:"fsId"` +} + +type UpdateFSArgs struct { + FSID string `json:"-"` + FSName string `json:"fsName"` +} + +type DescribeResultMeta struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type DescribeFSArgs struct { + FSID string + UserId string + Marker string + MaxKeys int +} + +type MoutTargetModel struct { + AccessGroupName string `json:"accessGroupName"` + MountID string `json:"mountId"` + Ovip string `json:"ovip"` + Domain string `json:"domain"` + SubnetID string `json:"subnetId"` +} + +type FSModel struct { + FSID string `json:"fsId"` + Name string `json:"fsName"` + VpcID string `json:"vpcId"` + Type string `json:"type"` + Protocol string `json:"protocol"` + Usage string `json:"fsUsage"` + Status FSStatus `json:"status"` + MoutTargets []MoutTargetModel `json:"mountTargetList"` +} + +type DescribeFSResult struct { + FSList []FSModel `json:"fileSystemList"` + DescribeResultMeta +} + +type DropFSArgs struct { + FSID string +} + +type CreateMountTargetArgs struct { + FSID string `json:"-"` + VpcID string `json:"vpcId"` + SubnetId string `json:"subnetId"` + AccessGroupName string `json:"accessGroupName"` +} + +type CreateMountTargetResult struct { + MountID string `json:"mountId"` + Domain string `json:"domain"` +} + +type DropMountTargetArgs struct { + FSID string + MountId string +} + +type DescribeMountTargetArgs struct { + FSID string + MountID string + Marker string + MaxKeys int +} + +type DescribeMountTargetResult struct { + MountTargetList []MoutTargetModel `json:"mountTargetList"` + DescribeResultMeta +} diff --git a/bce-sdk-go/services/cfw/cfw.go b/bce-sdk-go/services/cfw/cfw.go new file mode 100644 index 0000000..68955d5 --- /dev/null +++ b/bce-sdk-go/services/cfw/cfw.go @@ -0,0 +1,489 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 cfw + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" + "strings" +) + +// BindCfw - 批量实例绑定CFW策略。 - 没有规则的CFW不能绑定到实例 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func BindCfw(cli *Client, cfwId string, body *BindCfwRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + req.SetParam("bind", "") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreateCfw - 创建CFW策略。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - body: +// +// RETURNS: +// - *api.CreateCfwResponse: +// - error: the return error if any occurs +func CreateCfw(cli *Client, body *CreateCfwRequest) (*CreateCfwResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/cfw" + req.SetUri(path) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &CreateCfwResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// CreateCfwRule - 批量创建CFW中防护规则。 - 五元组(protocol/sourceAddress/destAddress/sourcePort/destPort) + 方向(direction)不能全部相同。 - 一次最多创建100条规则。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreateCfwRule(cli *Client, cfwId string, body *CreateCfwRuleRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/cfw/[cfwId]/rule" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteCfw - 删除指定CFW策略。 - CFW存在绑定关系时不允许删除 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// +// RETURNS: +// - error: the return error if any occurs +func DeleteCfw(cli *Client, cfwId string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteCfwRule - 批量删除指定CFW中某些规则。 - CFW已绑定到实例时,至少保留一条规则。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DeleteCfwRule(cli *Client, cfwId string, body *DeleteCfwRuleRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]/delete/rule" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DisableCfw - 已绑定CFW的实例,使用该接口临时关闭CFW的防护功能。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DisableCfw(cli *Client, cfwId string, body *DisableCfwRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + req.SetParam("off", "") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// EnableCfw - 已绑定CFW并且临时关闭了防护功能的实例,使用该接口恢复CFW的防护功能。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func EnableCfw(cli *Client, cfwId string, body *EnableCfwRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + req.SetParam("on", "") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// GetCfw - 查询指定CFW策略的详情信息。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// +// RETURNS: +// - *api.GetCfwResponse: +// - error: the return error if any occurs +func GetCfw(cli *Client, cfwId string) (*GetCfwResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &GetCfwResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListCfw - 查询CFW策略列表信息。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - listCfwArgs: +// +// RETURNS: +// - *api.ListCfwResponse: +// - error: the return error if any occurs +func ListCfw(cli *Client, listCfwArgs *ListCfwArgs) ( + *ListCfwResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/cfw" + req.SetUri(path) + if "" != listCfwArgs.Marker { + req.SetParam("marker", listCfwArgs.Marker) + } + if 0 != listCfwArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listCfwArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListCfwResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListInstance - 查询防护边界实例的列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - listInstanceRequest: +// +// RETURNS: +// - *api.ListInstanceResponse: +// - error: the return error if any occurs +func ListInstance(cli *Client, listInstanceRequest *ListInstanceRequest) (*ListInstanceResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/cfw/instance" + req.SetUri(path) + req.SetParam("instanceType", listInstanceRequest.InstanceType) + if "" != listInstanceRequest.Marker { + req.SetParam("marker", listInstanceRequest.Marker) + } + if 0 != listInstanceRequest.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listInstanceRequest.MaxKeys)) + } + if "" != listInstanceRequest.Status { + req.SetParam("status", listInstanceRequest.Status) + } + if "" != listInstanceRequest.Region { + req.SetParam("region", listInstanceRequest.Region) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListInstanceResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// UnbindCfw - 实例批量解绑CFW。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UnbindCfw(cli *Client, cfwId string, body *UnbindCfwRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + req.SetParam("unbind", "") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateCfw - 更新CFW策略的基本信息。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateCfw(cli *Client, cfwId string, body *UpdateCfwRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + req.SetUri(path) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateCfwRule - 修改指定CFW规则。 - 五元组(protocol/sourceAddress/destAddress/sourcePort/destPort) + 方向(direction)不能全部相同。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - cfwId: CFW策略的id +// - cfwRuleId: CFW规则的id +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateCfwRule(cli *Client, cfwId string, cfwRuleId string, + body *UpdateCfwRuleRequest) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/cfw/[cfwId]/rule/[cfwRuleId]" + path = strings.Replace(path, "[cfwId]", cfwId, -1) + path = strings.Replace(path, "[cfwRuleId]", cfwRuleId, -1) + req.SetUri(path) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/cfw/client.go b/bce-sdk-go/services/cfw/client.go new file mode 100644 index 0000000..1982dea --- /dev/null +++ b/bce-sdk-go/services/cfw/client.go @@ -0,0 +1,236 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 cfw + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "http://cfw.baidubce.com" + DEFAULT_MAX_PARALLEL = 10 + MULTIPART_ALIGN = 1 << 20 // 1MB + MIN_MULTIPART_SIZE = 1 << 20 // 1MB + DEFAULT_MULTIPART_SIZE = 12 * (1 << 20) // 12MB + MAX_PART_NUMBER = 10000 +) + +// Client of bcd service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient + + // Fileds that used in parallel operation for BOS service + MaxParallel int64 + MultipartSize int64 +} + +// NewClient make the bcd service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer), + DEFAULT_MAX_PARALLEL, DEFAULT_MULTIPART_SIZE} + return client, nil +} + +// BindCfw - 批量实例绑定CFW策略。 - 没有规则的CFW不能绑定到实例 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) BindCfw(cfwId string, body *BindCfwRequest) error { + return BindCfw(c, cfwId, body) +} + +// CreateCfw - 创建CFW策略。 +// +// PARAMS: +// - body: body参数 +// +// RETURNS: +// - *CreateCfwResponse: +// - error: the return error if any occurs +func (c *Client) CreateCfw(body *CreateCfwRequest) ( + *CreateCfwResponse, error) { + return CreateCfw(c, body) +} + +// CreateCfwRule - 批量创建CFW中防护规则。 - 五元组(protocol/sourceAddress/destAddress/sourcePort/destPort) + 方向(direction)不能全部相同。 - 一次最多创建100条规则。 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateCfwRule(cfwId string, body *CreateCfwRuleRequest) error { + return CreateCfwRule(c, cfwId, body) +} + +// DeleteCfw - 删除指定CFW策略。 - CFW存在绑定关系时不允许删除 +// +// PARAMS: +// - cfwId: CFW的id +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteCfw(cfwId string) error { + return DeleteCfw(c, cfwId) +} + +// DeleteCfwRule - 批量删除指定CFW中某些规则。 - CFW已绑定到实例时,至少保留一条规则。 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteCfwRule(cfwId string, body *DeleteCfwRuleRequest) error { + return DeleteCfwRule(c, cfwId, body) +} + +// DisableCfw - 已绑定CFW的实例,使用该接口临时关闭CFW的防护功能。 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DisableCfw(cfwId string, body *DisableCfwRequest) error { + return DisableCfw(c, cfwId, body) +} + +// EnableCfw - 已绑定CFW并且临时关闭了防护功能的实例,使用该接口恢复CFW的防护功能。 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) EnableCfw(cfwId string, body *EnableCfwRequest) error { + return EnableCfw(c, cfwId, body) +} + +// GetCfw - 查询指定CFW策略的详情信息。 +// +// PARAMS: +// - cfwId: CFW的id +// +// RETURNS: +// - *GetCfwResponse: +// - error: the return error if any occurs +func (c *Client) GetCfw(cfwId string) (*GetCfwResponse, error) { + return GetCfw(c, cfwId) +} + +// ListCfw - 查询CFW策略列表信息。 +// +// PARAMS: +// - marker: 批量获取列表查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListCfwResponse: +// - error: the return error if any occurs +func (c *Client) ListCfw(listCfwArgs *ListCfwArgs) ( + *ListCfwResponse, error) { + return ListCfw(c, listCfwArgs) +} + +// ListInstance - 查询防护边界实例的列表。 +// +// PARAMS: +// - instanceType: 实例类型,取值[ eip | nat | etGateway | peerconn | csn | ipv6Gateway ] +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000,缺省值为1000 +// - status: 防护状态,取值 [ unbound | protected | unprotected ] +// - region: 地域信息,取值 [ bj | gz | su | fsh | hkg | bd | fwh | sin ] +// - body: body参数 +// +// RETURNS: +// - *ListInstanceResponse: +// - error: the return error if any occurs +func (c *Client) ListInstance(body *ListInstanceRequest) (*ListInstanceResponse, error) { + return ListInstance(c, body) +} + +// UnbindCfw - 实例批量解绑CFW。 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UnbindCfw(cfwId string, body *UnbindCfwRequest) error { + return UnbindCfw(c, cfwId, body) +} + +// UpdateCfw - 更新CFW策略的基本信息。 +// +// PARAMS: +// - cfwId: CFW的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateCfw(cfwId string, body *UpdateCfwRequest) error { + return UpdateCfw(c, cfwId, body) +} + +// UpdateCfwRule - 修改指定CFW规则。 - 五元组(protocol/sourceAddress/destAddress/sourcePort/destPort) + 方向(direction)不能全部相同。 +// +// PARAMS: +// - cfwId: CFW策略的id +// - cfwRuleId: CFW规则的id +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateCfwRule(cfwId string, cfwRuleId string, + body *UpdateCfwRuleRequest) error { + return UpdateCfwRule(c, cfwId, cfwRuleId, body) +} diff --git a/bce-sdk-go/services/cfw/client_test.go b/bce-sdk-go/services/cfw/client_test.go new file mode 100644 index 0000000..14fd3b4 --- /dev/null +++ b/bce-sdk-go/services/cfw/client_test.go @@ -0,0 +1,236 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 cfw + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + CfwClient *Client +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + f = filepath.Dir(f) + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + CfwClient, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) +} + +func TestClient_CreateCfw(t *testing.T) { + args := &CreateCfwRequest{ + Name: "cfw_1", + Description: "desc", + CfwRules: []CreateRule{ + { + IpVersion: 4, + Priority: 4, + Protocol: "TCP", + Direction: "in", + SourceAddress: "192.168.0.4", + DestAddress: "192.168.0.5", + SourcePort: "80", + DestPort: "88", + Action: "allow", + }, + }, + } + result, err := CfwClient.CreateCfw(args) + ExpectEqual(t.Errorf, nil, err) + CfwId := result.CfwId + log.Debug(CfwId) +} + +func TestClient_ListCfw(t *testing.T) { + args := &ListCfwArgs{} + result, err := CfwClient.ListCfw(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_GetCfw(t *testing.T) { + result, err := CfwClient.GetCfw("cfw-xxxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_UpdateCfw(t *testing.T) { + args := &UpdateCfwRequest{ + Name: "cfw_2", + Description: "desc", + } + err := CfwClient.UpdateCfw("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteCfw(t *testing.T) { + err := CfwClient.DeleteCfw("cfw-xxxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateCfwRule(t *testing.T) { + args := &CreateCfwRuleRequest{ + CfwRules: []CreateRule{ + { + IpVersion: 4, + Priority: 5, + Protocol: "TCP", + Direction: "in", + SourceAddress: "192.168.0.3", + DestAddress: "192.168.0.4", + SourcePort: "80", + DestPort: "88", + Action: "allow", + }, + }, + } + err := CfwClient.CreateCfwRule("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateCfwRule(t *testing.T) { + args := &UpdateCfwRuleRequest{ + IpVersion: 4, + Priority: 2, + Protocol: "TCP", + Direction: "in", + SourceAddress: "192.168.0.1", + DestAddress: "192.168.0.2", + SourcePort: "80", + DestPort: "88", + Action: "allow", + } + err := CfwClient.UpdateCfwRule("cfw-xxxxxxxxxxxx", "cfwr-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteCfwRule(t *testing.T) { + args := &DeleteCfwRuleRequest{ + CfwRuleIds: []string{ + "cfwr-xxxxxxxxxxxx", + }, + } + err := CfwClient.DeleteCfwRule("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListInstance(t *testing.T) { + args := &ListInstanceRequest{ + InstanceType: "csn", + } + result, err := CfwClient.ListInstance(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_BindCfw(t *testing.T) { + args := &BindCfwRequest{ + InstanceType: "csn", + Instances: []CfwBind{ + { + Region: "bj", + InstanceId: "csn-xxxxxxxxxxxx", + MemberId: "vpc-xxxxxxxxxxxx", + }, + }, + } + err := CfwClient.BindCfw("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindCfw(t *testing.T) { + args := &UnbindCfwRequest{ + InstanceType: "csn", + Instances: []CfwBind{ + { + Region: "bj", + InstanceId: "csn-xxxxxxxxxxxx", + MemberId: "vpc-xxxxxxxxxxxx", + }, + }, + } + err := CfwClient.UnbindCfw("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EnableCfw(t *testing.T) { + args := &EnableCfwRequest{ + InstanceId: "csn-xxxxxxxxxxxx", + MemberId: "vpc-xxxxxxxxxxxx", + } + err := CfwClient.EnableCfw("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DisableCfw(t *testing.T) { + args := &DisableCfwRequest{ + InstanceId: "csn-xxxxxxxxxxxx", + MemberId: "vpc-xxxxxxxxxxxx", + } + err := CfwClient.DisableCfw("cfw-xxxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/cfw/model.go b/bce-sdk-go/services/cfw/model.go new file mode 100644 index 0000000..2471170 --- /dev/null +++ b/bce-sdk-go/services/cfw/model.go @@ -0,0 +1,203 @@ +/* + * Copyright Baidu, Inc. + * + * 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 cfw + +type BindCfwRequest struct { + InstanceType string `json:"instanceType"` + Instances []CfwBind `json:"instances"` +} + +type BindCfwRequestInstances struct { +} + +type Cfw struct { + CfwId string `json:"cfwId"` + Name string `json:"name"` + Description string `json:"description"` + CreatedTime string `json:"createdTime"` + BindInstanceNum int32 `json:"bindInstanceNum"` + CfwRules []CfwRule `json:"cfwRules"` +} + +type CfwBind struct { + Region string `json:"region"` + InstanceId string `json:"instanceId"` + Role string `json:"role"` + MemberId string `json:"memberId"` +} + +type CfwRule struct { + IpVersion int32 `json:"ipVersion"` + Priority int32 `json:"priority"` + Protocol string `json:"protocol"` + Direction string `json:"direction"` + SourceAddress string `json:"sourceAddress"` + DestAddress string `json:"destAddress"` + SourcePort string `json:"sourcePort"` + DestPort string `json:"destPort"` + Action string `json:"action"` + Description string `json:"description"` + CfwId string `json:"cfwId"` + CfwRuleId string `json:"cfwRuleId"` +} + +type CreateCfwRequest struct { + Name string `json:"name"` + Description string `json:"description"` + CfwRules []CreateRule `json:"cfwRules"` +} + +type CreateCfwRequestCfwRules struct { +} + +type CreateCfwResponse struct { + CfwId string `json:"cfwId"` +} + +type CreateCfwRuleRequest struct { + CfwRules []CreateRule `json:"cfwRules"` +} + +type CreateCfwRuleRequestCfwRules struct { +} + +type CreateRule struct { + IpVersion int32 `json:"ipVersion"` + Priority int32 `json:"priority"` + Protocol string `json:"protocol"` + Direction string `json:"direction"` + SourceAddress string `json:"sourceAddress"` + DestAddress string `json:"destAddress"` + SourcePort string `json:"sourcePort"` + DestPort string `json:"destPort"` + Action string `json:"action"` + Description string `json:"description"` +} + +type DeleteCfwRuleRequest struct { + CfwRuleIds []string `json:"cfwRuleIds"` +} + +type DeleteCfwRuleRequestCfwRuleIds struct { +} + +type DisableCfwRequest struct { + InstanceId string `json:"instanceId"` + Role string `json:"role"` + MemberId string `json:"memberId"` +} + +type EnableCfwRequest struct { + InstanceId string `json:"instanceId"` + Role string `json:"role"` + MemberId string `json:"memberId"` +} + +type GetCfwResponse struct { + CfwId string `json:"cfwId"` + Name string `json:"name"` + Description string `json:"description"` + CreatedTime string `json:"createdTime"` + BindInstanceNum int32 `json:"bindInstanceNum"` + CfwRules []CfwRule `json:"cfwRules"` +} + +type GetCfwResponseCfwRules struct { +} + +type Instance struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Status string `json:"status"` + Region string `json:"region"` + CfwId string `json:"cfwId"` + CfwName string `json:"cfwName"` + VpcId string `json:"vpcId"` + VpcName string `json:"vpcName"` + PublicIp string `json:"publicIp"` + Role string `json:"role"` + LocalIfId string `json:"localIfId"` + LocalIfName string `json:"localIfName"` + PeerRegion string `json:"peerRegion"` + PeerVpcId string `json:"peerVpcId"` + PeerVpcName string `json:"peerVpcName"` + MemberId string `json:"memberId"` + MemberName string `json:"memberName"` + MemberAccountId string `json:"memberAccountId"` +} + +type ListCfwResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int32 `json:"maxKeys"` + Cfws []Cfw `json:"cfws"` +} + +type ListCfwResponseCfws struct { +} + +type ListInstanceRequest struct { + InstanceType string `json:"instanceType"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + Status string `json:"status"` + Region string `json:"region"` +} + +type ListInstanceRequestCfwRuleIds struct { +} + +type ListInstanceResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []Instance `json:"instances"` +} + +type ListInstanceResponseInstances struct { +} + +type UnbindCfwRequest struct { + InstanceType string `json:"instanceType"` + Instances []CfwBind `json:"instances"` +} + +type UnbindCfwRequestInstances struct { +} + +type UpdateCfwRequest struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type UpdateCfwRuleRequest struct { + IpVersion int32 `json:"ipVersion"` + Priority int32 `json:"priority"` + Protocol string `json:"protocol"` + Direction string `json:"direction"` + SourceAddress string `json:"sourceAddress"` + DestAddress string `json:"destAddress"` + SourcePort string `json:"sourcePort"` + DestPort string `json:"destPort"` + Action string `json:"action"` + Description string `json:"description"` +} + +type ListCfwArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} diff --git a/bce-sdk-go/services/csn/client.go b/bce-sdk-go/services/csn/client.go new file mode 100644 index 0000000..7be44cb --- /dev/null +++ b/bce-sdk-go/services/csn/client.go @@ -0,0 +1,525 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 csn + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "http://csn.baidubce.com" + DEFAULT_MAX_PARALLEL = 10 + MULTIPART_ALIGN = 1 << 20 // 1MB + MIN_MULTIPART_SIZE = 1 << 20 // 1MB + DEFAULT_MULTIPART_SIZE = 12 * (1 << 20) // 12MB + MAX_PART_NUMBER = 10000 +) + +// Client of bcd service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient + + // Fileds that used in parallel operation for BOS service + MaxParallel int64 + MultipartSize int64 +} + +// NewClient make the bcd service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer), + DEFAULT_MAX_PARALLEL, DEFAULT_MULTIPART_SIZE} + return client, nil +} + +// AttachInstance - 将网络实例加载进云智能网。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) AttachInstance(csnId string, body *AttachInstanceRequest, clientToken string) error { + return AttachInstance(c, csnId, body, clientToken) +} + +// BindCsnBp - 带宽包绑定云智能网。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) BindCsnBp(csnBpId string, body *BindCsnBpRequest, clientToken string) error { + return BindCsnBp(c, csnBpId, body, clientToken) +} + +// CreateAssociation - 创建路由表的关联关系。 +// +// PARAMS: +// - csnRtId: 云智能网路由表的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateAssociation(csnRtId string, body *CreateAssociationRequest, + clientToken string) error { + return CreateAssociation(c, csnRtId, body, clientToken) +} + +// CreateCsn - 创建云智能网。 +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - *CreateCsnResponse: +// - error: the return error if any occurs +func (c *Client) CreateCsn(body *CreateCsnRequest, clientToken string) ( + *CreateCsnResponse, error) { + return CreateCsn(c, body, clientToken) +} + +// CreateCsnBp - 创建云智能网共享带宽包。 +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - *CreateCsnBpResponse: +// - error: the return error if any occurs +func (c *Client) CreateCsnBp(body *CreateCsnBpRequest, clientToken string) ( + *CreateCsnBpResponse, error) { + return CreateCsnBp(c, body, clientToken) +} + +// CreateCsnBpLimit - 创建带宽包中两个地域间的地域带宽。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateCsnBpLimit(csnBpId string, body *CreateCsnBpLimitRequest, clientToken string) error { + return CreateCsnBpLimit(c, csnBpId, body, clientToken) +} + +// CreatePropagation - 创建路由表的学习关系。 +// +// PARAMS: +// - csnRtId: 云智能网路由表的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreatePropagation(csnRtId string, body *CreatePropagationRequest, + clientToken string) error { + return CreatePropagation(c, csnRtId, body, clientToken) +} + +// CreateRouteRule - 添加云智能网路由表的路由条目。 +// +// PARAMS: +// - csnRtId: 云智能网路由表的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateRouteRule(csnRtId string, body *CreateRouteRuleRequest, + clientToken string) error { + return CreateRouteRule(c, csnRtId, body, clientToken) +} + +// DeleteAssociation - 删除云智能网路由表的关联关系。 +// +// PARAMS: +// - csnRtId: 路由表的ID +// - attachId: 网络实例在云智能网中的身份ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteAssociation(csnRtId string, attachId string, clientToken string) error { + return DeleteAssociation(c, csnRtId, attachId, clientToken) +} + +// DeleteCsn - 删除云智能网。 已经加载了网络实例的云智能网不能直接删除,必须先卸载实例。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteCsn(csnId string, clientToken string) error { + return DeleteCsn(c, csnId, clientToken) +} + +// DeleteCsnBp - 删除带宽包。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteCsnBp(csnBpId string, clientToken string) error { + return DeleteCsnBp(c, csnBpId, clientToken) +} + +// DeleteCsnBpLimit - 删除带宽包中两个地域间的地域带宽。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteCsnBpLimit(csnBpId string, body *DeleteCsnBpLimitRequest, + clientToken string) error { + return DeleteCsnBpLimit(c, csnBpId, body, clientToken) +} + +// DeletePropagation - 删除云智能网路由表的学习关系。 +// +// PARAMS: +// - csnRtId: 路由表的ID +// - attachId: 网络实例在云智能网中的身份ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeletePropagation(csnRtId string, attachId string, clientToken string) error { + return DeletePropagation(c, csnRtId, attachId, clientToken) +} + +// DeleteRouteRule - 删除云智能网路由表的指定路由条目。 +// +// PARAMS: +// - csnRtId: 路由表的ID +// - csnRtRuleId: 路由条目的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteRouteRule(csnRtId string, csnRtRuleId string, clientToken string) error { + return DeleteRouteRule(c, csnRtId, csnRtRuleId, clientToken) +} + +// DetachInstance - 从云智能网中移出指定的网络实例。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DetachInstance(csnId string, body *DetachInstanceRequest, clientToken string) error { + return DetachInstance(c, csnId, body, clientToken) +} + +// GetCsn - 查询云智能网详情。 +// +// PARAMS: +// - csnId: csnId +// +// RETURNS: +// - *api.GetCsnResponse: +// - error: the return error if any occurs +func (c *Client) GetCsn(csnId string) (*GetCsnResponse, error) { + return GetCsn(c, csnId) +} + +// GetCsnBp - 查询指定云智能网带宽包详情。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// +// RETURNS: +// - *GetCsnBpResponse: +// - error: the return error if any occurs +func (c *Client) GetCsnBp(csnBpId string) (*GetCsnBpResponse, error) { + return GetCsnBp(c, csnBpId) +} + +// ListAssociation - 查询指定云智能网路由表的关联关系。 +// +// PARAMS: +// - csnRtId: 云智能网路由表的ID +// +// RETURNS: +// - *ListAssociationResponse: +// - error: the return error if any occurs +func (c *Client) ListAssociation(csnRtId string) (*ListAssociationResponse, error) { + return ListAssociation(c, csnRtId) +} + +// ListCsn - 查询云智能网列表。 +// +// PARAMS: +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListCsnResponse: +// - error: the return error if any occurs +func (c *Client) ListCsn(listCsnArgs *ListCsnArgs) (*ListCsnResponse, error) { + return ListCsn(c, listCsnArgs) +} + +// ListCsnBp - 查询云智能网带宽包列表。 +// +// PARAMS: +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListCsnBpResponse: +// - error: the return error if any occurs +func (c *Client) ListCsnBp(listCsnBpArgs *ListCsnBpArgs) (*ListCsnBpResponse, error) { + return ListCsnBp(c, listCsnBpArgs) +} + +// ListCsnBpLimit - 查询带宽包的地域带宽列表。 +// +// PARAMS: +// - csnBpId: +// +// RETURNS: +// - *ListCsnBpLimitResponse: +// - error: the return error if any occurs +func (c *Client) ListCsnBpLimit(csnBpId string) (*ListCsnBpLimitResponse, error) { + return ListCsnBpLimit(c, csnBpId) +} + +// ListCsnBpLimitByCsnId - 查询云智能网的地域带宽列表。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - body: body参数 +// +// RETURNS: +// - *ListCsnBpLimitByCsnIdResponse: +// - error: the return error if any occurs +func (c *Client) ListCsnBpLimitByCsnId(csnId string) ( + *ListCsnBpLimitByCsnIdResponse, error) { + return ListCsnBpLimitByCsnId(c, csnId) +} + +// ListInstance - 查询指定云智能网下加载的网络实例信息。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListInstanceResponse: +// - error: the return error if any occurs +func (c *Client) ListInstance(csnId string, listInstanceArgs *ListInstanceArgs) ( + *ListInstanceResponse, error) { + return ListInstance(c, csnId, listInstanceArgs) +} + +// ListPropagation - 查询指定云智能网路由表的学习关系。 +// +// PARAMS: +// - csnRtId: 云智能网路由表的ID +// +// RETURNS: +// - *ListPropagationResponse: +// - error: the return error if any occurs +func (c *Client) ListPropagation(csnRtId string) (*ListPropagationResponse, error) { + return ListPropagation(c, csnRtId) +} + +// ListRouteRule - 查询指定云智能网路由表的路由条目。 +// +// PARAMS: +// - csnRtId: 云智能网路由表的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000。缺省值为1000 +// +// RETURNS: +// - *ListRouteRuleResponse: +// - error: the return error if any occurs +func (c *Client) ListRouteRule(csnRtId string, listRouteRuleArgs *ListRouteRuleArgs) ( + *ListRouteRuleResponse, error) { + return ListRouteRule(c, csnRtId, listRouteRuleArgs) +} + +// ListRouteTable - 查询云智能网的路由表列表。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListRouteTableResponse: +// - error: the return error if any occurs +func (c *Client) ListRouteTable(csnId string, listRouteTableArgs *ListRouteTableArgs) ( + *ListRouteTableResponse, error) { + return ListRouteTable(c, csnId, listRouteTableArgs) +} + +// ListTgw - 查询云智能网TGW列表。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListTgwResponse: +// - error: the return error if any occurs +func (c *Client) ListTgw(csnId string, listTgwArgs *ListTgwArgs) ( + *ListTgwResponse, error) { + return ListTgw(c, csnId, listTgwArgs) +} + +// ListTgwRule - 查询指定TGW的路由条目。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - tgwId: TGW的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *ListTgwRuleResponse: +// - error: the return error if any occurs +func (c *Client) ListTgwRule(csnId string, tgwId string, listTgwRuleArgs *ListTgwRuleArgs, +) (*ListTgwRuleResponse, error) { + return ListTgwRule(c, csnId, tgwId, listTgwRuleArgs) +} + +// ResizeCsnBp - 带宽包的带宽升降级。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) ResizeCsnBp(csnBpId string, body *ResizeCsnBpRequest, clientToken string) error { + return ResizeCsnBp(c, csnBpId, body, clientToken) +} + +// UnbindCsnBp - 带宽包解绑云智能网。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UnbindCsnBp(csnBpId string, body *UnbindCsnBpRequest, clientToken string) error { + return UnbindCsnBp(c, csnBpId, body, clientToken) +} + +// UpdateCsn - 更新云智能网。 更新云智能网的名称和描述。 +// +// PARAMS: +// - csnId: 云智能网ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateCsn(csnId string, body *UpdateCsnRequest, clientToken string) error { + return UpdateCsn(c, csnId, body, clientToken) +} + +// UpdateCsnBp - 更新带宽包的名称信息。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateCsnBp(csnBpId string, body *UpdateCsnBpRequest, clientToken string) error { + return UpdateCsnBp(c, csnBpId, body, clientToken) +} + +// UpdateCsnBpLimit - 更新带宽包中两个地域间的地域带宽。 +// +// PARAMS: +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateCsnBpLimit(csnBpId string, body *UpdateCsnBpLimitRequest, + clientToken string) error { + return UpdateCsnBpLimit(c, csnBpId, body, clientToken) +} + +// UpdateTgw - 更新TGW的名称、描述。 +// +// PARAMS: +// - csnId: 云智能网的ID +// - tgwId: TGW实例的ID +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateTgw(csnId string, tgwId string, body *UpdateTgwRequest, + clientToken string) error { + return UpdateTgw(c, csnId, tgwId, body, clientToken) +} diff --git a/bce-sdk-go/services/csn/client_test.go b/bce-sdk-go/services/csn/client_test.go new file mode 100644 index 0000000..373278e --- /dev/null +++ b/bce-sdk-go/services/csn/client_test.go @@ -0,0 +1,374 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 csn + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + CsnClient *Client +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + f = filepath.Dir(f) + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + CsnClient, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) +} + +func TestClient_CreateCsn(t *testing.T) { + desc := "desc" + args := &CreateCsnRequest{ + Name: "csn_api_1", + Description: &desc, + } + + result, err := CsnClient.CreateCsn(args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) + CsnId := result.CsnId + log.Debug(CsnId) +} + +func TestClient_UpdateCsn(t *testing.T) { + name := "csn_api_2" + args := &UpdateCsnRequest{ + Name: &name, + } + + err := CsnClient.UpdateCsn("csn-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteCsn(t *testing.T) { + err := CsnClient.DeleteCsn("csn-xxxxxxxxxxx", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListCsn(t *testing.T) { + args := &ListCsnArgs{} + result, err := CsnClient.ListCsn(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_GetCsn(t *testing.T) { + result, err := CsnClient.GetCsn("csn-xxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_ListInstance(t *testing.T) { + args := &ListInstanceArgs{} + result, err := CsnClient.ListInstance("csn-xxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_AttachInstance(t *testing.T) { + args := &AttachInstanceRequest{ + InstanceId: "vpc-xxxxxxxxxxx", + InstanceType: "vpc", + InstanceRegion: "gz", + } + err := CsnClient.AttachInstance("csn-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DetachInstance(t *testing.T) { + args := &DetachInstanceRequest{ + InstanceId: "vpc-xxxxxxxxxxx", + InstanceType: "vpc", + InstanceRegion: "gz", + } + err := CsnClient.DetachInstance("csn-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListRouteTable(t *testing.T) { + args := &ListRouteTableArgs{} + result, err := CsnClient.ListRouteTable("csn-xxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_CreateRouteRule(t *testing.T) { + args := &CreateRouteRuleRequest{ + AttachId: "tgwAttach-xxxxxxxxxxx", + DestAddress: "0.0.0.0/0", + RouteType: "custom", + } + err := CsnClient.CreateRouteRule("csnRt-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListRouteRuleArgs(t *testing.T) { + args := &ListRouteRuleArgs{} + result, err := CsnClient.ListRouteRule("csnRt-xxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_DeleteRouteRule(t *testing.T) { + err := CsnClient.DeleteRouteRule("csnRt-xxxxxxxxxxx", + "xxxxxxxxxxx-32ac-4949-a3ca-xxxxxxxxxxx", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreatePropagation(t *testing.T) { + desc := "desc" + args := &CreatePropagationRequest{ + AttachId: "tgwAttach-xxxxxxxxxxx", + Description: &desc, + } + err := CsnClient.CreatePropagation("csnRt-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListPropagation(t *testing.T) { + result, err := CsnClient.ListPropagation("csnRt-xxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_DeletePropagation(t *testing.T) { + err := CsnClient.DeletePropagation("csnRt-xxxxxxxxxxx", + "tgwAttach-xxxxxxxxxxx", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAssociation(t *testing.T) { + desc := "desc" + args := &CreateAssociationRequest{ + AttachId: "tgwAttach-xxxxxxxxxxx", + Description: &desc, + } + err := CsnClient.CreateAssociation("csnRt-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListAssociation(t *testing.T) { + result, err := CsnClient.ListAssociation("csnRt-xxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_DeleteAssociation(t *testing.T) { + err := CsnClient.DeleteAssociation("csnRt-xxxxxxxxxxx", + "tgwAttach-xxxxxxxxxxx", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateCsnBp(t *testing.T) { + instanceType := "center" + args := &CreateCsnBpRequest{ + Name: "csnBp_api_1", + Bandwidth: 100, + InterworkType: &instanceType, + GeographicA: "China", + GeographicB: "China", + Billing: Billing{ + PaymentTiming: "Postpaid", + }, + } + result, err := CsnClient.CreateCsnBp(args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_UpdateCsnBp(t *testing.T) { + args := &UpdateCsnBpRequest{ + Name: "csnBp_api_2", + } + err := CsnClient.UpdateCsnBp("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteCsnBp(t *testing.T) { + err := CsnClient.DeleteCsnBp("csnBp-xxxxxxxxxxx", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListCsnBp(t *testing.T) { + args := &ListCsnBpArgs{} + result, err := CsnClient.ListCsnBp(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_GetCsnBp(t *testing.T) { + result, err := CsnClient.GetCsnBp("csnBp-xxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_ResizeCsnBp(t *testing.T) { + args := &ResizeCsnBpRequest{ + Bandwidth: 50, + } + err := CsnClient.ResizeCsnBp("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindCsnBp(t *testing.T) { + args := &BindCsnBpRequest{ + CsnId: "csn-xxxxxxxxxxx", + } + err := CsnClient.BindCsnBp("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindCsnBpRequest(t *testing.T) { + args := &UnbindCsnBpRequest{ + CsnId: "csn-xxxxxxxxxxx", + } + err := CsnClient.UnbindCsnBp("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateCsnBpLimit(t *testing.T) { + args := &CreateCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "gz", + Bandwidth: 10, + } + err := CsnClient.CreateCsnBpLimit("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListCsnBpLimit(t *testing.T) { + result, err := CsnClient.ListCsnBpLimit("csnBp-xxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_DeleteCsnBpLimit(t *testing.T) { + args := &DeleteCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "gz", + } + err := CsnClient.DeleteCsnBpLimit("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateCsnBpLimit(t *testing.T) { + args := &UpdateCsnBpLimitRequest{ + LocalRegion: "bj", + PeerRegion: "gz", + Bandwidth: 20, + } + err := CsnClient.UpdateCsnBpLimit("csnBp-xxxxxxxxxxx", args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListCsnBpLimitByCsnId(t *testing.T) { + result, err := CsnClient.ListCsnBpLimitByCsnId("csn-xxxxxxxxxxx") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_ListTgw(t *testing.T) { + args := &ListTgwArgs{} + result, err := CsnClient.ListTgw("csn-xxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func TestClient_UpdateTgw(t *testing.T) { + name := "tgw_1" + desc := "desc" + args := &UpdateTgwRequest{ + Name: &name, + Description: &desc, + } + err := CsnClient.UpdateTgw("csn-xxxxxxxxxxx", "tgw-xxxxxxxxxxx", + args, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListTgwRuleArgs(t *testing.T) { + args := &ListTgwRuleArgs{} + result, err := CsnClient.ListTgwRule("csn-xxxxxxxxxxx", "tgw-xxxxxxxxxxx", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/csn/csn.go b/bce-sdk-go/services/csn/csn.go new file mode 100644 index 0000000..3842dc6 --- /dev/null +++ b/bce-sdk-go/services/csn/csn.go @@ -0,0 +1,1258 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 csn + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" + "strings" +) + +// AttachInstance - 将网络实例加载进云智能网。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func AttachInstance(cli bce.Client, csnId string, body *AttachInstanceRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/[csnId]" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + req.SetParam("attach", "") + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// BindCsnBp - 带宽包绑定云智能网。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func BindCsnBp(cli bce.Client, csnBpId string, body *BindCsnBpRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/bp/[csnBpId]" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetParam("bind", "") + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreateAssociation - 创建路由表的关联关系。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 云智能网路由表的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreateAssociation(cli bce.Client, csnRtId string, body *CreateAssociationRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn/routeTable/[csnRtId]/association" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreateCsn - 创建云智能网。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - *api.CreateCsnResponse: +// - error: the return error if any occurs +func CreateCsn(cli bce.Client, body *CreateCsnRequest, clientToken string) ( + *CreateCsnResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn" + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &CreateCsnResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// CreateCsnBp - 创建云智能网共享带宽包。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - *api.CreateCsnBpResponse: +// - error: the return error if any occurs +func CreateCsnBp(cli bce.Client, body *CreateCsnBpRequest, clientToken string) ( + *CreateCsnBpResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn/bp" + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &CreateCsnBpResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// CreateCsnBpLimit - 创建带宽包中两个地域间的地域带宽。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreateCsnBpLimit(cli bce.Client, csnBpId string, body *CreateCsnBpLimitRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn/bp/[csnBpId]/limit" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreatePropagation - 创建路由表的学习关系。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 云智能网路由表的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreatePropagation(cli bce.Client, csnRtId string, body *CreatePropagationRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn/routeTable/[csnRtId]/propagation" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreateRouteRule - 添加云智能网路由表的路由条目。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 云智能网路由表的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreateRouteRule(cli bce.Client, csnRtId string, body *CreateRouteRuleRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn/routeTable/[csnRtId]/rule" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteAssociation - 删除云智能网路由表的关联关系。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 路由表的ID +// - attachId: 网络实例在云智能网中的身份ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func DeleteAssociation(cli bce.Client, csnRtId string, attachId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/csn/routeTable/[csnRtId]/association/[attachId]" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + path = strings.Replace(path, "[attachId]", attachId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteCsn - 删除云智能网。 已经加载了网络实例的云智能网不能直接删除,必须先卸载实例。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func DeleteCsn(cli bce.Client, csnId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/csn/[csnId]" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteCsnBp - 删除带宽包。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func DeleteCsnBp(cli bce.Client, csnBpId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/csn/bp/[csnBpId]" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteCsnBpLimit - 删除带宽包中两个地域间的地域带宽。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DeleteCsnBpLimit(cli bce.Client, csnBpId string, body *DeleteCsnBpLimitRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/csn/bp/[csnBpId]/limit/delete" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeletePropagation - 删除云智能网路由表的学习关系。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 路由表的ID +// - attachId: 网络实例在云智能网中的身份ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func DeletePropagation(cli bce.Client, csnRtId string, attachId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/csn/routeTable/[csnRtId]/propagation/[attachId]" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + path = strings.Replace(path, "[attachId]", attachId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteRouteRule - 删除云智能网路由表的指定路由条目。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 路由表的ID +// - csnRtRuleId: 路由条目的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// +// RETURNS: +// - error: the return error if any occurs +func DeleteRouteRule(cli bce.Client, csnRtId string, csnRtRuleId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/csn/routeTable/[csnRtId]/rule/[csnRtRuleId]" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + path = strings.Replace(path, "[csnRtRuleId]", csnRtRuleId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DetachInstance - 从云智能网中移出指定的网络实例。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DetachInstance(cli bce.Client, csnId string, body *DetachInstanceRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/[csnId]" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + req.SetParam("detach", "") + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// GetCsn - 查询云智能网详情。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: csnId +// +// RETURNS: +// - *api.GetCsnResponse: +// - error: the return error if any occurs +func GetCsn(cli bce.Client, csnId string) (*GetCsnResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/[csnId]" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &GetCsnResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// GetCsnBp - 查询指定云智能网带宽包详情。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// +// RETURNS: +// - *api.GetCsnBpResponse: +// - error: the return error if any occurs +func GetCsnBp(cli bce.Client, csnBpId string) (*GetCsnBpResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/bp/[csnBpId]" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &GetCsnBpResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListAssociation - 查询指定云智能网路由表的关联关系。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 云智能网路由表的ID +// +// RETURNS: +// - *api.ListAssociationResponse: +// - error: the return error if any occurs +func ListAssociation(cli bce.Client, csnRtId string) (*ListAssociationResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/routeTable/[csnRtId]/association" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListAssociationResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListCsn - 查询云智能网列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *api.ListCsnResponse: +// - error: the return error if any occurs +func ListCsn(cli bce.Client, listCsnArgs *ListCsnArgs) (*ListCsnResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn" + req.SetUri(path) + if "" != listCsnArgs.Marker { + req.SetParam("marker", listCsnArgs.Marker) + } + if 0 != listCsnArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listCsnArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListCsnResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListCsnBp - 查询云智能网带宽包列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *api.ListCsnBpResponse: +// - error: the return error if any occurs +func ListCsnBp(cli bce.Client, listCsnBpArgs *ListCsnBpArgs) (*ListCsnBpResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/bp" + req.SetUri(path) + if "" != listCsnBpArgs.Marker { + req.SetParam("marker", listCsnBpArgs.Marker) + } + if 0 != listCsnBpArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listCsnBpArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListCsnBpResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListCsnBpLimit - 查询带宽包的地域带宽列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: +// +// RETURNS: +// - *api.ListCsnBpLimitResponse: +// - error: the return error if any occurs +func ListCsnBpLimit(cli bce.Client, csnBpId string) (*ListCsnBpLimitResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/bp/[csnBpId]/limit" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListCsnBpLimitResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListCsnBpLimitByCsnId - 查询云智能网的地域带宽列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - body: +// +// RETURNS: +// - *api.ListCsnBpLimitByCsnIdResponse: +// - error: the return error if any occurs +func ListCsnBpLimitByCsnId(cli bce.Client, csnId string) ( + *ListCsnBpLimitByCsnIdResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/[csnId]/bp/limit" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListCsnBpLimitByCsnIdResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListInstance - 查询指定云智能网下加载的网络实例信息。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *api.ListInstanceResponse: +// - error: the return error if any occurs +func ListInstance(cli bce.Client, csnId string, listInstanceArgs *ListInstanceArgs) ( + *ListInstanceResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/[csnId]/instance" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + if "" != listInstanceArgs.Marker { + req.SetParam("marker", listInstanceArgs.Marker) + } + if 0 != listInstanceArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listInstanceArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListInstanceResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListPropagation - 查询指定云智能网路由表的学习关系。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 云智能网路由表的ID +// +// RETURNS: +// - *api.ListPropagationResponse: +// - error: the return error if any occurs +func ListPropagation(cli bce.Client, csnRtId string) (*ListPropagationResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/routeTable/[csnRtId]/propagation" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListPropagationResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListRouteRule - 查询指定云智能网路由表的路由条目。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnRtId: 云智能网路由表的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000。缺省值为1000 +// +// RETURNS: +// - *api.ListRouteRuleResponse: +// - error: the return error if any occurs +func ListRouteRule(cli bce.Client, csnRtId string, listRouteRuleArgs *ListRouteRuleArgs) ( + *ListRouteRuleResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/routeTable/[csnRtId]/rule" + path = strings.Replace(path, "[csnRtId]", csnRtId, -1) + req.SetUri(path) + if "" != listRouteRuleArgs.Marker { + req.SetParam("marker", listRouteRuleArgs.Marker) + } + if 0 != listRouteRuleArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listRouteRuleArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListRouteRuleResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListRouteTable - 查询云智能网的路由表列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *api.ListRouteTableResponse: +// - error: the return error if any occurs +func ListRouteTable(cli bce.Client, csnId string, listRouteTableArgs *ListRouteTableArgs) ( + *ListRouteTableResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/[csnId]/routeTable" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + if "" != listRouteTableArgs.Marker { + req.SetParam("marker", listRouteTableArgs.Marker) + } + if 0 != listRouteTableArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listRouteTableArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListRouteTableResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListTgw - 查询云智能网TGW列表。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// +// RETURNS: +// - *api.ListTgwResponse: +// - error: the return error if any occurs +func ListTgw(cli bce.Client, csnId string, listTgwArgs *ListTgwArgs) (*ListTgwResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/[csnId]/tgw" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + if "" != listTgwArgs.Marker { + req.SetParam("marker", listTgwArgs.Marker) + } + if 0 != listTgwArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listTgwArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListTgwResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListTgwRule - 查询指定TGW的路由条目。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - tgwId: TGW的ID +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量不超过1000,缺省值为1000 +// - body: +// +// RETURNS: +// - *api.ListTgwRuleResponse: +// - error: the return error if any occurs +func ListTgwRule(cli bce.Client, csnId string, tgwId string, listTgwRuleArgs *ListTgwRuleArgs, +) (*ListTgwRuleResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/csn/[csnId]/tgw/[tgwId]/rule" + path = strings.Replace(path, "[csnId]", csnId, -1) + path = strings.Replace(path, "[tgwId]", tgwId, -1) + req.SetUri(path) + if "" != listTgwRuleArgs.Marker { + req.SetParam("marker", listTgwRuleArgs.Marker) + } + if 0 != listTgwRuleArgs.MaxKeys { + req.SetParam("maxKeys", strconv.Itoa(listTgwRuleArgs.MaxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListTgwRuleResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ResizeCsnBp - 带宽包的带宽升降级。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func ResizeCsnBp(cli bce.Client, csnBpId string, body *ResizeCsnBpRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/bp/[csnBpId]" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetParam("resize", "") + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UnbindCsnBp - 带宽包解绑云智能网。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UnbindCsnBp(cli bce.Client, csnBpId string, body *UnbindCsnBpRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/bp/[csnBpId]" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetParam("unbind", "") + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateCsn - 更新云智能网。 更新云智能网的名称和描述。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串,详见ClientToken幂等性 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateCsn(cli bce.Client, csnId string, body *UpdateCsnRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/[csnId]" + path = strings.Replace(path, "[csnId]", csnId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateCsnBp - 更新带宽包的名称信息。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateCsnBp(cli bce.Client, csnBpId string, body *UpdateCsnBpRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/bp/[csnBpId]" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateCsnBpLimit - 更新带宽包中两个地域间的地域带宽。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnBpId: 带宽包的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateCsnBpLimit(cli bce.Client, csnBpId string, body *UpdateCsnBpLimitRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/bp/[csnBpId]/limit" + path = strings.Replace(path, "[csnBpId]", csnBpId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateTgw - 更新TGW的名称、描述。 +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - csnId: 云智能网的ID +// - tgwId: TGW实例的ID +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateTgw(cli bce.Client, csnId string, tgwId string, body *UpdateTgwRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/csn/[csnId]/tgw/[tgwId]" + path = strings.Replace(path, "[csnId]", csnId, -1) + path = strings.Replace(path, "[tgwId]", tgwId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetHeader("Content-Type", "application/json;charset=UTF-8") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/csn/model.go b/bce-sdk-go/services/csn/model.go new file mode 100644 index 0000000..c3423d4 --- /dev/null +++ b/bce-sdk-go/services/csn/model.go @@ -0,0 +1,397 @@ +/* + * Copyright Baidu, Inc. + * + * 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 csn + +type AttachInstanceRequest struct { + InstanceType string `json:"instanceType"` + InstanceId string `json:"instanceId"` + InstanceRegion string `json:"instanceRegion"` + InstanceAccountId *string `json:"instanceAccountId,omitempty"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +type BindCsnBpRequest struct { + CsnId string `json:"csnId"` +} + +type CreateAssociationRequest struct { + AttachId string `json:"attachId"` + Description *string `json:"description,omitempty"` +} + +type CreateCsnBpLimitRequest struct { + LocalRegion string `json:"localRegion"` + PeerRegion string `json:"peerRegion"` + Bandwidth int32 `json:"bandwidth"` +} + +type CreateCsnBpRequest struct { + Name string `json:"name"` + InterworkType *string `json:"interworkType,omitempty"` + Bandwidth int32 `json:"bandwidth"` + GeographicA string `json:"geographicA"` + GeographicB string `json:"geographicB"` + Billing Billing `json:"billing"` +} + +type CreateCsnBpResponse struct { + CsnBpId string `json:"csnBpId"` +} + +type CreateCsnRequest struct { + Name string `json:"name"` + Description *string `json:"description,omitempty"` +} + +type CreateCsnResponse struct { + CsnId string `json:"csnId"` +} + +type CreatePropagationRequest struct { + AttachId string `json:"attachId"` + Description *string `json:"description,omitempty"` +} + +type CreateRouteRuleRequest struct { + AttachId string `json:"attachId"` + DestAddress string `json:"destAddress"` + RouteType string `json:"routeType"` +} + +type Csn struct { + CsnId string `json:"csnId"` + Name string `json:"name"` + Description string `json:"description"` + Status string `json:"status"` + InstanceNum int32 `json:"instanceNum"` + CsnBpNum int32 `json:"csnBpNum"` +} + +type CsnBp struct { + CsnBpId string `json:"csnBpId"` + Name string `json:"name"` + Bandwidth int32 `json:"bandwidth"` + UsedBandwidth int32 `json:"usedBandwidth"` + CsnId string `json:"csnId"` + InterworkType string `json:"interworkType"` + InterworkRegion string `json:"interworkRegion"` + Status string `json:"status"` + PaymentTiming string `json:"paymentTiming"` + ExpireTime string `json:"expireTime"` + CreatedTime string `json:"createdTime"` +} + +type CsnBpLimit struct { + CsnBpId string `json:"csnBpId"` + CsnId string `json:"csnId"` + LocalRegion string `json:"localRegion"` + PeerRegion string `json:"peerRegion"` + Bandwidth int32 `json:"bandwidth"` +} + +type CsnRouteTable struct { + CsnRtId string `json:"csnRtId"` + Name string `json:"name"` + Description string `json:"description"` + Type string `json:"type"` +} + +type CsnRtAssociation struct { + AttachId string `json:"attachId"` + Description string `json:"description"` + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + InstanceRegion string `json:"instanceRegion"` + InstanceType string `json:"instanceType"` + Status string `json:"status"` +} + +type CsnRtPropagation struct { + AttachId string `json:"attachId"` + Description string `json:"description"` + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + InstanceRegion string `json:"instanceRegion"` + InstanceType string `json:"instanceType"` + Status string `json:"status"` +} + +type CsnRtRule struct { + RuleId string `json:"ruleId"` + RouteType string `json:"routeType"` + CsnId string `json:"csnId"` + CsnRtId string `json:"csnRtId"` + Description string `json:"description"` + FromAttachId string `json:"fromAttachId"` + Status string `json:"status"` + SourceAddress string `json:"sourceAddress"` + DestAddress string `json:"destAddress"` + NextHopId string `json:"nextHopId"` + NextHopName string `json:"nextHopName"` + NextHopRegion string `json:"nextHopRegion"` + NextHopType string `json:"nextHopType"` + AsPath string `json:"asPath"` + Community string `json:"community"` + BlackHole bool `json:"blackHole"` +} + +type DeleteCsnBpLimitRequest struct { + LocalRegion string `json:"localRegion"` + PeerRegion string `json:"peerRegion"` +} + +type DetachInstanceRequest struct { + InstanceType string `json:"instanceType"` + InstanceId string `json:"instanceId"` + InstanceRegion string `json:"instanceRegion"` + InstanceAccountId *string `json:"instanceAccountId,omitempty"` +} + +type GetCsnResponse struct { + Name string `json:"name"` + Description string `json:"description"` + CsnId string `json:"csnId"` + Status string `json:"status"` + InstanceNum int32 `json:"instanceNum"` + CsnBpNum int32 `json:"csnBpNum"` +} + +type GetCsnBpResponse struct { + CsnBpId string `json:"csnBpId"` + Name string `json:"name"` + Bandwidth int32 `json:"bandwidth"` + UsedBandwidth int32 `json:"usedBandwidth"` + CsnId string `json:"csnId"` + InterworkType string `json:"interworkType"` + InterworkRegion string `json:"interworkRegion"` + Status string `json:"status"` + PaymentTiming string `json:"paymentTiming"` + ExpireTime string `json:"expireTime"` + CreatedTime string `json:"createdTime"` +} + +type Instance struct { + AttachId string `json:"attachId"` + InstanceType string `json:"instanceType"` + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + InstanceRegion string `json:"instanceRegion"` + InstanceAccountId string `json:"instanceAccountId"` + Status string `json:"status"` +} + +type ListAssociationResponse struct { + Associations []CsnRtAssociation `json:"associations"` +} + +type ListAssociationResponseAssociations struct { +} + +type ListCsnBpLimitByCsnIdRequest struct { + LocalRegion string `json:"localRegion"` + PeerRegion string `json:"peerRegion"` +} + +type ListCsnBpLimitByCsnIdResponse struct { + BpLimits []CsnBpLimit `json:"bpLimits"` +} + +type ListCsnBpLimitByCsnIdResponseBpLimits struct { +} + +type ListCsnBpLimitResponse struct { + BpLimits []CsnBpLimit `json:"bpLimits"` +} + +type ListCsnBpLimitResponseBpLimits struct { +} + +type ListCsnBpResponse struct { + CsnBps []CsnBp `json:"csnBps"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListCsnBpResponseCsnBps struct { +} + +type ListCsnResponse struct { + Csns []Csn `json:"csns"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListCsnResponseCsns struct { +} + +type ListInstanceResponse struct { + Instances []Instance `json:"instances"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListInstanceResponseInstances struct { +} + +type ListPropagationResponse struct { + Propagations []CsnRtPropagation `json:"propagations"` +} + +type ListPropagationResponsePropagations struct { +} + +type ListRouteRuleResponse struct { + CsnRtRules []CsnRtRule `json:"csnRtRules"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListRouteRuleResponseCsnRtRules struct { +} + +type ListRouteTableResponse struct { + CsnRts []CsnRouteTable `json:"csnRts"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListRouteTableResponseCsnRts struct { +} + +type ListTgwResponse struct { + Tgws []Tgw `json:"tgws"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListTgwRuleResponse struct { + TgwRtRules []TgwRtRule `json:"tgwRtRules"` + Marker *string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker,omitempty"` + MaxKeys int32 `json:"maxKeys"` +} + +type ListTgwRuleResponseTgwRtRules struct { +} + +type Reservation struct { + ReservationLength int32 `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} + +type ResizeCsnBpRequest struct { + Bandwidth int32 `json:"bandwidth"` +} + +type Tgw struct { + TgwId string `json:"tgwId"` + CsnId string `json:"csnId"` + Name string `json:"name"` + Region string `json:"region"` + Description string `json:"description"` +} + +type TgwRtRule struct { + RuleId string `json:"ruleId"` + RouteType string `json:"routeType"` + CsnId string `json:"csnId"` + CsnRtId string `json:"csnRtId"` + FromAttachId string `json:"fromAttachId"` + Status string `json:"status"` + DestAddress string `json:"destAddress"` + NextHopId string `json:"nextHopId"` + NextHopName string `json:"nextHopName"` + NextHopRegion string `json:"nextHopRegion"` + NextHopType string `json:"nextHopType"` + AsPath string `json:"asPath"` + Community string `json:"community"` + BlackHole bool `json:"blackHole"` +} + +type UnbindCsnBpRequest struct { + CsnId string `json:"csnId"` +} + +type UpdateCsnBpLimitRequest struct { + LocalRegion string `json:"localRegion"` + PeerRegion string `json:"peerRegion"` + Bandwidth int32 `json:"bandwidth"` +} + +type UpdateCsnBpRequest struct { + Name string `json:"name"` +} + +type UpdateCsnRequest struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` +} + +type UpdateTgwRequest struct { + Name *string `json:"name,omitempty"` + Description *string `json:"description,omitempty"` +} + +type ListCsnArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListCsnBpArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListInstanceArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListRouteRuleArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListRouteTableArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListTgwArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListTgwRuleArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} diff --git a/bce-sdk-go/services/dbsc/client.go b/bce-sdk-go/services/dbsc/client.go new file mode 100644 index 0000000..86fb955 --- /dev/null +++ b/bce-sdk-go/services/dbsc/client.go @@ -0,0 +1,82 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 dbsc + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" +) + +const DEFAULT_SERVICE_DOMAIN = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + +// Client of BCC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the BCC service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endPoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endPoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +func (c *Client) CreateVolumeCluster(args *CreateVolumeClusterArgs) (*CreateVolumeClusterResult, error) { + return CreateVolumeCluster(c, args) +} + +func (c *Client) ListVolumeCluster(queryArgs *ListVolumeClusterArgs) (*ListVolumeClusterResult, error) { + return ListVolumeCluster(c, queryArgs) +} + +func (c *Client) GetVolumeClusterDetail(clusterId string) (*VolumeClusterDetail, error) { + return GetVolumeClusterDetail(c, clusterId) +} + +func (c *Client) ResizeVolumeCluster(clusterId string, args *ResizeVolumeClusterArgs) error { + return ResizeVolumeCluster(c, clusterId, args) +} + +func (c *Client) PurchaseReservedVolumeCluster(clusterId string, args *PurchaseReservedVolumeClusterArgs) error { + return PurchaseReservedVolumeCluster(c, clusterId, args) +} + +func (c *Client) AutoRenewVolumeCluster(args *AutoRenewVolumeClusterArgs) error { + return AutoRenewVolumeCluster(c, args) +} + +func (c *Client) CancelAutoRenewVolumeCluster(args *CancelAutoRenewVolumeClusterArgs) error { + return CancelAutoRenewVolumeCluster(c, args) +} diff --git a/bce-sdk-go/services/dbsc/client_test.go b/bce-sdk-go/services/dbsc/client_test.go new file mode 100644 index 0000000..0c157a6 --- /dev/null +++ b/bce-sdk-go/services/dbsc/client_test.go @@ -0,0 +1,135 @@ +package dbsc + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "runtime" + "testing" +) + +var ( + DBSC_CLIENT *Client +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 6; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "../config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + DBSC_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +func TestCreateVolumeCluster(t *testing.T) { + args := &CreateVolumeClusterArgs{ + PurchaseCount: 1, + ClusterSizeInGB: 97280, + ClusterName: "dbsc", + StorageType: StorageTypeHdd, + Billing: &Billing{ + PaymentTiming: PaymentTimingPrePaid, + Reservation: &Reservation{ + ReservationLength: 6, + ReservationTimeUnit: "MONTH", + }, + }, + RenewTimeUnit: "month", + RenewTime: 6, + } + result, err := DBSC_CLIENT.CreateVolumeCluster(args) + if err != nil { + fmt.Println(err) + } + clusterId := result.ClusterIds[0] + fmt.Println(clusterId) + if result.ClusterUuids != nil { + clusterUuid := result.ClusterUuids[0] + fmt.Println(clusterUuid) + } +} + +func TestListVolumeCluster(t *testing.T) { + args := &ListVolumeClusterArgs{} + result, err := DBSC_CLIENT.ListVolumeCluster(args) + if err != nil { + fmt.Println(err) + } + fmt.Println(result) +} + +func TestGetVolumeClusterDetail(t *testing.T) { + result, err := DBSC_CLIENT.GetVolumeClusterDetail("DC-xxxxxx") + if err != nil { + fmt.Println(err) + } + fmt.Println(result) +} + +func TestResizeVolumeCluster(t *testing.T) { + args := &ResizeVolumeClusterArgs{ + NewClusterSizeInGB: 107520, + } + err := DBSC_CLIENT.ResizeVolumeCluster("DC-yWfhpUbN", args) + if err != nil { + fmt.Println(err) + } +} + +func TestPurchaseReservedVolumeCluster(t *testing.T) { + args := &PurchaseReservedVolumeClusterArgs{ + Billing: &Billing{ + PaymentTiming: PaymentTimingPrePaid, + Reservation: &Reservation{ + ReservationLength: 6, + ReservationTimeUnit: "month", + }, + }, + } + err := DBSC_CLIENT.PurchaseReservedVolumeCluster("DC-yWfhpUbN", args) + if err != nil { + fmt.Println(err) + } +} + +func TestAutoRenewVolumeCluster(t *testing.T) { + args := &AutoRenewVolumeClusterArgs{ + ClusterId: "DC-yWfhpUbN", + RenewTime: 6, + RenewTimeUnit: "month", + } + err := DBSC_CLIENT.AutoRenewVolumeCluster(args) + if err != nil { + fmt.Println(err) + } +} + +func TestCancelAutoRenewVolumeCluster(t *testing.T) { + args := &CancelAutoRenewVolumeClusterArgs{ + ClusterId: "DC-yWfhpUbN", + } + err := DBSC_CLIENT.CancelAutoRenewVolumeCluster(args) + if err != nil { + fmt.Println(err) + } +} diff --git a/bce-sdk-go/services/dbsc/dedicatedVolumeCluster.go b/bce-sdk-go/services/dbsc/dedicatedVolumeCluster.go new file mode 100644 index 0000000..689a33d --- /dev/null +++ b/bce-sdk-go/services/dbsc/dedicatedVolumeCluster.go @@ -0,0 +1,235 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 dbsc + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +func CreateVolumeCluster(cli bce.Client, args *CreateVolumeClusterArgs) (*CreateVolumeClusterResult, error) { + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_CREATE_URI) + req.SetMethod(http.POST) + req.SetParam("uuidFlag", args.UuidFlag) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + err = cli.SendRequest(req, resp) + if err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &CreateVolumeClusterResult{} + err = resp.ParseJsonBody(jsonBody) + if err != nil { + return nil, err + } + return jsonBody, nil +} + +func ListVolumeCluster(cli bce.Client, queryArgs *ListVolumeClusterArgs) (*ListVolumeClusterResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_CREATE_URI) + req.SetMethod(http.GET) + + if queryArgs != nil { + if len(queryArgs.ZoneName) != 0 { + req.SetParam("zoneName", queryArgs.ZoneName) + } + if len(queryArgs.ClusterName) != 0 { + req.SetParam("clusterName", queryArgs.ClusterName) + } + if len(queryArgs.Marker) != 0 { + req.SetParam("marker", queryArgs.Marker) + } + if queryArgs.MaxKeys != 0 { + req.SetParam("maxKeys", strconv.Itoa(queryArgs.MaxKeys)) + } + } + + if queryArgs == nil || queryArgs.MaxKeys == 0 { + req.SetParam("maxKeys", "1000") + } + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListVolumeClusterResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetVolumeClusterDetail(cli bce.Client, clusterId string) (*VolumeClusterDetail, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_CREATE_URI + "/" + clusterId) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &VolumeClusterDetail{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func ResizeVolumeCluster(cli bce.Client, clusterId string, args *ResizeVolumeClusterArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_CREATE_URI + "/" + clusterId) + req.SetMethod(http.PUT) + req.SetParam("resize", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { _ = resp.Body().Close() }() + return nil +} + +func PurchaseReservedVolumeCluster(cli bce.Client, clusterId string, args *PurchaseReservedVolumeClusterArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_CREATE_URI + "/" + clusterId) + req.SetMethod(http.PUT) + + req.SetParam("purchaseReserved", "") + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { _ = resp.Body().Close() }() + return nil +} + +func AutoRenewVolumeCluster(cli bce.Client, args *AutoRenewVolumeClusterArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_AUTO_RENEW_URI) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { _ = resp.Body().Close() }() + + return nil +} + +func CancelAutoRenewVolumeCluster(cli bce.Client, args *CancelAutoRenewVolumeClusterArgs) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getVolumeClusterUri() + REQUEST_CANCEL_AUTO_RENEW_URI) + req.SetMethod(http.POST) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { _ = resp.Body().Close() }() + + return nil +} diff --git a/bce-sdk-go/services/dbsc/model.go b/bce-sdk-go/services/dbsc/model.go new file mode 100644 index 0000000..b02a31f --- /dev/null +++ b/bce-sdk-go/services/dbsc/model.go @@ -0,0 +1,114 @@ +package dbsc + +type CreateVolumeClusterArgs struct { + ZoneName string `json:"zoneName,omitempty"` + ClusterName string `json:"clusterName,omitempty"` + StorageType StorageType `json:"storageType,omitempty"` + ClusterSizeInGB int `json:"clusterSizeInGB,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + Billing *Billing `json:"billing"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` + UuidFlag string `json:"uuidFlag"` +} + +type Billing struct { + PaymentTiming PaymentTimingType `json:"paymentTiming,omitempty"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} + +type PaymentTimingType string + +const ( + PaymentTimingPrePaid PaymentTimingType = "Prepaid" + PaymentTimingPostPaid PaymentTimingType = "Postpaid" +) + +type StorageType string + +const ( + StorageTypeHP1 StorageType = "hp1" + StorageTypeHdd StorageType = "hdd" +) + +type CreateVolumeClusterResult struct { + ClusterIds []string `json:"clusterIds"` + ClusterUuids []string `json:"clusterUuids"` +} + +type ListVolumeClusterArgs struct { + Marker string + MaxKeys int + ClusterName string + ZoneName string +} + +type ListVolumeClusterResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Result []VolumeClusterModel `json:"result"` +} + +type VolumeClusterModel struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + CreatedTime string `json:"createdTime"` + ExpiredTime string `json:"expiredTime"` + Status string `json:"status"` + ZoneName string `json:"logicalZone"` + ProductType string `json:"productType"` + ClusterType string `json:"clusterType"` + TotalCapacity int `json:"totalCapacity"` + UsedCapacity int `json:"usedCapacity"` + AvailableCapacity int `json:"availableCapacity"` + ExpandingCapacity int `json:"expandingCapacity"` + CreatedVolumeNum int `json:"createdVolumeNum"` + EnableAutoRenew bool `json:"enableAutoRenew"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` +} + +type VolumeClusterDetail struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + CreatedTime string `json:"createdTime"` + ExpiredTime string `json:"expiredTime"` + Status string `json:"status"` + ZoneName string `json:"logicalZone"` + ProductType string `json:"productType"` + ClusterType string `json:"clusterType"` + TotalCapacity int `json:"totalCapacity"` + UsedCapacity int `json:"usedCapacity"` + AvailableCapacity int `json:"availableCapacity"` + ExpandingCapacity int `json:"expandingCapacity"` + CreatedVolumeNum int `json:"createdVolumeNum"` + AffiliatedCDSNumber []string `json:"affiliatedCDSNumber"` + EnableAutoRenew bool `json:"enableAutoRenew"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` +} + +type ResizeVolumeClusterArgs struct { + NewClusterSizeInGB int `json:"newClusterSizeInGB"` +} + +type PurchaseReservedVolumeClusterArgs struct { + Billing *Billing `json:"billing"` +} + +type AutoRenewVolumeClusterArgs struct { + ClusterId string `json:"clusterId"` + RenewTimeUnit string `json:"renewTimeUnit"` + RenewTime int `json:"renewTime"` +} + +type CancelAutoRenewVolumeClusterArgs struct { + ClusterId string `json:"clusterId"` +} diff --git a/bce-sdk-go/services/dbsc/util.go b/bce-sdk-go/services/dbsc/util.go new file mode 100644 index 0000000..a03c0e9 --- /dev/null +++ b/bce-sdk-go/services/dbsc/util.go @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of BBC service +package dbsc + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX_V2 = bce.URI_PREFIX + "v2" + REQUEST_VOLUME_URI = "/volume" + + REQUEST_CREATE_URI = "/cluster" + REQUEST_AUTO_RENEW_URI = "/cluster/autoRenew" + REQUEST_CANCEL_AUTO_RENEW_URI = "/cluster/cancelAutoRenew" +) + +func getVolumeClusterUri() string { + return URI_PREFIX_V2 + REQUEST_VOLUME_URI +} diff --git a/bce-sdk-go/services/dcc/client.go b/bce-sdk-go/services/dcc/client.go new file mode 100644 index 0000000..62dc5e0 --- /dev/null +++ b/bce-sdk-go/services/dcc/client.go @@ -0,0 +1,27 @@ +package dcc + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + // DefaultEndpoint -- xx + DefaultEndpoint = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" +) + +// Client used for client +type Client struct { + *bce.BceClient +} + +// NewClient return a client +func NewClient(ak, sk, endPoint string) (ret *Client, err error) { + if len(endPoint) == 0 { + endPoint = DefaultEndpoint + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} diff --git a/bce-sdk-go/services/dcc/dedicatedHost.go b/bce-sdk-go/services/dcc/dedicatedHost.go new file mode 100644 index 0000000..58b98f2 --- /dev/null +++ b/bce-sdk-go/services/dcc/dedicatedHost.go @@ -0,0 +1,134 @@ +package dcc + +import ( + "fmt" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListDedicatedHosts -- xx +func (c *Client) ListDedicatedHosts(args *ListDedicatedHostArgs) (list *ListDedicatedHostResult, err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithBody(args). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost"). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", fmt.Sprintf("%d", args.MaxKeys)). + WithQueryParamFilter("zoneName", args.ZoneName). + WithResult(&list). + Do() + return +} + +// GetDedicatedHostDetail -- xx +func (c *Client) GetDedicatedHostDetail(hostID string) (ret *GetDedicatedHostDetailResult, err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(bce.URI_PREFIX + "v1/dedicatedHost/" + hostID). + WithBody(&ret). + WithResult(&ret). + Do() + return + +} + +// PurchaseReserved -- xx +func (c *Client) PurchaseReserved(hostID string, args *PurchaseReservedArgs) (err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost/"+hostID). + WithQueryParamFilter("purchaseReserved", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(&args). + Do() + return +} + +// Create -- xx +func (c *Client) Create(args *CreateArgs) (ret *CreateResult, err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(&args). + WithResult(&ret). + Do() + return + +} +func (c *Client) tag(action, uri string, args interface{}) (err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(uri). + WithQueryParamFilter(action, ""). + WithBody(&args). + Do() + return + +} + +// BindTag -- xx +func (c *Client) BindTag(dccID string, args *BindTagArgs) (err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost/"+dccID+"/tag"). + WithQueryParamFilter("bind", ""). + WithBody(&args). + Do() + return + +} + +// UnbindTag -- xx +func (c *Client) UnbindTag(dccID string, args *BindTagArgs) (err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost/"+dccID+"/tag"). + WithQueryParamFilter("unbind", ""). + WithBody(&args). + Do() + return +} + +// CreateInstance -- xx +func (c *Client) CreateInstance(args *CreateInstanceArgs) (ret *CreateInstanceResult, err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost/instance"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(&args). + WithResult(&ret). + Do() + return +} + +// ModityInstance -- xx +func (c *Client) ModityInstance(instanceID string, args *ModityInstanceArgs) (err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost/instance/"+instanceID). + WithQueryParamFilter("modifyAttribute", ""). + WithBody(&args). + Do() + return +} +func (c *Client) tagforInstance(action, instanceID string, args *BindTagArgs) (err error) { + err = bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(bce.URI_PREFIX+"v1/dedicatedHost/instance/"+instanceID+"/tag"). + WithQueryParamFilter(action, ""). + WithBody(&args). + Do() + return +} + +// BindTagforInstance -- xx +func (c *Client) BindTagforInstance(instanceID string, args *BindTagArgs) error { + return c.tagforInstance("bind", instanceID, args) +} + +// UnbindTagforInstance -- xx +func (c *Client) UnbindTagforInstance(instanceID string, args *BindTagArgs) error { + return c.tagforInstance("unbind", instanceID, args) +} diff --git a/bce-sdk-go/services/dcc/model.go b/bce-sdk-go/services/dcc/model.go new file mode 100644 index 0000000..7eea78f --- /dev/null +++ b/bce-sdk-go/services/dcc/model.go @@ -0,0 +1,162 @@ +package dcc + +import bcc "github.com/baidubce/bce-sdk-go/services/bcc/api" + +// ListDedicatedHostArgs struct +type ListDedicatedHostArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxkeys"` + ZoneName string `json:"zoneName"` +} + +// ListDedicatedHostResult struct +type ListDedicatedHostResult struct { + Marker string + IsTruncated bool + NextMarker string + MaxKeys int + DedicatedHosts []*DedicatedHostModel +} + +// DedicatedHostModel -- xx +type DedicatedHostModel struct { + ID string // 专属服务器ID,符合BCE规范,是一个定长字符串,且只允许包含大小写字母、数字、连字号(-)和下划线(_)。 + Name string // 专属服务器名称 + Status DedicatedHostStatus // 专属服务器状态 + FlavorName string // 套餐名称 + ResourceUsage ResourceUsage // 套餐明细 + PaymentTiming string // 付费方式,包括Postpaid(后付费),Prepaid(预付费)两种。 + CreateTime string // 创建时间 + ExpireTime string // 过期时间,只有Prepaid计费资源存在 + Desc string // 描述信息 + ZoneName string // 可用区名称 + Tags []TagModel // 实例当前配置的标签 +} + +// DedicatedHostStatus string +type DedicatedHostStatus string + +const ( + //DedicatedHostStatusStarting DedicatedHostStatus = "Starting" + DedicatedHostStatusStarting DedicatedHostStatus = "Starting" + //DedicatedHostStatusRunning DedicatedHostStatus = "Running" + DedicatedHostStatusRunning DedicatedHostStatus = "Running" + //DedicatedHostStatusExpired DedicatedHostStatus = "Expired" + DedicatedHostStatusExpired DedicatedHostStatus = "Expired" + //DedicatedHostStatusError DedicatedHostStatus = "Error" + DedicatedHostStatusError DedicatedHostStatus = "Error" +) + +// ResourceUsage struct { +type ResourceUsage struct { + CPUCount int `json:"cpuCount"` + FreeCPUCount int `json:"FreeCpuCount"` + MemoryCapacityInGB int + FreeMemoryCapacityInGB int + EphemeralDisks []EphemeralDisk +} + +// EphemeralDisk struct { for go-lint +type EphemeralDisk struct { + StorageType StorageType `json:"storageType,omitempty"` + SizeInGB int `json:"sizeInGB,omitempty"` + FreeSizeInGB int `json:"freesizeInGB,omitempty"` +} + +// StorageType string for go-lint +type StorageType string + +const ( + //StorageTypeSata StorageType = "sata" for go-lint + StorageTypeSata StorageType = "sata" + //StorageTypeSSD StorageType = "ssd" for go-lint + StorageTypeSSD StorageType = "ssd" +) + +// TagModel struct { for go-lint +type TagModel struct { + TagKey string + TagValue string +} + +// GetDedicatedHostDetailResult struct { +type GetDedicatedHostDetailResult struct { + DedicatedHost DedicatedHostModel +} + +// PurchaseReservedArgs struct { +type PurchaseReservedArgs struct { + ClientToken string // 是 Query参数 幂等性Token,是一个长度不超过64位的ASCII字符串)。 + Billing Billing // 是 RequestBody参数 订单信息 +} + +// Billing struct { +type Billing struct { + PaymentTiming string `json:"paymentTiming"` // 付款时间,预支付(Prepaid)和后支付(Postpaid) + Reservation Reservation `json:"reservation"` // 保留信息,支付方式为后支付时不需要设置,预支付时必须设置 +} + +// Reservation struct { +type Reservation struct { + Length int `json:"reservationLength"` // 时长,[1,2,3,4,5,6,7,8,9,12,24,36] + TimeUnit string `json:"reservationTimeUnit,omitempty"` // 时间单位,month,当前仅支持按月 +} + +// CreateArgs -- xx +type CreateArgs struct { + Version string // 是 URL参数 API版本号 + ClientToken string // 是 Query参数 幂等性Token,是一个长度不超过64位的ASCII字符串)。 + VCPU int `json:"vcpu"` // 否 RequestBody参数 待创建专属服务器虚拟CPU核数,数量不能超过物理CPU核数的两倍 + FlavorName string // 是 RequestBody参数 套餐类型,可选计算型(calculation)C01/C02,可选大数据机型(storage)S01/S02 + PurchaseCount int // 否 RequestBody参数 批量创建(购买)的虚专属服务器个数,必须为大于0的整数,可选参数,缺省为1 + Name string // 否 RequestBody参数 专属服务器名字(可选)。默认都不指定name。如果指定name:批量时name作为名字的前缀。后端将加上后缀,后缀生成方式:name{ -序号}。如果没有指定name,则自动生成,方式:{instance-八位随机串-序号}。注:随机串从0~9a~z生成;序号按照count的数量级,依次递增,如果count为100,则序号从000~100递增,如果为10,则从00~10递增 + Billing Billing // 是 RequestBody参数 订单、计费相关参数 + ZoneName string // 否 RequestBody参数 指定zone信息,默认为空,由系统自动选择 +} + +// CreateResult struct { +type CreateResult struct { + DedicatedHostIds []string +} + +// BindTagArgs struct { +type BindTagArgs struct { + ChangeTags []TagModel // 是 Request Body参数 标签数组,每个标签由tagKey和tagValue组成 +} + +// ModityInstanceArgs struct { +type ModityInstanceArgs struct { + Name string // 是 Request Body参数 实例名称 +} + +// CreateInstanceArgs struct { +type CreateInstanceArgs struct { + ClientToken string `json:"clientToken"` + ImageID string `json:"imageId"` + Billing Billing `json:"billing"` + CPUCount int `json:"cpuCount"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` + InstanceType string `json:"instanceType,omitempty"` + RootDiskSizeInGb int `json:"rootDiskSizeInGb,omitempty"` + RootDiskStorageType string `json:"rootDiskStorageType,omitempty"` + LocalDiskSizeInGB int `json:"localDiskSizeInGB,omitempty"` + EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + CreateCdsList []bcc.CreateCdsModel `json:"createCdsList,omitempty"` + NetworkCapacityInMbps int `json:"networkCapacityInMbps"` + InternetChargeType string `json:"internetChargeType,omitempty"` + DedicatedHostID string `json:"dedicatedHostId,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + Name string `json:"name,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + SubnetID string `json:"subnetId,omitempty"` + SecurityGroupID string `json:"securityGroupId,omitempty"` + GpuCard string `json:"gpuCard,omitempty"` + FpgaCard string `json:"fpgaCard,omitempty"` + CardCount string `json:"cardCount,omitempty"` +} + +// CreateInstanceResult struct +type CreateInstanceResult struct { + InstanceIds []string // 虚机实例ID的集合,其中ID符合BCE规范,必须是一个定长字符串,且只允许包含大小写字母、数字、连字号(-)和下划线(_)。 +} diff --git a/bce-sdk-go/services/ddc/client.go b/bce-sdk-go/services/ddc/client.go new file mode 100644 index 0000000..6774962 --- /dev/null +++ b/bce-sdk-go/services/ddc/client.go @@ -0,0 +1,207 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for DDC service + +// Package ddc defines the DDC services of BCE. The supported APIs are all defined in sub-package +package ddc + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1/ddc" + DEFAULT_ENDPOINT = "ddc.su.baidubce.com" + REQUEST_DDC_INSTANCE_URL = "/instance" + REQUEST_DDC_POOL_URL = "/pool" + REQUEST_DDC_HOST_URL = "/host" + REQUEST_DDC_DEPLOY_URL = "/deploy" + REQUEST_DDC_DATABASE_URL = "/database" + REQUEST_DDC_TABLE_URL = "/table" + REQUEST_DDC_HARDLINK_URL = "/link" + REQUEST_DDC_ACCOUNT_URL = "/account" + REQUEST_DDC_ROGROUP_URL = "/roGroup" + REQUEST_DDC_RECYCLER_URL = "/recycler" + REQUEST_DDC_SECURITYGROUP_URL = "/security" + REQUEST_DDC_LOG_URL = "/logs" + REQUEST_DDC_UPDATE_ACTION = "/update" + REQUEST_DDC_MAINTAINTIME_URL = "/maintenTimeInfo" + REQUEST_UPDATE_MAINTAINTIME_URL = "/updateMaintenTime" +) + +// Client of DDC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getDdcUri() string { + return URI_PREFIX +} + +func getDdcInstanceUri() string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL +} + +// Pool URL +func getPoolUri() string { + return URI_PREFIX + REQUEST_DDC_POOL_URL +} + +func getPoolUriWithId(poolId string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId +} + +// Host URL +func getHostUri() string { + return URI_PREFIX + REQUEST_DDC_HOST_URL +} + +func getHostUriWithPnetIp(poolId, hostPnetIP string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId + REQUEST_DDC_HOST_URL + "/" + hostPnetIP +} + +// DeploySet URL +func getDeploySetUri(poolId string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId + REQUEST_DDC_DEPLOY_URL +} + +func getDeploySetUriWithId(poolId, id string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId + REQUEST_DDC_DEPLOY_URL + "/" + id +} + +func getDdcUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId +} + +// Database URL +func getDatabaseUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL +} + +func getDatabaseUriWithDbName(instanceId string, dbName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL + "/" + dbName +} + +// Account URL +func getAccountUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_ACCOUNT_URL +} + +func getAccountUriWithAccountName(instanceId string, accountName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_ACCOUNT_URL + "/" + accountName +} + +// RoGroup URL +func getRoGroupUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_ROGROUP_URL +} + +// MaintainTime URL +func getMaintainTimeUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_MAINTAINTIME_URL +} + +// MaintainTime URL +func getUpdateMaintainTimeUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_UPDATE_MAINTAINTIME_URL +} + +// RoGroup URL +func getUpdateRoGroupUriWithId(roGroupId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + REQUEST_DDC_ROGROUP_URL + "/" + roGroupId + REQUEST_DDC_UPDATE_ACTION +} + +// RoGroupWeight URL +func getUpdateRoGroupWeightUriWithId(roGroupId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + REQUEST_DDC_ROGROUP_URL + "/" + roGroupId + "/updateWeight" +} + +// ReBalance RoGroup URL +func getReBalanceRoGroupUriWithId(roGroupId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + REQUEST_DDC_ROGROUP_URL + "/" + roGroupId + "/balanceRoLoad" +} + +// Recycler URL +func getRecyclerUrl() string { + return URI_PREFIX + REQUEST_DDC_RECYCLER_URL +} + +// Recycler Recover URL +func getRecyclerRecoverUrl() string { + return URI_PREFIX + REQUEST_DDC_RECYCLER_URL + "/batchRecover" +} + +// Recycler Recover URL +func getRecyclerDeleteUrl() string { + return URI_PREFIX + REQUEST_DDC_RECYCLER_URL + "/batchDelete" +} + +// List Security Group By Vpc URL +func getSecurityGroupWithVpcIdUrl(vpcId string) string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/" + vpcId + "/listByVpc" +} + +// List Security Group By Instance URL +func getSecurityGroupWithInstanceIdUrl(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/" + instanceId + "/list" +} + +// Bind Security Group To Instance URL +func getBindSecurityGroupWithUrl() string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/bind" +} + +// UnBind Security Group To Instance URL +func getUnBindSecurityGroupWithUrl() string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/unbind" +} + +// Batch Replace Security Group URL +func getReplaceSecurityGroupWithUrl() string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/updateSecurityGroup" +} + +func getLogsUrlWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_LOG_URL +} + +func getLogsUrlWithLogId(instanceId, logId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_LOG_URL + "/" + logId +} + +func getCreateTableHardLinkUrl(instanceId, dbName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + + REQUEST_DDC_DATABASE_URL + "/" + dbName + + REQUEST_DDC_TABLE_URL + REQUEST_DDC_HARDLINK_URL +} + +func getTableHardLinkUrl(instanceId, dbName, tableName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + + REQUEST_DDC_DATABASE_URL + "/" + dbName + + REQUEST_DDC_TABLE_URL + "/" + tableName + REQUEST_DDC_HARDLINK_URL +} + +func getChangeSemiSyncStatusUrlWithId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/semisync" +} diff --git a/bce-sdk-go/services/ddc/client_test.go b/bce-sdk-go/services/ddc/client_test.go new file mode 100644 index 0000000..143272a --- /dev/null +++ b/bce-sdk-go/services/ddc/client_test.go @@ -0,0 +1,530 @@ +package ddc + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + DDC_CLIENT *Client + DDC_ID string = "ddc-m8rs4yjz" + ACCOUNT_NAME string = "go_sdk_account_2" + ACCOUNT_PASSWORD string = "go_sdk_password_1" + ACCOUNT_REMARK string = "go-sdk-remark-1" + DB_NAME string = "go_sdk_db_1" + DB_CHARACTER_SET_NAME string = "utf8" + DB_REMARK string = "go_sdk_db_remark" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +const ( + SDK_NAME_PREFIX = "sdk_rds_" + POOL = "xdb_gaiabase_pool" + PNETIP = "100.88.65.121" + DEPLOY_ID = "ab89d829-9068-d88e-75bc-64bb6367d036" + INSTANCE_ID = "rdsmcb38t7b8atx" +) + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 1; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + DDC_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateInstance(t *testing.T) { + args := &CreateRdsArgs{ + PurchaseCount: 1, + InstanceName: "mysql_5.7", + //SourceInstanceId: "ddc-mmqptugx", + Engine: "mysql", + EngineVersion: "5.7", + CpuCount: 1, + MemoryCapacity: 1, + VolumeCapacity: 5, + Billing: Billing{ + PaymentTiming: "Postpaid", + Reservation: Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + VpcId: "vpc-80m2ksi6sv0f", + ZoneNames: []string{ + "cn-su-c", + }, + Subnets: []SubnetMap{ + { + ZoneName: "cn-su-c", + SubnetId: "sbn-8v3p33vhyhq5", + }, + }, + DeployId: "", + PoolId: "xdb_gaiabase_pool", + } + rds, err := DDC_CLIENT.CreateRds(args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(rds) +} + +func TestClient_ListDeploySets(t *testing.T) { + deploys, err := DDC_CLIENT.ListDeploySets(POOL, &Marker{MaxKeys: 1}) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, deploys.MaxKeys, 1) + fmt.Println(deploys.Result[0].DeployName) +} + +func TestClient_GetDeploySet(t *testing.T) { + deploy, err := DDC_CLIENT.GetDeploySet(POOL, DEPLOY_ID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, DEPLOY_ID, deploy.DeployID) +} + +func TestClient_DeleteDeploySet(t *testing.T) { + err := DDC_CLIENT.DeleteDeploySet(POOL, "b444142c-69ed-87a6-396b-fc4a76a9754f") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateDeploySet(t *testing.T) { + err := DDC_CLIENT.CreateDeploySet(POOL, &CreateDeployRequest{ + DeployName: "api-from-go", + Strategy: "distributed", + }) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListParameters(t *testing.T) { + parameters, err := DDC_CLIENT.ListParameters("rdsmcb38t7b8atx") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, parameters.Items, parameters.Items) + fmt.Println(parameters.Items) +} + +func TestClient_UpdateParameter(t *testing.T) { + DDC_CLIENT.UpdateParameter(INSTANCE_ID, &UpdateParameterArgs{Parameters: []KVParameter{ + { + Name: "auto_increment_increment", + Value: "2", + }, + }}) +} + +func TestClient_GetSecurityIps(t *testing.T) { + ips, err := DDC_CLIENT.GetSecurityIps(INSTANCE_ID) + ExpectEqual(t.Errorf, ips, ips) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(ips.SecurityIps) +} +func TestClient_ListRoGroup(t *testing.T) { + ips, err := DDC_CLIENT.ListRoGroup("rdsm2bpbozmj59z") + ExpectEqual(t.Errorf, ips, ips) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(ips) +} + +func TestClient_ListVpc(t *testing.T) { + vpc, err := DDC_CLIENT.ListVpc() + ExpectEqual(t.Errorf, vpc, vpc) + ExpectEqual(t.Errorf, err, nil) + fmt.Println(vpc) +} + +func TestClient_GetDetail(t *testing.T) { + detail, err := DDC_CLIENT.GetDetail("ddc-mmqptugx") + ExpectEqual(t.Errorf, detail, detail) + ExpectEqual(t.Errorf, err, nil) + res, _ := json.Marshal(detail) + fmt.Println(string(res)) +} + +func TestClient_UpdateSecurityIps(t *testing.T) { + DDC_CLIENT.UpdateSecurityIps(INSTANCE_ID, &UpdateSecurityIpsArgs{ + SecurityIps: []string{ + "10.10.0.0/16", + }, + }) +} + +func TestClient_GetBackupList(t *testing.T) { + list, err := DDC_CLIENT.GetBackupList(INSTANCE_ID) + ExpectEqual(t.Errorf, list.Snapshots, list.Snapshots) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(list.Snapshots) +} + +func TestClient_GetBackupDetail(t *testing.T) { + list, err := DDC_CLIENT.GetBackupDetail(INSTANCE_ID, "1611156600150859846") + ExpectEqual(t.Errorf, list.Snapshot, list.Snapshot) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(list.Snapshot) +} + +func TestClient_CreateBackup(t *testing.T) { + DDC_CLIENT.CreateBackup(INSTANCE_ID) +} + +func TestClient_ModifyBackupPolicy(t *testing.T) { + DDC_CLIENT.ModifyBackupPolicy(INSTANCE_ID, &BackupPolicy{ + BackupDays: "0,1,2,3,5", + ExpireInDays: 100, + BackupTime: "17:00:00Z", + }) +} + +func TestClient_GetZoneList(t *testing.T) { + list, err := DDC_CLIENT.GetZoneList() + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, list, list) + fmt.Println(list) +} + +func TestClient_ListSubnets(t *testing.T) { + args := &ListSubnetsArgs{ZoneName: "zoneA"} + subnets, err := DDC_CLIENT.ListSubnets(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, subnets, subnets) + result, _ := json.Marshal(subnets.Subnets) + fmt.Println(string(result)) +} + +func TestClient_GetBinlogList(t *testing.T) { + list, err := DDC_CLIENT.GetBinlogList(INSTANCE_ID, "") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, list, list) + fmt.Println(list.Binlogs) +} + +func TestClient_GetBinlogDetail(t *testing.T) { + detail, err := DDC_CLIENT.GetBinlogDetail(INSTANCE_ID, "1611072328934047748") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, detail.Binlog.BinlogId, "1611072328934047748") + fmt.Println(detail) +} + +func TestClient_DeleteDdcInstance(t *testing.T) { + instanceId := "ddc-m8rs4yjz" + DDC_CLIENT.DeleteRds(instanceId) +} + +func TestClient_SwitchInstance(t *testing.T) { + args := &SwitchArgs{IsSwitchNow: false} + DDC_CLIENT.SwitchInstance("rdsma7fcyu2anvi", args) +} + +// Database +func TestClient_CreateDatabase(t *testing.T) { + args := &CreateDatabaseArgs{ + ClientToken: getClientToken(), + DbName: DB_NAME, + CharacterSetName: DB_CHARACTER_SET_NAME, + Remark: DB_REMARK, + } + + err := DDC_CLIENT.CreateDatabase(DDC_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetDatabase(t *testing.T) { + result, err := DDC_CLIENT.GetDatabase(DDC_ID, DB_NAME) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "available", result.DbStatus) +} + +func TestClient_ListDatabase(t *testing.T) { + result, err := DDC_CLIENT.ListDatabase(DDC_ID) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Databases { + if e.DbName == DB_NAME { + ExpectEqual(t.Errorf, "available", e.DbStatus) + } + } +} + +func TestClient_UpdateDatabaseRemark(t *testing.T) { + args := &UpdateDatabaseRemarkArgs{ + Remark: DB_REMARK + "_update", + } + err := DDC_CLIENT.UpdateDatabaseRemark(DDC_ID, DB_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteDatabase(t *testing.T) { + err := DDC_CLIENT.DeleteDatabase(DDC_ID, DB_NAME) + ExpectEqual(t.Errorf, nil, err) +} + +// Account +func TestClient_CreateAccount(t *testing.T) { + args := &CreateAccountArgs{ + ClientToken: getClientToken(), + AccountName: ACCOUNT_NAME, + Password: ACCOUNT_PASSWORD, + AccountType: "Common", + Desc: ACCOUNT_REMARK, + DatabasePrivileges: []DatabasePrivilege{ + { + DbName: "hello", + AuthType: "ReadOnly", + }, + }, + } + + err := DDC_CLIENT.CreateAccount(DDC_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetAccount(t *testing.T) { + result, err := DDC_CLIENT.GetAccount(DDC_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Available", result.Status) +} + +func TestClient_ListAccount(t *testing.T) { + result, err := DDC_CLIENT.ListAccount(DDC_ID) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Accounts { + if e.AccountName == ACCOUNT_NAME { + ExpectEqual(t.Errorf, "Available", e.Status) + } + } +} + +func TestClient_UpdateAccountPassword(t *testing.T) { + args := &UpdateAccountPasswordArgs{ + Password: ACCOUNT_PASSWORD + "_update", + } + err := DDC_CLIENT.UpdateAccountPassword(DDC_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountDesc(t *testing.T) { + args := &UpdateAccountDescArgs{ + Desc: ACCOUNT_REMARK + "_update", + } + err := DDC_CLIENT.UpdateAccountDesc(DDC_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountPrivileges(t *testing.T) { + databasePrivileges := []DatabasePrivilege{ + { + DbName: "hello", + AuthType: "ReadWrite", + }, + } + args := &UpdateAccountPrivilegesArgs{ + DatabasePrivileges: databasePrivileges, + } + err := DDC_CLIENT.UpdateAccountPrivileges(DDC_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAccount(t *testing.T) { + err := DDC_CLIENT.DeleteAccount(DDC_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) +} + +// util +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateRds(t *testing.T) { + args := &CreateRdsArgs{ + PurchaseCount: 1, + InstanceName: "mysql_5.7", + //SourceInstanceId: "ddc-mmqptugx", + Engine: "mysql", + EngineVersion: "5.7", + CpuCount: 1, + MemoryCapacity: 1, + VolumeCapacity: 5, + Billing: Billing{ + PaymentTiming: "Postpaid", + Reservation: Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + VpcId: "vpc-80m2ksi6sv0f", + ZoneNames: []string{ + "cn-su-c", + }, + Subnets: []SubnetMap{ + { + ZoneName: "cn-su-c", + SubnetId: "sbn-8v3p33vhyhq5", + }, + }, + DeployId: "", + PoolId: "xdb_gaiabase_pool", + } + rds, err := DDC_CLIENT.CreateRds(args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(rds) +} + +func TestClient_ListDdcInstance(t *testing.T) { + args := &ListRdsArgs{ + // 批量获取列表的查询的起始位置,实例列表中Marker需要指定实例Id,可选 + // Marker: "marker", + // 指定每页包含的最大数量(主实例),最大数量不超过1000,缺省值为1000,可选 + MaxKeys: 100, + } + resp, err := DDC_CLIENT.ListRds(args) + + if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return + } + + // 返回标记查询的起始位置 + fmt.Println("ddc list marker: ", resp.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("ddc list isTruncated: ", resp.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("ddc list nextMarker: ", resp.NextMarker) + // 每页包含的最大数量 + fmt.Println("ddc list maxKeys: ", resp.MaxKeys) + + // 获取instance的列表信息 + for _, e := range resp.Instances { + fmt.Println("ddc instanceId: ", e.InstanceId) + fmt.Println("ddc instanceName: ", e.InstanceName) + fmt.Println("ddc engine: ", e.Engine) + fmt.Println("ddc engineVersion: ", e.EngineVersion) + fmt.Println("ddc instanceStatus: ", e.InstanceStatus) + fmt.Println("ddc cpuCount: ", e.CpuCount) + fmt.Println("ddc memoryCapacity: ", e.MemoryCapacity) + fmt.Println("ddc volumeCapacity: ", e.VolumeCapacity) + fmt.Println("ddc usedStorage: ", e.UsedStorage) + fmt.Println("ddc paymentTiming: ", e.PaymentTiming) + fmt.Println("ddc instanceType: ", e.InstanceType) + fmt.Println("ddc instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("ddc instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("ddc publicAccessStatus: ", e.PublicAccessStatus) + fmt.Println("ddc vpcId: ", e.VpcId) + } + +} +func TestClient_GetDetail2(t *testing.T) { + result, err := DDC_CLIENT.GetDetail("ddc-mrjnghx8") + if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return + } + // 获取实例详情信息 + fmt.Println("ddc instanceId: ", result.InstanceId) + fmt.Println("ddc instanceName: ", result.InstanceName) + fmt.Println("ddc engine: ", result.Engine) + fmt.Println("ddc engineVersion: ", result.EngineVersion) + fmt.Println("ddc instanceStatus: ", result.InstanceStatus) + fmt.Println("ddc cpuCount: ", result.CpuCount) + fmt.Println("ddc memoryCapacity: ", result.MemoryCapacity) + fmt.Println("ddc volumeCapacity: ", result.VolumeCapacity) + fmt.Println("ddc usedStorage: ", result.UsedStorage) + fmt.Println("ddc paymentTiming: ", result.PaymentTiming) + fmt.Println("ddc instanceType: ", result.InstanceType) + fmt.Println("ddc instanceCreateTime: ", result.InstanceCreateTime) + fmt.Println("ddc instanceExpireTime: ", result.InstanceExpireTime) + fmt.Println("ddc publicAccessStatus: ", result.PublicAccessStatus) + fmt.Println("ddc vpcId: ", result.VpcId) + fmt.Println("ddc Subnets: ", result.Subnets) + fmt.Println("ddc BackupPolicy: ", result.BackupPolicy) + fmt.Println("ddc RoGroupList: ", result.RoGroupList) + fmt.Println("ddc NodeMaster: ", result.NodeMaster) + fmt.Println("ddc NodeSlave: ", result.NodeSlave) + fmt.Println("ddc NodeReadReplica: ", result.NodeReadReplica) + fmt.Println("ddc DeployId: ", result.DeployId) +} + +func TestClient_UpdateInstanceName(t *testing.T) { + args := &UpdateInstanceNameArgs{ + // DDC实例名称,允许小写字母、数字,中文,长度限制为1~64 + InstanceName: "ssss", + } + err := DDC_CLIENT.UpdateInstanceName("ddc-m67du0mh", args) + if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return + } + fmt.Printf("update instance name success\n") +} + +func TestClient_BinlogAccessDetail(t *testing.T) { + args := &AccessDetailArgs{ + StartDateTime: "2023-02-02T01:00:00Z", + EndDateTime: "2023-02-02T10:00:00Z", + Marker: "0", + MaxKeys: 100, + } + result, err := DDC_CLIENT.BinlogAccessDetail(args) + if err != nil { + fmt.Printf("get binlog access detail error: %+v\n", err) + return + } + fmt.Printf("get binlog access detail success\n") + fmt.Println("result: ", result) +} + +func TestClient_SnapshotAccessDetail(t *testing.T) { + args := &AccessDetailArgs{ + StartDateTime: "2023-02-02T01:00:00Z", + EndDateTime: "2023-02-02T10:00:00Z", + Marker: "0", + MaxKeys: 100, + } + result, err := DDC_CLIENT.SnapshotAccessDetail(args) + if err != nil { + fmt.Printf("get snapshot access detail error: %+v\n", err) + return + } + fmt.Printf("get snapshot access detail success\n %+v", result) +} diff --git a/bce-sdk-go/services/ddc/ddc.go b/bce-sdk-go/services/ddc/ddc.go new file mode 100644 index 0000000..1191f15 --- /dev/null +++ b/bce-sdk-go/services/ddc/ddc.go @@ -0,0 +1,1868 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// ddc.go - the ddc APIs definition supported by the DDC service +package ddc + +import ( + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + KEY_CLIENT_TOKEN = "clientToken" + KEY_MARKER = "marker" + KEY_MAX_KEYS = "maxKeys" + COMMA = "," +) + +// Convert marker to request params +func getMarkerParams(marker *Marker) map[string]string { + if marker == nil { + marker = &Marker{Marker: "-1"} + } + params := make(map[string]string, 2) + params[KEY_MARKER] = marker.Marker + if marker.MaxKeys > 0 { + params[KEY_MAX_KEYS] = strconv.Itoa(marker.MaxKeys) + } + return params +} + +// CreateInstance - create a Instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create a instance +// +// RETURNS: +// - *InstanceIds: the result of create RDS, contains new RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstance(args *CreateInstanceArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + result := &CreateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDdcInstanceUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateRds - create a DDC with the specific parameters +// +// PARAMS: +// - args: the arguments to create a ddc +// +// RETURNS: +// - *InstanceIds: the result of create DDC, contains new DDC's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateRds(args *CreateRdsArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.Engine == "" { + return nil, fmt.Errorf("unset Engine") + } + + if args.EngineVersion == "" { + return nil, fmt.Errorf("unset EngineVersion") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + + newArgs := &CreateInstanceArgs{ + InstanceType: "RDS", + Number: args.PurchaseCount, + ClientToken: args.ClientToken, + Instance: CreateInstance{ + InstanceName: args.InstanceName, + Engine: args.Engine, + EngineVersion: args.EngineVersion, + CpuCount: args.CpuCount, + AllocatedMemoryInGB: args.MemoryCapacity, + AllocatedStorageInGB: args.VolumeCapacity, + DiskIoType: "ssd", + DeployId: args.DeployId, + PoolId: args.PoolId, + IsDirectPay: args.IsDirectPay, + Billing: args.Billing, + AutoRenewTime: args.AutoRenewTime, + AutoRenewTimeUnit: args.AutoRenewTimeUnit, + Tags: args.Tags, + Category: args.Category, + SyncMode: args.SyncMode, + }, + } + + info, err := c.SupplyVpcInfo(newArgs, args) + if err != nil { + return nil, err + } + result, err2 := c.CreateInstance(info) + if err2 != nil { + return nil, err2 + } + //list, err4 := c.GetZoneList() + //if err4 != nil { + // fmt.Printf("get zone list error: %+v\n", err4) + // return nil, err4 + //} + //if args.ZoneNames != nil { + // newZoneName := "" + // for _, e1 := range list.Zones { + // if strings.Join(args.ZoneNames, ",") == strings.Join(e1.ZoneNames, ",") { + // newZoneName = strings.Join(e1.ZoneNames, ",") + // } + // } + // newArgs.Instance.AZone = newZoneName + //} + return result, nil +} + +func (c *Client) SupplyVpcInfo(newArgs *CreateInstanceArgs, args *CreateRdsArgs) (*CreateInstanceArgs, error) { + + info := newArgs + vpc, err := c.ListVpc() + if err != nil { + fmt.Printf("list vpc error: %+v\n", err) + return nil, err + } + defaultVpcId := "" + if args.VpcId == "" { + for _, e := range *vpc { + defaultVpcId = e.VpcId + info.Instance.VpcId = e.VpcId + args.VpcId = e.VpcId + } + } + if args.VpcId == defaultVpcId { + for _, e := range *vpc { + if e.VpcId == args.VpcId { + info.Instance.VpcId = e.VpcId + args.VpcId = e.VpcId + } + } + info, err = c.UnDefaultVpcInfo(info, args) + if err != nil { + fmt.Printf("set vpc error: %+v\n", err) + return nil, err + } + } else { + for _, e := range *vpc { + if args.VpcId == e.ShortId { + info.Instance.VpcId = e.VpcId + args.VpcId = e.VpcId + } + } + info, err = c.UnDefaultVpcInfo(info, args) + if err != nil { + fmt.Printf("supply zoneAndSubnet info error: %+v\n", err) + return nil, err + } + } + return info, nil +} + +func (c *Client) SupplyZoneAndSubnetInfo(newArgs *CreateInstanceArgs, args *CreateRdsArgs) (*CreateInstanceArgs, error) { + newZoneName := "" + if args.Subnets != nil { + for _, e := range args.Subnets { + newZoneName += e.ZoneName + "," + } + if newZoneName != "" && newZoneName[0:len(newZoneName)-1] != strings.Join(args.ZoneNames, ",") { + fmt.Printf("subnets and zoneNames not matcher: %+v\n", nil) + return nil, errors.New("subnets and zoneNames not matcher") + } else { + subnets, err1 := c.ListSubnets(nil) + if err1 != nil { + fmt.Printf("list subnets error: %+v\n", err1) + return nil, err1 + } + subnetId := "" + if args.Subnets != nil { + for _, e := range subnets.Subnets { + for _, e1 := range args.Subnets { + if e.ShortId == e1.SubnetId { + subnetId += e.Az + ":" + e.SubnetId + "," + } + } + } + if subnetId == "" { + return nil, errors.New("subnetId no match") + } + newArgs.Instance.SubnetId = subnetId[0 : len(subnetId)-1] + } + } + } else { + var subnetStr string + for _, e := range args.ZoneNames { + if !strings.Contains(e, ",") { + listSubnetsArgs := &ListSubnetsArgs{ + VpcId: args.VpcId, + ZoneName: e, + } + subnets, err := c.ListSubnets(listSubnetsArgs) + if err != nil { + fmt.Printf("list subnets error: %+v\n", err) + return nil, err + } + if subnets != nil && len(subnets.Subnets) > 0 { + subnetId := subnets.Subnets[0].SubnetId + subnetStr += e + ":" + subnetId + "," + } + } + } + if len(subnetStr) < 1 { + return nil, errors.New("Have no available subnet") + } + newArgs.Instance.SubnetId = subnetStr[:len(subnetStr)-1] + } + return newArgs, nil +} + +func (c *Client) UnDefaultVpcInfo(newArgs *CreateInstanceArgs, args *CreateRdsArgs) (*CreateInstanceArgs, error) { + info := newArgs + list, err2 := c.GetZoneList() + if err2 != nil { + fmt.Printf("get zone list error: %+v\n", err2) + return nil, err2 + } + newZoneName := "" + if args.ZoneNames == nil { + if args.Subnets == nil { + subnets, _ := c.ListSubnets(nil) + if subnets == nil || len(subnets.Subnets) == 0 { + return nil, errors.New("Have no available subnet or zone") + } + + for _, e := range subnets.Subnets { + info.Instance.AZone = e.Az + args.ZoneNames = append(args.ZoneNames, e.Az) + break + } + //for _, e := range list.Zones { + // info.Instance.AZone = e.ApiZoneNames[0] + // args.ZoneNames = append(args.ZoneNames, e.ApiZoneNames[0]) + // break + //} + } else { + for _, e := range args.Subnets { + newZoneName += e.ZoneName + "," + args.ZoneNames = append(args.ZoneNames, e.ZoneName) + } + for _, e := range list.Zones { + if newZoneName == strings.Join(e.ApiZoneNames, ",") { + info.Instance.AZone = strings.Join(e.ApiZoneNames, ",") + } + } + } + if args.ZoneNames == nil { + return nil, errors.New("Have no available zone for your operation.") + } + } else { + newZoneName = "" + for _, e1 := range list.Zones { + if strings.Join(args.ZoneNames, ",") == strings.Join(e1.ZoneNames, ",") { + newZoneName = strings.Join(e1.ApiZoneNames, ",") + } + } + info.Instance.AZone = newZoneName + } + + info, err2 = c.SupplyZoneAndSubnetInfo(info, args) + if err2 != nil { + return nil, err2 + } + return info, nil +} + +// CreateReadReplica - create a readReplica ddc with the specific parameters +// +// PARAMS: +// - args: the arguments to create a readReplica ddc +// +// RETURNS: +// - *InstanceIds: the result of create a readReplica ddc, contains the readReplica DDC's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateReadReplica(args *CreateReadReplicaArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.SourceInstanceId == "" { + return nil, fmt.Errorf("unset SourceInstanceId") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + detail, err2 := c.GetDdcDetail(args.SourceInstanceId) + if err2 != nil { + return nil, err2 + } + newArgs := &CreateInstanceArgs{ + InstanceType: "RDS", + Number: args.PurchaseCount, + ClientToken: args.ClientToken, + Instance: CreateInstance{ + InstanceName: args.InstanceName, + Engine: detail.Instance.Engine, + EngineVersion: detail.Instance.EngineVersion, + CpuCount: args.CpuCount, + AllocatedMemoryInGB: args.MemoryCapacity, + AllocatedStorageInGB: args.VolumeCapacity, + DiskIoType: "ssd", + DeployId: args.DeployId, + PoolId: args.PoolId, + RoGroupId: args.RoGroupId, + RoGroupWeight: args.RoGroupWeight, + EnableDelayOff: args.EnableDelayOff, + DelayThreshold: args.DelayThreshold, + LeastInstanceAmount: args.LeastInstanceAmount, + Billing: args.Billing, + IsDirectPay: args.IsDirectPay, + Tags: args.Tags, + }, + } + + createRdsArgs := &CreateRdsArgs{ + VpcId: args.VpcId, + Subnets: args.Subnets, + ZoneNames: args.ZoneNames, + } + + info, err := c.SupplyVpcInfo(newArgs, createRdsArgs) + if err != nil { + return nil, err + } + result, err2 := c.CreateInstance(info) + if err2 != nil { + return nil, err2 + } + + return result, err +} + +// UpdateRoGroup - update a roGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateRoGroup(roGroupId string, args *UpdateRoGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUpdateRoGroupUriWithId(roGroupId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// UpdateRoGroupReplicaWeight- update repica weight in roGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateRoGroupReplicaWeight(roGroupId string, args *UpdateRoGroupWeightArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUpdateRoGroupWeightUriWithId(roGroupId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ReBalanceRoGroup- Initiate a rebalance for foGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ReBalanceRoGroup(roGroupId string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getReBalanceRoGroupUriWithId(roGroupId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + return err +} + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) CreateDeploySet(poolId string, args *CreateDeployRequest) error { + if args == nil { + return fmt.Errorf("unset args") + } + if !(args.Strategy == "distributed" || args.Strategy == "centralized") { + return fmt.Errorf("Only support strategy distributed/centralized, current strategy: %v", args.Strategy) + } + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(cli). + WithMethod(http.POST). + WithURL(getDeploySetUri(poolId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return err +} + +// UpdateDeploySet - update a deploy set +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateDeploySet(poolId string, deployId string, args *UpdateDeployRequest) error { + if args == nil { + return fmt.Errorf("unset args") + } + if !(args.Strategy == "distributed" || args.Strategy == "centralized") { + return fmt.Errorf("Only support strategy distributed/centralized, current strategy: %v", args.Strategy) + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDeploySetUriWithId(poolId, deployId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListRds - list all instances +// RETURNS: +// - *ListRdsResult: the result of list instances with marker +// - error: nil if success otherwise the specific error +func (c *Client) ListRds(marker *ListRdsArgs) (*ListRdsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getDdcInstanceUri() + "/list") + req.SetMethod(http.GET) + if marker != nil { + req.SetParam(KEY_MARKER, marker.Marker) + req.SetParam(KEY_MAX_KEYS, strconv.Itoa(marker.MaxKeys)) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListRdsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// GetDdcDetail - get details of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// +// RETURNS: +// - *InstanceModelResult: the detail of the instance +// - error: nil if success otherwise the specific error +func (c *Client) GetDdcDetail(instanceId string) (*InstanceModelResult, error) { + result := &InstanceModelResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)). + WithResult(result). + Do() + + return result, err +} + +// GetDetail - get a specific ddc Instance's detail +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *Instance: the specific ddc Instance's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetDetail(instanceId string) (*Instance, error) { + detail, err := c.GetDdcDetail(instanceId) + instanceJson, _ := json.Marshal(detail.Instance) + args := &Instance{ + InstanceName: detail.Instance.InstanceName, + InstanceId: detail.Instance.InstanceId, + SourceInstanceId: detail.Instance.SourceInstanceId, + Endpoint: detail.Instance.Endpoint, + Engine: detail.Instance.Engine, + EngineVersion: detail.Instance.EngineVersion, + InstanceStatus: detail.Instance.InstanceStatus, + CpuCount: detail.Instance.CpuCount, + MemoryCapacity: detail.Instance.AllocatedMemoryInGB, + VolumeCapacity: detail.Instance.AllocatedStorageInGB, + UsedStorage: detail.Instance.UsedStorageInGB, + InstanceType: detail.Instance.Type, + InstanceCreateTime: detail.Instance.InstanceCreateTime, + InstanceExpireTime: detail.Instance.InstanceExpireTime, + PublicAccessStatus: detail.Instance.PublicAccessStatus, + PaymentTiming: detail.Instance.PaymentTiming, + SyncMode: detail.Instance.SyncMode, + Region: detail.Instance.Region, + VpcId: detail.Instance.VpcId, + BackupPolicy: detail.Instance.BackupPolicy, + RoGroupList: detail.Instance.RoGroupList, + NodeMaster: detail.Instance.NodeMaster, + NodeSlave: detail.Instance.NodeSlave, + NodeReadReplica: detail.Instance.NodeReadReplica, + Subnets: detail.Instance.Subnets, + DeployId: detail.Instance.DeployId, + ZoneNames: detail.Instance.ZoneNames, + } + err = json.Unmarshal(instanceJson, &args) + return args, err +} + +// DeleteRds - delete instances +// +// PARAMS: +// - instanceIds: id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRds(instanceIds string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getDdcInstanceUri()+"/delete"). + WithQueryParam("instanceIds", instanceIds). + Do() +} + +// RebootInstance - reboot a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebooted +// - args: reboot args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstance(instanceId string, args *RebootArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)). + WithQueryParam("reboot", ""). + WithBody(args). + Do() +} + +// UpdateInstanceName - update name of a specified instance +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to update instanceName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceName(instanceId string, args *UpdateInstanceNameArgs) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/updateName"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return err +} + +// GetBackupList - get backup list of the instance +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *GetBackupListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupList(instanceId string) (*GetBackupListResult, error) { + result := &GetBackupListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/snapshot"). + WithResult(result). + Do() + + return result, err +} + +// GetZoneList - list all zone +// +// PARAMS: +// - c: the client agent which can perform sending request +// +// RETURNS: +// - *GetZoneListResult: result of the zone list +// - error: nil if success otherwise the specific error +func (c *Client) GetZoneList() (*GetZoneListResult, error) { + result := &GetZoneListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(URI_PREFIX + "/zone"). + WithResult(result). + Do() + + return result, err +} + +// ListsSubnet - list all Subnets +// +// PARAMS: +// - c: the client agent which can perform sending request +// - args: the arguments to list all subnets, not necessary +// +// RETURNS: +// - *ListSubnetsResult: result of the subnet list +// - error: nil if success otherwise the specific error +func (c *Client) ListSubnets(args *ListSubnetsArgs) (*ListSubnetsResult, error) { + result := &ListSubnetsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(URI_PREFIX + "/subnet"). + WithResult(result). + Do() + if args == nil { + return result, err + } + if args.ZoneName == "" { + return result, err + } + // to compat rds api, filter by zone and vpcId + if result.Subnets != nil && len(result.Subnets) > 0 { + var filterd = []Subnet{} + for _, subnet := range result.Subnets { + // subnet az is logical zone + if subnet.Az == args.ZoneName { + if args.VpcId == "" || args.VpcId == subnet.VpcId { + filterd = append(filterd, subnet) + } + } + } + result.Subnets = filterd + } + return result, err +} + +// ListPool - list current pools +// RETURNS: +// - *ListResultWithMarker: the result of list hosts with marker +// - error: nil if success otherwise the specific error +func (cli *Client) ListPool(marker *Marker) (*ListPoolResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getPoolUri()) + req.SetMethod(http.GET) + if marker != nil { + req.SetParam(KEY_MARKER, marker.Marker) + req.SetParam(KEY_MAX_KEYS, strconv.Itoa(marker.MaxKeys)) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPoolResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListDeploySets - list all deploy sets +// RETURNS: +// - *ListResultWithMarker: the result of list deploy sets with marker +// - error: nil if success otherwise the specific error +func (cli *Client) ListDeploySets(poolId string, marker *Marker) (*ListDeploySetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUri(poolId)) + req.SetMethod(http.GET) + if marker != nil { + req.SetParam(KEY_MARKER, marker.Marker) + req.SetParam(KEY_MAX_KEYS, strconv.Itoa(marker.MaxKeys)) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListDeploySetResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - poolId: the id of the pool +// - deploySetId: the id of the deploy set +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (cli *Client) DeleteDeploySet(poolId string, deploySetId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(poolId, deploySetId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + + return nil +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - poolId: the id of the pool +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *DeploySet: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (cli *Client) GetDeploySet(poolId string, deploySetId string) (*DeploySet, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(poolId, deploySetId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeploySet{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetSecurityIps - get all SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *GetSecurityIpsResult: all security IP +// - error: nil if success otherwise the specific error +func (c *Client) GetSecurityIps(instanceId string) (*GetSecurityIpsResult, error) { + rowResult := &SecurityIpsRawResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/authIp"). + WithResult(rowResult). + Do() + // to compat rds api,json annotations for SecurityIps are different + result := &GetSecurityIpsResult{ + SecurityIps: rowResult.SecurityIps, + } + return result, err +} + +// UpdateSecurityIps - update SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: all SecurityIps +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSecurityIps(instacneId string, args *UpdateSecurityIpsArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instacneId)+"/updateAuthIp"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ListParameters - list all parameters of a RDS instance +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListParametersResult: the result of list all parameters +// - error: nil if success otherwise the specific error +func (c *Client) ListParameters(instanceId string) (*ListParametersResult, error) { + result := &ListParametersResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/parameter" + "/list"). + WithResult(result). + Do() + + return result, err +} + +// UpdateParameter - update Parameter +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: *UpdateParameterArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateParameter(instanceId string, args *UpdateParameterArgs) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/parameter"+"/modify"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return err +} + +// CreateBackup - create backup of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateBackup(instanceId string) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDdcUriWithInstanceId(instanceId)+"/snapshot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return err +} + +// GetBackupDetail - get details of the instance'Backup +// +// PARAMS: +// - instanceId: the id of the instance +// - snapshotId: the id of the backup +// +// RETURNS: +// - *BackupDetailResult: the detail of the backup +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupDetail(instanceId string, snapshotId string) (*BackupDetailResult, error) { + result := &BackupDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/snapshot" + "/" + snapshotId). + WithResult(result). + Do() + + return result, err +} + +// ModifyBackupPolicy - update backupPolicy +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: the specific rds Instance's BackupPolicy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyBackupPolicy(instanceId string, args *BackupPolicy) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/snapshot"+"/update"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return err +} + +// GetBinlogList - get backup list of the instance +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *BinlogListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *Client) GetBinlogList(instanceId string, datetime string) (*BinlogListResult, error) { + + result := &BinlogListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)+"/binlog"). + WithQueryParam("datetime", datetime). + WithResult(result). + Do() + + return result, err +} + +// GetBinlogDetail - get details of the instance'Binlog +// +// PARAMS: +// - instanceId: the id of the instance +// - binlog: the id of the binlog +// +// RETURNS: +// - *BinlogDetailResult: the detail of the binlog +// - error: nil if success otherwise the specific error +func (c *Client) GetBinlogDetail(instanceId string, binlog string) (*BinlogDetailResult, error) { + result := &BinlogDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/binlog" + "/" + binlog). + WithResult(result). + Do() + + return result, err +} + +// SwitchInstance - main standby switching of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// - args: switch now or wait to the maintain time +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SwitchInstance(instanceId string, args *SwitchArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/switchMaster"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return err +} + +// CreateDatabase - create a database with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateDatabase(instanceId string, args *CreateDatabaseArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.DbName == "" { + return fmt.Errorf("unset DbName") + } + + if args.CharacterSetName == "" { + return fmt.Errorf("unset CharacterSetName") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDatabaseUriWithInstanceId(instanceId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteDatabase - delete an database of a DDC instance +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - dbName: the specific database's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDatabase(instanceId, dbName string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getDatabaseUriWithDbName(instanceId, dbName)). + Do() +} + +// UpdateDatabaseRemark - update a database remark with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - dbName: the specific accountName +// - args: the arguments to update a database remark +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateDatabaseRemark(instanceId string, dbName string, args *UpdateDatabaseRemarkArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + //if args.Remark == "" { + // return fmt.Errorf("unset Remark") + //} + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDatabaseUriWithDbName(instanceId, dbName)). + WithQueryParam("remark", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetDatabase - get an database of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - dbName: the specific database's name +// +// RETURNS: +// - *Database: the database's meta +// - error: nil if success otherwise the specific error +func (c *Client) GetDatabase(instanceId, dbName string) (*Database, error) { + result := &DatabaseResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDatabaseUriWithDbName(instanceId, dbName)). + WithResult(result). + Do() + + return &result.Database, err +} + +// ListDatabase - list all database of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *ListDatabaseResult: the result of list all database, contains all databases' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListDatabase(instanceId string) (*ListDatabaseResult, error) { + result := &ListDatabaseResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDatabaseUriWithInstanceId(instanceId)). + WithResult(result). + Do() + + return result, err +} + +// CreateAccount - create a account with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateAccount(instanceId string, args *CreateAccountArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.AccountName == "" { + return fmt.Errorf("unset AccountName") + } + + if args.Password == "" { + return fmt.Errorf("unset Password") + } + + if args.AccountType == "" { + args.AccountType = "common" + } + if args.AccountType == "Super" { + args.AccountType = "rdssuper" + } + if args.AccountType == "Common" { + args.AccountType = "common" + } + if args.DatabasePrivileges != nil { + for idx, _ := range args.DatabasePrivileges { + if args.DatabasePrivileges[idx].AuthType == "ReadOnly" { + args.DatabasePrivileges[idx].AuthType = "readOnly" + } else if args.DatabasePrivileges[idx].AuthType == "ReadWrite" { + args.DatabasePrivileges[idx].AuthType = "readWrite" + } + } + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAccountUriWithInstanceId(instanceId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteAccount - delete an account of a RDS instance +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - accountName: the specific account's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAccount(instanceId, accountName string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + Do() +} + +// UpdateAccountPassword - update a account password with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPassword(instanceId string, accountName string, args *UpdateAccountPasswordArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.Password == "" { + return fmt.Errorf("unset Password") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithQueryParam("password", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateAccountDesc - update a account desc with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account remark +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountDesc(instanceId string, accountName string, args *UpdateAccountDescArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + //if args.Remark == "" { + // return fmt.Errorf("unset Remark") + //} + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithQueryParam("remark", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateAccountPrivileges - update a account privileges with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account privileges +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPrivileges(instanceId string, accountName string, args *UpdateAccountPrivilegesArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + for idx, _ := range args.DatabasePrivileges { + if args.DatabasePrivileges[idx].AuthType == "ReadOnly" { + args.DatabasePrivileges[idx].AuthType = "readOnly" + } else if args.DatabasePrivileges[idx].AuthType == "ReadWrite" { + args.DatabasePrivileges[idx].AuthType = "readWrite" + } + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithQueryParam("privileges", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetAccount - get an account of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - accountName: the specific account's name +// +// RETURNS: +// - *Account: the account's meta +// - error: nil if success otherwise the specific error +func (c *Client) GetAccount(instanceId, accountName string) (*Account, error) { + result := &AccountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithResult(result). + Do() + + if result.Account.AccountType == "common" { + result.Account.AccountType = "Common" + } else if result.Account.AccountType == "rdssuper" { + result.Account.AccountType = "Super" + } + + for idx, _ := range result.Account.DatabasePrivileges { + if result.Account.DatabasePrivileges[idx].AuthType == "readOnly" { + result.Account.DatabasePrivileges[idx].AuthType = "ReadOnly" + } else if result.Account.DatabasePrivileges[idx].AuthType == "readWrite" { + result.Account.DatabasePrivileges[idx].AuthType = "ReadWrite" + } + } + result.Account.Status = strings.Title(result.Account.Status) + return &result.Account, err +} + +// ListAccount - list all account of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListAccountResult: the result of list all account, contains all accounts' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListAccount(instanceId string) (*ListAccountResult, error) { + result := &ListAccountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAccountUriWithInstanceId(instanceId)). + WithResult(result). + Do() + for idx, _ := range result.Accounts { + if result.Accounts[idx].AccountType == "common" { + result.Accounts[idx].AccountType = "Common" + } else if result.Accounts[idx].AccountType == "rdssuper" { + result.Accounts[idx].AccountType = "Super" + } + result.Accounts[idx].Status = strings.Title(result.Accounts[idx].Status) + + for iidx, _ := range result.Accounts[idx].DatabasePrivileges { + if result.Accounts[idx].DatabasePrivileges[iidx].AuthType == "readOnly" { + result.Accounts[idx].DatabasePrivileges[iidx].AuthType = "ReadOnly" + } else if result.Accounts[idx].DatabasePrivileges[iidx].AuthType == "readWrite" { + result.Accounts[idx].DatabasePrivileges[iidx].AuthType = "ReadWrite" + } + } + } + return result, err +} + +// ListRoGroup - list all roGroups of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListRoGroupResult: All roGroups of the current instance +// - error: nil if success otherwise the specific error +func (c *Client) ListRoGroup(instanceId string) (*ListRoGroupResult, error) { + result := &ListRoGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRoGroupUriWithInstanceId(instanceId) + "/list"). + WithResult(result). + Do() + + return result, err +} + +// ListVpc - list all Vpc +// +// PARAMS: +// RETURNS: +// - *ListVpc: All vpc of +// - error: nil if success otherwise the specific error +func (c *Client) ListVpc() (*[]VpcVo, error) { + result := &[]VpcVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUri() + "/vpcList"). + WithResult(result). + Do() + + return result, err +} + +// GetMaintenTime - get details of the maintenTime +// +// PARAMS: +// - poolId: the id of the pool +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *DeploySet: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *Client) GetMaintainTime(instanceId string) (*MaintainTime, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getMaintainTimeUriWithInstanceId(instanceId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &MaintainWindow{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return &jsonBody.MaintainTime, nil +} + +// UpdateMaintenTime - update UpdateMaintenTime of instance +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateMaintainTime(instanceId string, args *MaintainTime) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUpdateMaintainTimeUriWithInstanceId(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListRecycleInstances - list all instances in recycler with marker +// +// PARAMS: +// - marker: marker page +// +// RETURNS: +// - *RecyclerInstanceList: the result of instances in recycler +// - error: nil if success otherwise the specific error +func (c *Client) ListRecycleInstances(marker *Marker) (*RecyclerInstanceList, error) { + result := &RecyclerInstanceList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParams(getMarkerParams(marker)). + WithURL(getRecyclerUrl()). + WithResult(result). + Do() + + return result, err +} + +// RecoverRecyclerInstances - batch recover instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to recover +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecoverRecyclerInstances(instanceIds []string) error { + if instanceIds == nil || len(instanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return fmt.Errorf("the instanceIds length max value is 10") + } + + args := &BatchInstanceIds{ + InstanceIds: strings.Join(instanceIds, COMMA), + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRecyclerRecoverUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// DeleteRecyclerInstances - batch delete instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecyclerInstances(instanceIds []string) error { + if instanceIds == nil || len(instanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return fmt.Errorf("the instanceIds length max value is 10") + } + + // delete use query params + instanceIdsParam := strings.Join(instanceIds, COMMA) + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRecyclerDeleteUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("instanceIds", instanceIdsParam). + Do() + return err +} + +// ListSecurityGroupByVpcId - list security groups by vpc id +// +// PARAMS: +// - vpcId: id of vpc +// +// RETURNS: +// - *[]SecurityGroup:security groups of vpc +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroupByVpcId(vpcId string) (*[]SecurityGroup, error) { + if len(vpcId) < 1 { + return nil, fmt.Errorf("unset vpcId") + } + result := &[]SecurityGroup{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupWithVpcIdUrl(vpcId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// ListSecurityGroupByInstanceId - list security groups by instance id +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *ListSecurityGroupResult: list secrity groups result of instance +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroupByInstanceId(instanceId string) (*ListSecurityGroupResult, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + result := &ListSecurityGroupResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupWithInstanceIdUrl(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// BindSecurityGroups - bind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBindSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// UnBindSecurityGroups - unbind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUnBindSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ReplaceSecurityGroups - replace SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ReplaceSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getReplaceSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListLogByInstanceId - list error or slow logs of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *[]Log:logs of instance +// - error: nil if success otherwise the specific error +func (c *Client) ListLogByInstanceId(instanceId string, args *ListLogArgs) (*[]Log, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if args == nil { + return nil, fmt.Errorf("unset list args") + } + if "error" != args.LogType && "slow" != args.LogType { + return nil, fmt.Errorf("invalid logType, should be 'error' or 'slow'") + } + result := &[]Log{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getLogsUrlWithInstanceId(instanceId)). + WithQueryParam("logType", strings.ToLower(args.LogType)). + WithQueryParam("datetime", args.Datetime). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetLogById - get log's detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Log:log's detail of instance +// - error: nil if success otherwise the specific error +func (c *Client) GetLogById(instanceId, logId string, args *GetLogArgs) (*LogDetail, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(logId) < 1 { + return nil, fmt.Errorf("unset logId") + } + if args == nil { + return nil, fmt.Errorf("unset get log args") + } + + result := &LogDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getLogsUrlWithLogId(instanceId, logId)). + WithQueryParam("downloadValidTimeInSec", strconv.Itoa(args.ValidSeconds)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// LazyDropCreateHardLink - create a hard link for specified large table +// +// PARAMS: +// - instanceId: id of instance +// - dbName: name of database +// - tableName: name of table +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) LazyDropCreateHardLink(instanceId, dbName, tableName string) error { + if len(instanceId) < 1 { + return fmt.Errorf("unset instanceId") + } + if len(dbName) < 1 { + return fmt.Errorf("unset dbName") + } + if len(tableName) < 1 { + return fmt.Errorf("unset tableName") + } + + args := &CreateTableHardLinkArgs{ + TableName: tableName, + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getCreateTableHardLinkUrl(instanceId, dbName)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// LazyDropDeleteHardLink - delete the hard link for specified large table +// +// PARAMS: +// - instanceId: id of instance +// - dbName: name of database +// - tableName: name of table +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) LazyDropDeleteHardLink(instanceId, dbName, tableName string) error { + if len(instanceId) < 1 { + return fmt.Errorf("unset instanceId") + } + if len(dbName) < 1 { + return fmt.Errorf("unset dbName") + } + if len(tableName) < 1 { + return fmt.Errorf("unset tableName") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getTableHardLinkUrl(instanceId, dbName, tableName)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + return err +} + +// ResizeRds - resize an RDS with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to resize an RDS +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeRds(instanceId string, args *ResizeRdsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId) + "/resize"). + WithBody(args). + Do() +} + +// UpdateSyncMode - update sync mode of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update syncMode +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifySyncMode(instanceId string, args *ModifySyncModeArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getChangeSemiSyncStatusUrlWithId(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetDisk - get disk detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Disk:disk of instance +// - error: nil if success otherwise the specific error +func (c *Client) GetDisk(instanceId string) (*Disk, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &Disk{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)+"/disk"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// SnapshotAccessDetail - get snapshot access detail +// +// PARAMS: +// - args: the arguments to get snapshot access detail +// +// RETURNS: +// - *AccessDetail +// - error: nil if success otherwise the specific error +func (c *Client) SnapshotAccessDetail(args *AccessDetailArgs) (*BackupAccessDetail, error) { + + result := &BackupAccessDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUri()+"/snapshot/accessdetail"). + WithQueryParam("startDateTime", args.StartDateTime). + WithQueryParam("endDateTime", args.EndDateTime). + WithQueryParam("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("dataType", args.DataType). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// BinlogAccessDetail - get snapshot access detail +// +// PARAMS: +// - args: the arguments to get snapshot access detail +// +// RETURNS: +// - *AccessDetail +// - error: nil if success otherwise the specific error +func (c *Client) BinlogAccessDetail(args *AccessDetailArgs) (*BackupAccessDetail, error) { + + result := &BackupAccessDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUri()+"/binlog/accessdetail"). + WithQueryParam("startDateTime", args.StartDateTime). + WithQueryParam("endDateTime", args.EndDateTime). + WithQueryParam("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("dataType", args.DataType). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} diff --git a/bce-sdk-go/services/ddc/ddc_util/util.go b/bce-sdk-go/services/ddc/ddc_util/util.go new file mode 100644 index 0000000..e24ecb7 --- /dev/null +++ b/bce-sdk-go/services/ddc/ddc_util/util.go @@ -0,0 +1,54 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of RDS service +package ddc_util + +import ( + "bytes" + "encoding/gob" + "encoding/hex" + "errors" + "fmt" + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} + +// 拷贝字段内容工具 +func SimpleCopyProperties(dst, src interface{}) (err error) { + // 防止意外panic + defer func() { + if e := recover(); e != nil { + err = errors.New(fmt.Sprintf("%v", e)) + } + }() + + var buf bytes.Buffer + if err := gob.NewEncoder(&buf).Encode(src); err != nil { + return err + } + return gob.NewDecoder(bytes.NewBuffer(buf.Bytes())).Decode(dst) +} diff --git a/bce-sdk-go/services/ddc/model.go b/bce-sdk-go/services/ddc/model.go new file mode 100644 index 0000000..4405df5 --- /dev/null +++ b/bce-sdk-go/services/ddc/model.go @@ -0,0 +1,817 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package ddc + +import "github.com/baidubce/bce-sdk-go/model" + +type CreateInstanceArgs struct { + ClientToken string `json:"-"` + InstanceType string `json:"instanceType"` + Number int `json:"number"` + Instance CreateInstance `json:"instance"` +} + +type CreateRdsArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing"` + PurchaseCount int `json:"purchaseCount,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + Category string `json:"category,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacity int `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + DeployId string `json:"deployId"` + PoolId string `json:"poolId"` + SyncMode string `json:"syncMode"` +} + +type CreateReadReplicaArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing"` + PurchaseCount int `json:"purchaseCount,omitempty"` + SourceInstanceId string `json:"sourceInstanceId"` + InstanceName string `json:"instanceName,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacity int `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + DeployId string `json:"deployId"` + PoolId string `json:"poolId"` + RoGroupId string `json:"roGroupId"` + EnableDelayOff bool `json:"enableDelayOff"` + DelayThreshold int `json:"delayThreshold"` + LeastInstanceAmount int `json:"leastInstanceAmount"` + RoGroupWeight int `json:"roGroupWeight"` +} + +type Instance struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + Category string `json:"category"` + InstanceStatus string `json:"instanceStatus"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"allocatedMemoryInGB"` + VolumeCapacity int `json:"allocatedStorageInGB"` + NodeAmount int `json:"nodeAmount"` + UsedStorage float64 `json:"usedStorageInGB"` + PublicAccessStatus bool `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + Endpoint Endpoint `json:"endpoint"` + SyncMode string `json:"syncMode"` + BackupPolicy BackupPolicy `json:"backupPolicy"` + Region string `json:"region"` + InstanceType string `json:"type"` + SourceInstanceId string `json:"sourceInstanceId"` + SourceRegion string `json:"sourceRegion"` + ZoneNames []string `json:"zoneNames"` + VpcId string `json:"vpcId"` + Subnets []Subnet `json:"subnets"` + Topology Topology `json:"topology"` + PaymentTiming string `json:"paymentTiming"` + RoGroupList []RoGroup `json:"roGroupList"` + NodeMaster NodeInfo `json:"nodeMaster"` + NodeSlave NodeInfo `json:"nodeSlave"` + NodeReadReplica NodeInfo `json:"nodeReadReplica"` + DeployId string `json:"deployId"` +} + +type SubnetMap struct { + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation Reservation `json:"reservation,omitempty"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength,omitempty"` + ReservationTimeUnit string `json:"reservationTimeUnit,omitempty"` +} + +type CreateResult struct { + InstanceIds []string `json:"instanceIds"` +} + +type InstanceModelResult struct { + Instance InstanceModel `json:"instance"` +} + +type CreateInstance struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + SourceInstanceId string `json:"sourceInstanceId"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + CpuCount int `json:"cpuCount"` + AllocatedMemoryInGB int `json:"allocatedMemoryInGB"` + AllocatedStorageInGB int `json:"allocatedStorageInGB"` + AZone string `json:"azone"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + DiskIoType string `json:"diskIoType"` + DeployId string `json:"deployId"` + PoolId string `json:"poolId"` + RoGroupId string `json:"roGroupId"` + EnableDelayOff bool `json:"enableDelayOff"` + DelayThreshold int `json:"delayThreshold"` + LeastInstanceAmount int `json:"leastInstanceAmount"` + RoGroupWeight int `json:"roGroupWeight"` + IsDirectPay bool `json:"IsDirectPay"` + Billing Billing `json:"billing"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Category string `json:"category,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + SyncMode string `json:"syncMode"` +} + +type Pool struct { + CPUQuotaTotal int `json:"cpuQuotaTotal"` + CPUQuotaUsed int `json:"cpuQuotaUsed"` + CreateTime string `json:"createTime"` + DeployMethod string `json:"deployMethod"` + DiskQuotaTotal int `json:"diskQuotaTotal"` + DiskQuotaUsed int `json:"diskQuotaUsed"` + Engine string `json:"engine"` + Hosts []Host `json:"hosts"` + MaxMemoryUsedRatio string `json:"maxMemoryUsedRatio"` + MemoryQuotaTotal int `json:"memoryQuotaTotal"` + MemoryQuotaUsed int `json:"memoryQuotaUsed"` + PoolID string `json:"poolId"` + PoolName string `json:"poolName"` + VpcID string `json:"vpcId"` +} + +type Host struct { + Containers []Container `json:"containers"` + Flavor Flavor `json:"flavor"` + CPUQuotaTotal int `json:"cpuQuotaTotal"` + CPUQuotaUsed int `json:"cpuQuotaUsed"` + DeploymentStatus string `json:"deploymentStatus"` + DiskQuotaTotal int `json:"diskQuotaTotal"` + DiskQuotaUsed int `json:"diskQuotaUsed"` + HostID string `json:"hostId"` + HostName string `json:"hostName"` + ImageType string `json:"imageType"` + MemoryQuotaTotal int64 `json:"memoryQuotaTotal"` + MemoryQuotaUsed int64 `json:"memoryQuotaUsed"` + PnetIP string `json:"pnetIp"` + Role string `json:"role"` + Status string `json:"status"` + SubnetID string `json:"subnetId"` + VnetIP string `json:"vnetIp"` + VpcID string `json:"vpcId"` + Zone string `json:"zone"` +} + +type OperateHostRequest struct { + Action string `json:"action"` +} + +type Flavor struct { + CPUCount int `json:"cpuCount"` + CPUType string `json:"cpuType"` + Disk int `json:"disk"` + FlavorID string `json:"flavorId"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` +} + +type Container struct { + ContainerID string `json:"containerId"` + DeployID string `json:"deployId"` + DeployName string `json:"deployName"` + Engine string `json:"engine"` + HostID string `json:"hostId"` + HostName string `json:"hostName"` + PoolName string `json:"poolName"` + Role string `json:"role"` + Zone string `json:"zone"` +} + +type DeploySet struct { + CreateTime string `json:"createTime"` + DeployID string `json:"deployId"` + DeployName string `json:"deployName"` + Instances []string `json:"instances"` + PoolID string `json:"poolId"` + Strategy string `json:"strategy"` + CentralizeThreshold int `json:"centralizeThreshold"` +} + +type CreateDeployRequest struct { + ClientToken string `json:"-"` + DeployName string `json:"deployName"` + Strategy string `json:"strategy"` + CentralizeThreshold int `json:"centralizeThreshold"` +} + +type UpdateDeployRequest struct { + ClientToken string `json:"-"` + Strategy string `json:"strategy"` + CentralizeThreshold int `json:"centralizeThreshold"` +} + +type Marker struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListResultWithMarker struct { + IsTruncated bool `json:"isTruncated"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` +} + +type ListPoolResult struct { + ListResultWithMarker + Result []Pool `json:"result"` +} + +type ListHostResult struct { + ListResultWithMarker + Result []Host `json:"result"` +} + +type ListDeploySetResult struct { + ListResultWithMarker + Result []DeploySet `json:"result"` +} + +type InstanceModel struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + InstanceStatus string `json:"instanceStatus"` + CpuCount int `json:"cpuCount"` + AllocatedMemoryInGB float64 `json:"allocatedMemoryInGB"` + AllocatedStorageInGB int `json:"allocatedStorageInGB"` + NodeAmount int `json:"nodeAmount"` + UsedStorageInGB float64 `json:"usedStorageInGB"` + PublicAccessStatus bool `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + Endpoint Endpoint `json:"endpoint"` + SyncMode string `json:"syncMode"` + BackupPolicy BackupPolicy `json:"backupPolicy"` + Region string `json:"region"` + InstanceType string `json:"instanceType"` + SourceInstanceId string `json:"sourceInstanceId"` + SourceRegion string `json:"sourceRegion"` + ZoneNames []string `json:"zoneNames"` + VpcId string `json:"vpcId"` + Subnets []Subnet `json:"subnets"` + NodeMaster NodeInfo `json:"nodeMaster"` + NodeSlave NodeInfo `json:"nodeSlave"` + NodeReadReplica NodeInfo `json:"nodeReadReplica"` + DeployId string `json:"deployId"` + Topology Topology `json:"topology"` + DiskType string `json:"diskType"` + Type string `json:"type"` + ApplicationType string `json:"applicationType"` + RoGroupList []RoGroup `json:"roGroupList"` + PaymentTiming string `json:"paymentTiming"` +} + +type SubnetVo struct { + Name string `json:"name"` + SubnetId string `json:"subnetId"` + Az string `json:"az"` + Cidr string `json:"cidr"` + ShortId string `json:"shortId"` +} + +type RoGroup struct { + RoGroupID string `json:"roGroupId"` + RoGroupName string `json:"roGroupName"` + VnetIP string `json:"vnetIp"` + IsBalanceRoLoad int `json:"isBalanceRoLoad"` + EnableDelayOff int `json:"enableDelayOff"` + DelayThreshold int `json:"delayThreshold"` + LeastInstanceAmount int `json:"leastInstanceAmount"` + ReplicaList []Replica `json:"replicaList"` +} + +type UpdateRoGroupArgs struct { + RoGroupName string `json:"roGroupName"` + IsBalanceRoLoad int `json:"isBalanceRoLoad"` + EnableDelayOff int `json:"enableDelayOff"` + DelayThreshold int `json:"delayThreshold"` + LeastInstanceAmount int `json:"leastInstanceAmount"` +} + +type UpdateRoGroupWeightArgs struct { + IsBalanceRoLoad int `json:"isBalanceRoLoad"` + ReplicaList []ReplicaWeight `json:"replicaList"` +} +type ReplicaWeight struct { + InstanceId string `json:"instanceId"` + Weight int `json:"weight"` +} + +type Replica struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Status string `json:"status"` + RoGroupWeight int `json:"roGroupWeight"` +} + +type NodeInfo struct { + Id string `json:"id"` + Azone string `json:"azone"` + SubnetId string `json:"subnetId"` + Cidr string `json:"cidr"` + Name string `json:"name"` + HostName string `json:"hostname"` +} + +type Subnet struct { + Name string `json:"name"` + SubnetId string `json:"subnetId"` + ZoneName string `json:"zoneName"` + Cidr string `json:"cidr"` + ShortId string `json:"shortId"` + VpcId string `json:"vpcId"` + VpcShortId string `json:"vpcShortId"` + Az string `json:"az"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` +} + +type Endpoint struct { + Address string `json:"address"` + Port int `json:"port"` + VnetIp string `json:"vnetIp"` + VnetIpBackup string `json:"vnetIpBackup"` + InetIp string `json:"inetIp"` +} + +type BackupPolicy struct { + BackupDays string `json:"backupDays"` + BackupTime string `json:"backupTime"` + Persistent bool `json:"persistent"` + ExpireInDays int `json:"expireInDays"` + FreeSpaceInGB int `json:"freeSpaceInGb"` +} + +type Topology struct { + Rdsproxy []string `json:"rdsproxy"` + Master []string `json:"master"` + ReadReplica []string `json:"readReplica"` +} + +type DeleteDdcArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type UpdateInstanceNameArgs struct { + InstanceName string `json:"instanceName"` +} + +type ListRdsResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Instances []Instance `json:"result"` +} + +type ListRdsArgs struct { + Marker string + MaxKeys int +} + +type GetBackupListResult struct { + Snapshots []Snapshot `json:"snapshots"` + FreeSpaceInMB int64 `json:"freeSpaceInMB"` + UsedSpaceInMB int64 `json:"usedSpaceInMB"` +} + +type GetZoneListResult struct { + Zones []ZoneName `json:"zones"` +} + +type ZoneName struct { + ZoneNames []string `json:"apiZoneNames"` + ApiZoneNames []string `json:"zoneNames"` + Available bool `json:"bool"` + DefaultSubnetId string `json:"defaultSubnetId"` +} + +type ListSubnetsArgs struct { + VpcId string `json:"vpcId"` + ZoneName string `json:"zoneName"` +} + +type ListSubnetsResult struct { + Subnets []Subnet `json:"subnets"` +} + +type SecurityIpsRawResult struct { + SecurityIps []string `json:"ip"` +} + +type UpdateSecurityIpsArgs struct { + SecurityIps []string `json:"securityIps"` +} + +type ListParametersResult struct { + Items []Parameter `json:"items"` +} + +type Parameter struct { + Name string `json:"name"` + DefaultValue string `json:"defaultValue"` + Value string `json:"value"` + PendingValue string `json:"pendingValue"` + Type string `json:"type"` + Dynamic bool `json:"dynamic"` + Modifiable bool `json:"modifiable"` + AllowedValues string `json:"allowedValues"` + Desc string `json:"desc"` +} + +type UpdateParameterArgs struct { + Parameters []KVParameter `json:"parameters"` +} + +type KVParameter struct { + Name string `json:"name"` + Value string `json:"value"` +} + +type Snapshot struct { + SnapshotId string `json:"snapshotId"` + SnapshotSizeInBytes string `json:"snapshotSizeInBytes"` + SnapshotType string `json:"snapshotType"` + SnapshotStatus string `json:"snapshotStatus"` + SnapshotStartTime string `json:"snapshotStartTime"` + SnapshotEndTime string `json:"snapshotEndTime"` +} + +type SnapshotModel struct { + SnapshotId string `json:"snapshotId"` + SnapshotSizeInBytes string `json:"snapshotSizeInBytes"` + SnapshotType string `json:"snapshotType"` + SnapshotStatus string `json:"snapshotStatus"` + SnapshotStartTime string `json:"snapshotStartTime"` + SnapshotEndTime string `json:"snapshotEndTime"` + DownloadUrl string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type BackupDetailResult struct { + Snapshot SnapshotModel `json:"snapshot"` +} + +type Binlog struct { + BinlogId string `json:"binlogId"` + BinlogSizeInBytes int64 `json:"binlogSizeInBytes"` + BinlogStatus string `json:"binlogStatus"` + BinlogStartTime string `json:"binlogStartTime"` + BinlogEndTime string `json:"binlogEndTime"` +} + +type BinlogModel struct { + BinlogId string `json:"binlogId"` + BinlogSizeInBytes int64 `json:"binlogSizeInBytes"` + BinlogStatus string `json:"binlogStatus"` + BinlogStartTime string `json:"binlogStartTime"` + BinlogEndTime string `json:"binlogEndTime"` + DownloadUrl string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type BinlogListResult struct { + Binlogs []Binlog `json:"binlogs"` +} + +type BinlogDetailResult struct { + Binlog BinlogModel `json:"binlog"` +} + +type AuthType string + +const ( + AuthType_ReadOnly AuthType = "readOnly" + AuthType_ReadWrite AuthType = "readWrite" +) + +type AccountPrivilege struct { + AccountName string `json:"accountName"` + AuthType AuthType `json:"authType"` +} + +type CreateDatabaseArgs struct { + ClientToken string `json:"-"` + DbName string `json:"dbName"` + CharacterSetName string `json:"characterSetName"` + Remark string `json:"remark"` +} + +type UpdateDatabaseRemarkArgs struct { + Remark string `json:"remark"` +} + +type Database struct { + DbName string `json:"dbName"` + CharacterSetName string `json:"characterSetName"` + DbStatus string `json:"dbStatus"` + Remark string `json:"remark"` + AccountPrivileges []AccountPrivilege `json:"accountPrivileges"` +} + +type DatabaseResult struct { + Database Database `json:"database"` +} + +type ListDatabaseResult struct { + Databases []Database `json:"databases"` +} + +// Account +type AccountType string + +const ( + AccountType_Super AccountType = "rdssuper" + AccountType_Common AccountType = "common" +) + +type CreateAccountArgs struct { + ClientToken string `json:"-"` + AccountName string `json:"accountName"` + Password string `json:"password"` + // 为了兼容 RDS 参数结构 + AccountType AccountType `json:"type"` + Desc string `json:"remark"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges,omitempty"` +} + +type DatabasePrivilege struct { + DbName string `json:"dbName"` + AuthType string `json:"authType"` +} + +type Account struct { + AccountName string `json:"accountName"` + Desc string `json:"remark"` + Status string `json:"accountStatus"` + AccountType string `json:"accountType"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` +} + +type AccountResult struct { + Account Account `json:"account"` +} + +type ListAccountResult struct { + Accounts []Account `json:"accounts"` +} + +type UpdateAccountPasswordArgs struct { + Password string `json:"password"` +} + +type UpdateAccountDescArgs struct { + Desc string `json:"remark"` +} + +type UpdateAccountPrivilegesArgs struct { + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` +} + +type ListRoGroupResult struct { + RoGroups []RoGroup `json:"roGroups"` +} + +type VpcVo struct { + VpcId string `json:"vpcId"` + ShortId string `json:"shortId"` + Name string `json:"name"` + Cidr string `json:"cidr"` + Status int `json:"status"` + CreateTime string `json:"createTime"` + Description string `json:"description"` + DefaultVpc bool `json:"defaultVpc"` + Ipv6Cidr string `json:"ipv6Cidr"` + AuxiliaryCidr []string `json:"auxiliaryCidr"` + Relay bool `json:"relay"` +} +type GetBackupListArgs struct { + Marker string + MaxKeys int +} +type GetSecurityIpsResult struct { + Etag string `json:"etag"` + SecurityIps []string `json:"securityIps"` +} + +type ResizeRdsArgs struct { + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + NodeAmount int `json:"nodeAmount,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + IsResizeNow bool `json:"isResizeNow,omitempty"` +} + +type RebootArgs struct { + IsRebootNow bool `json:"isRebootNow"` +} + +type SwitchArgs struct { + IsSwitchNow bool `json:"isSwitchNow"` +} + +type MaintainWindow struct { + MaintainTime MaintainTime `json:"maintentime"` +} + +type MaintainTime struct { + Period string `json:"period"` + StartTime string `json:"startTime"` + Duration int `json:"duration"` +} + +type RecycleInstance struct { + EngineVersion string `json:"engineVersion"` + VolumeCapacity int `json:"volumeCapacity"` + ApplicationType string `json:"applicationType"` + InstanceName string `json:"instanceName"` + PublicAccessStatus string `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceType string `json:"instanceType"` + Type string `json:"type"` + InstanceStatus string `json:"instanceStatus"` + MemoryCapacity float64 `json:"memoryCapacity"` + InstanceId string `json:"instanceId"` + Engine string `json:"engine"` + VpcId string `json:"vpcId"` + PubliclyAccessible bool `json:"publiclyAccessible"` + InstanceExpireTime string `json:"instanceExpireTime"` + DiskType string `json:"diskType"` + Region string `json:"region"` + CpuCount int `json:"cpuCount"` + UsedStorage float64 `json:"usedStorage"` +} + +type RecyclerInstanceList struct { + ListResultWithMarker + Result []RecycleInstance `json:"result"` +} + +type BatchInstanceIds struct { + InstanceIds string `json:"instanceIds"` +} + +type SecurityGroup struct { + Name string `json:"name"` + SecurityGroupID string `json:"securityGroupId"` + Description string `json:"description"` + TenantID string `json:"tenantId"` + AssociateNum int `json:"associateNum"` + VpcID string `json:"vpcId"` + VpcShortID string `json:"vpcShortId"` + VpcName string `json:"vpcName"` + CreatedTime string `json:"createdTime"` + Version int `json:"version"` + DefaultSecurityGroup int `json:"defaultSecurityGroup"` +} + +type SecurityGroupArgs struct { + InstanceIds []string `json:"instanceIds"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type ListSecurityGroupResult struct { + Groups []SecurityGroupDetail `json:"groups"` +} + +type SecurityGroupRule struct { + PortRange string `json:"portRange"` + Protocol string `json:"protocol"` + RemoteGroupID string `json:"remoteGroupId"` + RemoteIP string `json:"remoteIP"` + Ethertype string `json:"ethertype"` + TenantID string `json:"tenantId"` + Name string `json:"name"` + ID string `json:"id"` + SecurityGroupRuleID string `json:"securityGroupRuleId"` + Direction string `json:"direction"` +} + +type SecurityGroupDetail struct { + SecurityGroupName string `json:"securityGroupName"` + SecurityGroupID string `json:"securityGroupId"` + SecurityGroupRemark string `json:"securityGroupRemark"` + Inbound []SecurityGroupRule `json:"inbound"` + Outbound []SecurityGroupRule `json:"outbound"` + VpcName string `json:"vpcName"` + VpcID string `json:"vpcId"` + ProjectID string `json:"projectId"` +} + +type ListLogArgs struct { + LogType string `json:"logType"` + Datetime string `json:"datetime"` +} + +type Log struct { + LogStartTime string `json:"logStartTime"` + LogEndTime string `json:"logEndTime"` + LogID string `json:"logId"` + LogSizeInBytes int `json:"logSizeInBytes"` +} + +type LogDetail struct { + Log + DownloadURL string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type GetLogArgs struct { + ValidSeconds int `json:"downloadValidTimeInSec"` +} + +type CreateTableHardLinkArgs struct { + TableName string `json:"tableName"` +} + +type ModifySyncModeArgs struct { + SyncMode string `json:"syncMode"` +} +type Disk struct { + CapacityRatio []string `json:"capacityRatio"` +} + +type AccessDetailItem struct { + BackupID string `json:"backupID"` + AccessDateTime string `json:"accessDateTime"` + AccessResult string `json:"accessResult"` + AccessSrcAddressType string `json:"accessSrcAddressType"` + AvailableZone string `json:"availableZone"` + AccessSrcAddress string `json:"accessSrcAddress"` + AccessOperationType string `json:"accessOperationType"` + StorageType string `json:"storageType"` + StorageAddress string `json:"storageAddress"` + Region string `json:"region"` + BackupName string `json:"backupName"` + AccessSrcAgent string `json:"accessSrcAgent"` + StorageID string `json:"storageID"` +} + +type Pagination struct { + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Marker string `json:"marker"` + TotalKeys int `json:"totalKeys"` +} +type BackupAccessDetail struct { + StartDateTime string `json:"startDateTime"` + EndDateTime string `json:"endDateTime"` + DataType string `json:"dataType"` + BackupAccessDetails []AccessDetailItem `json:"backupAccessDetails"` + Pagination Pagination `json:"pagination"` +} + +type AccessDetailArgs struct { + StartDateTime string `json:"startDateTime"` + EndDateTime string `json:"endDateTime"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + DataType string `json:"dataType,omitempty"` +} diff --git a/bce-sdk-go/services/ddc/v2/client.go b/bce-sdk-go/services/ddc/v2/client.go new file mode 100644 index 0000000..5b74db6 --- /dev/null +++ b/bce-sdk-go/services/ddc/v2/client.go @@ -0,0 +1,353 @@ +package ddcrds + +import ( + "fmt" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/rds" +) + +const ( + DEFAULT_ENDPOINT = "ddc.su.baidubce.com" + DDC_NOT_SUPPORTED = "DDC does not support this feature." + RDS_NOT_SUPPORTED = "RDS does not support this feature." + URI_PREFIX = bce.URI_PREFIX + "v1/ddc" + URI_PREFIX_V2 = bce.URI_PREFIX + "v2/ddc" + REQUEST_DDC_INSTANCE_URL = "/instance" + REQUEST_DDC_POOL_URL = "/pool" + REQUEST_DDC_HOST_URL = "/host" + REQUEST_DDC_TASK_URL = "/task" + REQUEST_DDC_DEPLOY_URL = "/deploy" + REQUEST_DDC_DATABASE_URL = "/database" + REQUEST_DDC_TABLE_URL = "/table" + REQUEST_DDC_HARDLINK_URL = "/link" + REQUEST_DDC_ACCOUNT_URL = "/account" + REQUEST_DDC_ROGROUP_URL = "/roGroup" + REQUEST_DDC_RECYCLER_URL = "/recycler" + REQUEST_DDC_SECURITYGROUP_URL = "/security" + REQUEST_DDC_LOG_URL = "/logs" + REQUEST_DDC_UPDATE_ACTION = "/update" + REQUEST_DDC_MAINTAINTIME_URL = "/maintenTimeInfo" + REQUEST_UPDATE_MAINTAINTIME_URL = "/updateMaintenTime" +) + +func DDCNotSupportError() error { + return fmt.Errorf(DDC_NOT_SUPPORTED) +} +func RDSNotSupportError() error { + return fmt.Errorf(RDS_NOT_SUPPORTED) +} + +// Client of DDC service is a kind of BceClient, so derived from BceClient +type Client struct { + rdsClient *rds.Client + ddcClient *DDCClient +} + +func (c *Client) Config(config *bce.BceClientConfiguration) { + c.ddcClient.Config = config + c.rdsClient.Config = config +} + +func (c *Client) ConfigEndpoint(endPoint string) { + // 替换Endpoint,优先创建ddc Client + ddcEndpoint := strings.Replace(endPoint, "rds.", "ddc.", 1) + c.ddcClient.Config.Endpoint = ddcEndpoint + // 替换Endpoint + rdsEndpoint := strings.Replace(endPoint, "ddc.", "rds.", 1) + c.rdsClient.Config.Endpoint = rdsEndpoint +} + +func (c *Client) ConfigRegion(region string) { + c.ddcClient.Config.Region = region + c.rdsClient.Config.Region = region +} + +func (c *Client) ConfigRetry(policy bce.RetryPolicy) { + c.ddcClient.Config.Retry = policy + c.rdsClient.Config.Retry = policy +} + +func (c *Client) ConfigSignOption(option *auth.SignOptions) { + c.ddcClient.Config.SignOption = option + c.rdsClient.Config.SignOption = option +} + +func (c *Client) ConfigSignOptionHeadersToSign(header map[string]struct{}) { + c.ddcClient.Config.SignOption.HeadersToSign = header + c.rdsClient.Config.SignOption.HeadersToSign = header +} + +func (c *Client) ConfigSignOptionExpireSeconds(seconds int) { + c.ddcClient.Config.SignOption.ExpireSeconds = seconds + c.rdsClient.Config.SignOption.ExpireSeconds = seconds +} + +func (c *Client) ConfigCredentials(credentials *auth.BceCredentials) { + c.ddcClient.Config.Credentials = credentials + c.rdsClient.Config.Credentials = credentials +} + +func (c *Client) ConfigProxyUrl(proxyUrl string) { + c.ddcClient.Config.ProxyUrl = proxyUrl + c.rdsClient.Config.ProxyUrl = proxyUrl +} + +func (c *Client) ConfigConnectionTimeoutInMillis(millis int) { + c.ddcClient.Config.ConnectionTimeoutInMillis = millis + c.rdsClient.Config.ConnectionTimeoutInMillis = millis +} + +// 内部创建rds和ddc两个client +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + // 替换Endpoint,优先创建ddc Client + ddcEndpoint := strings.Replace(endPoint, "rds.", "ddc.", 1) + ddcClient, err := NewDDCClient(ak, sk, ddcEndpoint) + if err != nil { + return nil, err + } + // 替换Endpoint + rdsEndpoint := strings.Replace(endPoint, "ddc.", "rds.", 1) + rdsClient, err := rds.NewClient(ak, sk, rdsEndpoint) + if err != nil { + return nil, err + } + return &Client{rdsClient: rdsClient, ddcClient: ddcClient}, nil +} + +// Client for DDC service +type DDCClient struct { + *bce.BceClient +} + +func NewDDCClient(ak, sk, endPoint string) (*DDCClient, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &DDCClient{client}, nil +} + +func getDdcUri() string { + return URI_PREFIX +} + +func getDdcInstanceUri() string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL +} + +// Pool URL +func getPoolUri() string { + return URI_PREFIX + REQUEST_DDC_POOL_URL +} + +func getPoolUriWithId(poolId string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId +} + +// Host URL +func getHostUri() string { + return URI_PREFIX + REQUEST_DDC_HOST_URL +} + +func getHostUriWithPnetIp(poolId, hostPnetIP string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId + REQUEST_DDC_HOST_URL + "/" + hostPnetIP +} + +// DeploySet URL +func getDeploySetUri(poolId string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId + REQUEST_DDC_DEPLOY_URL +} + +func getDeploySetUriWithId(poolId, id string) string { + return URI_PREFIX + REQUEST_DDC_POOL_URL + "/" + poolId + REQUEST_DDC_DEPLOY_URL + "/" + id +} + +func getDdcUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId +} + +func getDdcUriWithInstanceIdV2(instanceId string) string { + return URI_PREFIX_V2 + REQUEST_DDC_INSTANCE_URL + "/" + instanceId +} + +// Database URL +func getDatabaseUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL +} + +func getDatabaseUriWithDbName(instanceId string, dbName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL + "/" + dbName +} + +func getQueryDatabaseUriWithDbName(instanceId string, dbName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL + "/" + dbName + "/amount" +} + +func getDatabaseDiskUsageUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL + "/usage" +} + +func getDatabaseRecoverTimeUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_DATABASE_URL + "/recoverableDateTimes" +} + +func getRecoverInstanceDatabaseUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/recoveryToSourceInstanceByDatetime" +} + +// Account URL +func getAccountUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_ACCOUNT_URL +} + +func getAccountUriWithAccountName(instanceId string, accountName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_ACCOUNT_URL + "/" + accountName +} + +// RoGroup URL +func getRoGroupUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_ROGROUP_URL +} + +// MaintainTime URL +func getMaintainTimeUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_MAINTAINTIME_URL +} + +// MaintainTime URL +func getUpdateMaintainTimeUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_UPDATE_MAINTAINTIME_URL +} + +// RoGroup URL +func getUpdateRoGroupUriWithId(roGroupId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + REQUEST_DDC_ROGROUP_URL + "/" + roGroupId + REQUEST_DDC_UPDATE_ACTION +} + +// RoGroupWeight URL +func getUpdateRoGroupWeightUriWithId(roGroupId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + REQUEST_DDC_ROGROUP_URL + "/" + roGroupId + "/updateWeight" +} + +// ReBalance RoGroup URL +func getReBalanceRoGroupUriWithId(roGroupId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + REQUEST_DDC_ROGROUP_URL + "/" + roGroupId + "/balanceRoLoad" +} + +// Recycler URL +func getRecyclerUrl() string { + return URI_PREFIX + REQUEST_DDC_RECYCLER_URL +} + +// Recycler Recover URL +func getRecyclerRecoverUrl() string { + return URI_PREFIX + REQUEST_DDC_RECYCLER_URL + "/batchRecover" +} + +// Recycler Recover URL +func getRecyclerDeleteUrl() string { + return URI_PREFIX + REQUEST_DDC_RECYCLER_URL + "/batchDelete" +} + +// List Security Group By Vpc URL +func getSecurityGroupWithVpcIdUrl(vpcId string) string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/" + vpcId + "/listByVpc" +} + +// List Security Group By Instance URL +func getSecurityGroupWithInstanceIdUrl(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/" + instanceId + "/list" +} + +// Bind Security Group To Instance URL +func getBindSecurityGroupWithUrl() string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/bind" +} + +// UnBind Security Group To Instance URL +func getUnBindSecurityGroupWithUrl() string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/unbind" +} + +// Batch Replace Security Group URL +func getReplaceSecurityGroupWithUrl() string { + return URI_PREFIX + REQUEST_DDC_SECURITYGROUP_URL + "/updateSecurityGroup" +} + +func getAccessLogUrl() string { + return URI_PREFIX + REQUEST_DDC_LOG_URL + "/accessLog" +} + +func getLogsUrlWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_LOG_URL +} + +func getLogsUrlWithLogId(instanceId, logId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_LOG_URL + "/" + logId +} + +func getErrorLogsUrlWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_LOG_URL + "/logErrorDetail" +} + +func getSlowLogsUrlWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + REQUEST_DDC_LOG_URL + "/logSlowDetail" +} + +func getCreateTableHardLinkUrl(instanceId, dbName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + + REQUEST_DDC_DATABASE_URL + "/" + dbName + + REQUEST_DDC_TABLE_URL + REQUEST_DDC_HARDLINK_URL +} + +func getTableHardLinkUrl(instanceId, dbName, tableName string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + + REQUEST_DDC_DATABASE_URL + "/" + dbName + + REQUEST_DDC_TABLE_URL + "/" + tableName + REQUEST_DDC_HARDLINK_URL +} + +func getChangeSemiSyncStatusUrlWithId(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/semisync" +} + +func getKillSessionUri(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/session/kill" +} + +func getKillSessionTaskUri(instanceId string, taskId int) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/session/task" + "/" + strconv.Itoa(taskId) +} + +func getMaintainTaskUri() string { + return URI_PREFIX + REQUEST_DDC_TASK_URL +} + +func getMaintainTaskDetailUri() string { + return URI_PREFIX + REQUEST_DDC_TASK_URL + "/detail" +} + +func getMaintainTaskUriWithTaskId(taskId string) string { + return URI_PREFIX + REQUEST_DDC_TASK_URL + "/" + taskId +} + +func getInstanceBackupStatusUrl(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/backupStatus" +} + +func getInstanceSyncDelayUrl(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/sync_delay" +} + +func getInstanceSyncDelayReplicationUrl(instanceId string) string { + return URI_PREFIX + REQUEST_DDC_INSTANCE_URL + "/" + instanceId + "/replication" +} diff --git a/bce-sdk-go/services/ddc/v2/client_test.go b/bce-sdk-go/services/ddc/v2/client_test.go new file mode 100644 index 0000000..97a6d84 --- /dev/null +++ b/bce-sdk-go/services/ddc/v2/client_test.go @@ -0,0 +1,1811 @@ +package ddcrds + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + DDCRDS_CLIENT *Client + DDC_ID string = "ddc-m8rs4yjz" + ACCOUNT_NAME string = "go_sdk_account_2" + ACCOUNT_PASSWORD string = "go_sdk_password_1" + ACCOUNT_REMARK string = "go-sdk-remark-1" + DB_NAME string = "go_sdk_db_1" + DB_CHARACTER_SET_NAME string = "utf8" + DB_REMARK string = "go_sdk_db_remark" + TASK_ID string = "1173906" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +const ( + SDK_NAME_PREFIX = "sdk_rds_" + POOL = "xdb_005a2d79-a4f4-4bfb-8284-0ffe9ddaa307_pool" + PNETIP = "100.88.65.121" + DEPLOY_ID = "ab89d829-9068-d88e-75bc-64bb6367d036" + DDC_INSTANCE_ID = "ddc-mqv3e72u" + RDS_INSTANCE_ID = "rds-OtTkC1OD" + ETAG = "v0" +) + +var instanceId = DDC_INSTANCE_ID +var client = DDCRDS_CLIENT + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 2; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + panic("config json file of ak/sk not given:") + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + DDCRDS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + client = DDCRDS_CLIENT + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func assertAvailable(instanceId string, t *testing.T) { + result, err := DDCRDS_CLIENT.GetDetail(instanceId) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Available", result.InstanceStatus) +} + +func TestClient_CreateInstance(t *testing.T) { + args := &CreateRdsArgs{ + ClientToken: "81adc02cf0221a753d1ef969eb6c6360", + Billing: Billing{ + PaymentTiming: "Prepaid", + Reservation: Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + PurchaseCount: 1, + InstanceName: "go_sdk_tester", + Engine: "mysql", + EngineVersion: "5.7", + Category: "Standard", + CpuCount: 2, + MemoryCapacity: 4, + VolumeCapacity: 50, + IsDirectPay: true, + AutoRenewTime: 1, + AutoRenewTimeUnit: "month", + PoolId: "xdb_9c72b2ea-a24c-41ba-b6c7-fc4eb7e8f538_pool", + VpcId: "vpc-4mcfvqcitav5", + ZoneNames: []string{"cn-bj-a"}, + Subnets: []SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-izx7eq3wy87e", + }, + }, + } + result, err := DDCRDS_CLIENT.CreateRds(args, "ddc") + ExpectEqual(t.Errorf, nil, err) + fmt.Println("create ddc success, orderId: ", result.OrderId) + for _, e := range result.InstanceIds { + fmt.Println("create ddc success, instanceId: ", e) + } +} + +func TestClient_ListDeploySets(t *testing.T) { + result, err := client.ListDeploySets(POOL, nil) + if err != nil { + fmt.Printf("list deploy set error: %+v\n", err) + return + } + + for i := range result.Result { + deploy := result.Result[i] + fmt.Println("ddc deploy id: ", deploy.DeployID) + fmt.Println("ddc deploy name: ", deploy.DeployName) + fmt.Println("ddc deploy strategy: ", deploy.Strategy) + fmt.Println("ddc deploy create time: ", deploy.CreateTime) + fmt.Println("ddc deploy centralizeThreshold: ", deploy.CentralizeThreshold) + fmt.Println("ddc instance ids: ", deploy.Instances) + } +} + +func TestClient_GetDeploySet(t *testing.T) { + deploy, err := DDCRDS_CLIENT.GetDeploySet(POOL, DEPLOY_ID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, DEPLOY_ID, deploy.DeployID) +} + +func TestClient_DeleteDeploySet(t *testing.T) { + err := DDCRDS_CLIENT.DeleteDeploySet(POOL, "b444142c-69ed-87a6-396b-fc4a76a9754f") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateDeploySet(t *testing.T) { + result, err := DDCRDS_CLIENT.CreateDeploySet(POOL, &CreateDeployRequest{ + DeployName: "api-from-go4", + CentralizeThreshold: 10, + }) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(result.DeployID) +} + +func TestClient_UpdateDeploySet(t *testing.T) { + deployId := "1424c210-f998-1072-9608-9def4d93dec7" + //err := DDCRDS_CLIENT.UpdateDeploySet(POOL, deployId, &UpdateDeployRequest{ + // Strategy: "centralized", + // CentralizeThreshold: 23, + //}) + //ExpectEqual(t.Errorf, nil, err) + + client := DDCRDS_CLIENT + args := &UpdateDeployRequest{ + // 幂等 Token + ClientToken: "xxxyyyzzz", + // 部署策略 支持集中部署(centralized)/完全打散(distributed) + Strategy: "distributed", + // 亲和度阈值 取值范围【0-96】,必须大于原亲和度阈值 + CentralizeThreshold: 30, + } + err := client.UpdateDeploySet(POOL, deployId, args) + if err != nil { + fmt.Printf("update deploy set error: %+v\n", err) + return + } + + fmt.Println("update deploy set success.") +} + +func TestClient_ListParameters(t *testing.T) { + parameters, err := DDCRDS_CLIENT.ListParameters(DDC_INSTANCE_ID) + ExpectEqual(t.Errorf, nil, err) + res, err := json.Marshal(parameters.Parameters) + fmt.Println(len(parameters.Parameters)) + + parameters, err = DDCRDS_CLIENT.ListParameters(RDS_INSTANCE_ID) + ExpectEqual(t.Errorf, nil, err) + res, err = json.Marshal(parameters.Parameters[:3]) + fmt.Println(string(res)) + fmt.Println(string(parameters.Etag)) +} + +func TestClient_UpdateParameter(t *testing.T) { + + instances := getRdsList(t) + for _, e := range *instances { + if "Available" == e.InstanceStatus { + res, err := DDCRDS_CLIENT.ListParameters(e.InstanceId) + ExpectEqual(t.Errorf, nil, err) + args := &UpdateParameterArgs{ + Parameters: []KVParameter{ + { + Name: "auto_increment_increment", + Value: "2", + }, + }, + WaitSwitch: 0, + } + result, er := DDCRDS_CLIENT.UpdateParameter(e.InstanceId, res.Etag, args) + ExpectEqual(t.Errorf, nil, er) + if result != nil { + fmt.Println("update parameter task success: ", result.Result.TaskID) + TASK_ID = result.Result.TaskID + TestClient_GetMaintainTaskDetail(t) + } else { + fmt.Println("update parameter task success.") + } + break + } + } +} + +func getRdsList(t *testing.T) *[]Instance { + listRdsArgs := &ListRdsArgs{} + result, err := DDCRDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + return &result.Instances +} + +func TestClient_GetSecurityIps(t *testing.T) { + ips, err := DDCRDS_CLIENT.GetSecurityIps(DDC_INSTANCE_ID) + ExpectEqual(t.Errorf, ips, ips) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(ips.SecurityIps) + + ips, err = DDCRDS_CLIENT.GetSecurityIps(RDS_INSTANCE_ID) + ExpectEqual(t.Errorf, ips, ips) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(ips.SecurityIps) +} + +// Only DDC +func TestClient_ListRoGroup(t *testing.T) { + ips, err := DDCRDS_CLIENT.ListRoGroup(DDC_INSTANCE_ID) + ExpectEqual(t.Errorf, ips, ips) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(ips) +} + +// Only DDC +func TestClient_UpdateRoGroup(t *testing.T) { + detail, err := client.GetDetail(instanceId) + if err != nil { + fmt.Printf("get ddc detail error: %+v\n", err) + return + } + roGroupList := detail.RoGroupList + if len(roGroupList) < 1 { + fmt.Printf("the ddc instance %s do not have roGroup \n", instanceId) + } + roGroupId := roGroupList[0].RoGroupID + fmt.Println(roGroupId) + args := &UpdateRoGroupArgs{ + RoGroupName: "testRo", + IsBalanceRoLoad: "1", + EnableDelayOff: "1", + DelayThreshold: "0", + LeastInstanceAmount: "1", + MasterDelay: "1", + } + err = client.UpdateRoGroup(roGroupId, args, "ddc") + if err != nil { + fmt.Printf("update ddc roGroup error: %+v\n", err) + return + } + fmt.Println("update ddc roGroup success") +} + +// Only DDC +func TestClient_UpdateRoGroupReplicaWeight(t *testing.T) { + detail, err := client.GetDetail(instanceId) + if err != nil { + fmt.Printf("get ddc detail error: %+v\n", err) + return + } + roGroupList := detail.RoGroupList + if len(roGroupList) < 1 { + fmt.Printf("the ddc instance %s do not have roGroup \n", instanceId) + } + roGroupId := roGroupList[0].RoGroupID + fmt.Println(roGroupId) + replicaId := roGroupList[0].ReplicaList[0].InstanceId + replicaWeight := ReplicaWeight{ + InstanceId: replicaId, + Weight: 20, + } + args := &UpdateRoGroupWeightArgs{ + RoGroupName: "testRo", + EnableDelayOff: "1", + DelayThreshold: "", + LeastInstanceAmount: "0", + IsBalanceRoLoad: "0", + MasterDelay: "1", + ReplicaList: []ReplicaWeight{replicaWeight}, + } + err = client.UpdateRoGroupReplicaWeight(roGroupId, args, "ddc") + if err != nil { + fmt.Printf("update ddc roGroup replica weight error: %+v\n", err) + return + } + fmt.Println("update ddc roGroup replica weight success") +} + +// Only DDC +func TestClient_ReBalanceRoGroup(t *testing.T) { + detail, err := client.GetDetail(instanceId) + if err != nil { + fmt.Printf("get ddc detail error: %+v\n", err) + return + } + roGroupList := detail.RoGroupList + if len(roGroupList) < 1 { + fmt.Printf("the ddc instance %s do not have roGroup \n", instanceId) + } + roGroupId := roGroupList[0].RoGroupID + fmt.Println(roGroupId) + err = client.ReBalanceRoGroup(roGroupId, "ddc") + if err != nil { + fmt.Printf("reBalance ddc roGroup error: %+v\n", err) + return + } + fmt.Println("reBalance ddc roGroup success") +} + +// Only DDC +func TestClient_ListPool(t *testing.T) { + //pools, err := DDCRDS_CLIENT.ListPool(nil, "ddc") + result, err := client.ListPool(nil, "ddc") + if err != nil { + fmt.Printf("list pool error: %+v\n", err) + return + } + + for i := range result.Result { + pool := result.Result[i] + fmt.Println("ddc pool id: ", pool.PoolID) + fmt.Println("ddc pool vpc id: ", pool.VpcID) + fmt.Println("ddc pool engine: ", pool.Engine) + fmt.Println("ddc pool create time: ", pool.CreateTime) + fmt.Println("ddc pool hosts: ", pool.Hosts) + } +} + +// Only DDC +func TestClient_ListVpc(t *testing.T) { + vpc, err := DDCRDS_CLIENT.ListVpc("ddc") + ExpectEqual(t.Errorf, vpc, vpc) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(vpc) +} + +func TestClient_GetDetail(t *testing.T) { + instanceId = "ddc-mqqint6z" + result, err := DDCRDS_CLIENT.GetDetail(instanceId) + ExpectEqual(t.Errorf, err, nil) + fmt.Println("ddc instanceId: ", result.InstanceId) + fmt.Println("ddc instanceName: ", result.InstanceName) + fmt.Println("ddc engine: ", result.Engine) + fmt.Println("ddc engineVersion: ", result.EngineVersion) + fmt.Println("ddc instanceStatus: ", result.InstanceStatus) + fmt.Println("ddc cpuCount: ", result.CpuCount) + fmt.Println("ddc memoryCapacity: ", result.MemoryCapacity) + fmt.Println("ddc volumeCapacity: ", result.VolumeCapacity) + fmt.Println("ddc usedStorage: ", result.UsedStorage) + fmt.Println("ddc paymentTiming: ", result.PaymentTiming) + fmt.Println("ddc instanceType: ", result.InstanceType) + fmt.Println("ddc instanceCreateTime: ", result.InstanceCreateTime) + fmt.Println("ddc instanceExpireTime: ", result.InstanceExpireTime) + fmt.Println("ddc publicAccessStatus: ", result.PublicAccessStatus) + fmt.Println("ddc vpcId: ", result.VpcId) + fmt.Println("ddc Subnets: ", result.Subnets) + fmt.Println("ddc BackupPolicy: ", result.BackupPolicy) + fmt.Println("ddc RoGroupList: ", result.RoGroupList) + fmt.Println("ddc NodeMaster: ", result.NodeMaster) + fmt.Println("master BBC hostname: ", result.NodeMaster.HostName) + fmt.Println("ddc NodeSlave: ", result.NodeSlave) + fmt.Println("slave BBC hostname: ", result.NodeSlave.HostName) + fmt.Println("ddc NodeReadReplica: ", result.NodeReadReplica) + fmt.Println("ddc DeployId: ", result.DeployId) + fmt.Println("ddc SyncMode: ", result.SyncMode) + fmt.Println("ddc Category: ", result.Category) + fmt.Println("ddc ZoneNames: ", result.ZoneNames) + fmt.Println("ddc Endpoint: ", result.Endpoint) + fmt.Println("ddc Endpoint vnetIpBackup: ", result.Endpoint.VnetIpBackup) + fmt.Println("ddc long BBC Id: ", result.LongBBCId) + fmt.Println("ddc topo: ", result.InstanceTopoForReadonly) + // 自动续费规则 + if result.AutoRenewRule != nil { + fmt.Println("ddc renewTime: ", result.AutoRenewRule.RenewTime) + fmt.Println("ddc renewTimeUnit: ", result.AutoRenewRule.RenewTimeUnit) + } +} + +func TestClient_UpdateSecurityIps(t *testing.T) { + err := DDCRDS_CLIENT.UpdateSecurityIps(DDC_INSTANCE_ID, "", &UpdateSecurityIpsArgs{ + SecurityIps: []string{ + "10.10.0.0/16", + }, + }) + ExpectEqual(t.Errorf, nil, err) + + instances := getRdsList(t) + for _, e := range *instances { + if "Available" == e.InstanceStatus { + res, err := DDCRDS_CLIENT.GetSecurityIps(e.InstanceId) + ExpectEqual(t.Errorf, nil, err) + args := &UpdateSecurityIpsArgs{ + SecurityIps: []string{ + "%", + "192.0.0.1", + "192.0.0.2", + }, + } + er := DDCRDS_CLIENT.UpdateSecurityIps(e.InstanceId, res.Etag, args) + ExpectEqual(t.Errorf, nil, er) + } + } +} + +func TestClient_GetBackupList(t *testing.T) { + args := &GetBackupListArgs{ + MaxKeys: 3, + } + list, err := DDCRDS_CLIENT.GetBackupList(DDC_INSTANCE_ID, args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 3, list.MaxKeys) + res, err := json.Marshal(list.Backups) + fmt.Println(string(res)) + + list, err = DDCRDS_CLIENT.GetBackupList(RDS_INSTANCE_ID, args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 3, list.MaxKeys) + res, err = json.Marshal(list.Backups) + fmt.Println(string(res)) +} + +// Only DDC +func TestClient_GetBackupDetail(t *testing.T) { + list, err := DDCRDS_CLIENT.GetBackupDetail(DDC_INSTANCE_ID, "1612625400590890206") + ExpectEqual(t.Errorf, nil, err) + fmt.Println(Json(list.Snapshot)) + + list, err = DDCRDS_CLIENT.GetBackupDetail(RDS_INSTANCE_ID, "snap-rdsmi35jqm07uyg-2021_02_07T17_00_19Z") + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// Only DDC +func TestClient_CreateBackup(t *testing.T) { + err := DDCRDS_CLIENT.CreateBackup(DDC_INSTANCE_ID) + ExpectEqual(t.Errorf, nil, err) + err = DDCRDS_CLIENT.CreateBackup(RDS_INSTANCE_ID) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// Only DDC +func TestClient_ModifyBackupPolicy(t *testing.T) { + err := DDCRDS_CLIENT.ModifyBackupPolicy(DDC_INSTANCE_ID, &BackupPolicy{ + BackupDays: "0,1,2,3,5", + ExpireInDaysInt: 100, + BackupTime: "17:00:00Z", + }) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.ModifyBackupPolicy(RDS_INSTANCE_ID, &BackupPolicy{ + BackupDays: "0,1,2,3,5", + ExpireInDaysInt: 100, + BackupTime: "17:00:00Z", + }) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// ddc 有多可用区 +func TestClient_GetZoneList(t *testing.T) { + list, err := DDCRDS_CLIENT.GetZoneList("ddc") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, list, list) + fmt.Println(Json(list)) + + list, err = DDCRDS_CLIENT.GetZoneList("rds") + ExpectEqual(t.Errorf, nil, err) + fmt.Println(Json(list)) +} + +// rds使用apiZoneNames,ddc使用zoneNames逻辑可用区 +func TestClient_ListSubnets(t *testing.T) { + //args := &ListSubnetsArgs{VpcId: "vpc-fhsajv3w2j7h"} + subnets, err := DDCRDS_CLIENT.ListSubnets(nil, "ddc") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, subnets, subnets) + fmt.Println(Json(subnets)) + + //args = &ListSubnetsArgs{ZoneName: "cn-su-a"} + //subnets, err = DDCRDS_CLIENT.ListSubnets(args, "rds") + //ExpectEqual(t.Errorf, nil, err) + //fmt.Println(Json(subnets)) +} + +// Only DDC +func TestClient_GetBinlogList(t *testing.T) { + // 获取两天前的日志备份 + yesterday := time.Now(). + AddDate(0, 0, -2). + Format("2006-01-02T15:04:05Z") + list, err := DDCRDS_CLIENT.GetBinlogList(DDC_INSTANCE_ID, yesterday) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(Json(list.Binlogs)) + + list, err = DDCRDS_CLIENT.GetBinlogList(RDS_INSTANCE_ID, "") + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// Only DDC +func TestClient_GetBinlogDetail(t *testing.T) { + detail, err := DDCRDS_CLIENT.GetBinlogDetail(DDC_INSTANCE_ID, "1612713949797105170") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, detail.Binlog.BinlogId, "1612713949797105170") + fmt.Println(Json(detail)) + + detail, err = DDCRDS_CLIENT.GetBinlogDetail(RDS_INSTANCE_ID, "1612355516300875570") + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +func TestClient_DeleteDdcInstance(t *testing.T) { + instanceId := "rds-EOWuPqrI,rds-OtTkC1OD,ddc-m1e78f5f" + err := DDCRDS_CLIENT.DeleteRds(instanceId) + ExpectEqual(t.Errorf, nil, err) +} + +// Only DDC +func TestClient_SwitchInstance(t *testing.T) { + instanceId = "ddc-m8xc5hmz" + args := &SwitchArgs{ + IsSwitchNow: false, + } + result, err := client.SwitchInstance(instanceId, args) + if err != nil { + fmt.Printf(" main standby switching of the instance error: %+v\n", err) + return + } + if result != nil { + fmt.Printf(" main standby switching of the instance success, taskId: %v\n", result.Result.TaskID) + } else { + fmt.Printf(" main standby switching of the instance success\n") + } +} + +// Database +func TestClient_CreateDatabase(t *testing.T) { + args := &CreateDatabaseArgs{ + ClientToken: getClientToken(), + DbName: DB_NAME, + CharacterSetName: DB_CHARACTER_SET_NAME, + Remark: DB_REMARK, + } + + err := DDCRDS_CLIENT.CreateDatabase(DDC_INSTANCE_ID, args) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.CreateDatabase(RDS_INSTANCE_ID, args) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +func TestClient_GetDatabase(t *testing.T) { + result, err := DDCRDS_CLIENT.GetDatabase(DDC_INSTANCE_ID, DB_NAME) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Available", result.DbStatus) + + result, err = DDCRDS_CLIENT.GetDatabase(RDS_INSTANCE_ID, DB_NAME) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +func TestClient_ListDatabase(t *testing.T) { + result, err := DDCRDS_CLIENT.ListDatabase(DDC_INSTANCE_ID) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Databases { + if e.DbName == DB_NAME { + ExpectEqual(t.Errorf, "available", e.DbStatus) + } + fmt.Println("ddc dbStatus: ", e.DbStatus) + fmt.Println("ddc remark: ", e.Remark) + fmt.Println("ddc accountPrivileges: ", e.AccountPrivileges) + } + + result, err = DDCRDS_CLIENT.ListDatabase(RDS_INSTANCE_ID) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +func TestClient_GetTableAmount(t *testing.T) { + args := &GetTableAmountArgs{ + InstanceId: instanceId, + DbName: "test1", + Pattern: "0", + } + result, err := DDCRDS_CLIENT.GetTableAmount(args) + if err != nil { + fmt.Printf("get table amount error: %+v\n", err) + return + } + fmt.Printf("get table amount success.\n") + fmt.Println("ddc return amount ", result.ReturnAmount) + fmt.Println("ddc total amount ", result.TotalAmount) + for k, v := range result.Tables { + fmt.Println("ddc table ", k, " size: ", v) + } +} + +func TestClient_GetDatabaseDiskUsage(t *testing.T) { + result, err := DDCRDS_CLIENT.GetDatabaseDiskUsage(instanceId, "") + if err != nil { + fmt.Printf("get database disk usage error: %+v\n", err) + return + } + fmt.Printf("get database disk usage success.\n") + fmt.Println("ddc rest disk size(byte) ", result.RestDisk) + fmt.Println("ddc used disk size(byte) ", result.UsedDisk) + for k, v := range result.Databases { + fmt.Println("ddc table ", k, " size: ", v) + } +} + +func TestClient_GetRecoverableDateTime(t *testing.T) { + result, err := DDCRDS_CLIENT.GetRecoverableDateTime(instanceId) + if err != nil { + fmt.Printf("get recoverable datetimes error: %+v\n", err) + return + } + fmt.Printf("get recoverable datetimes success.\n") + for _, e := range result.RecoverableDateTimes { + fmt.Println("recover startTime: ", e.StartDateTime, " endTime: ", e.EndDateTime) + } +} + +func TestClient_RecoverToSourceInstanceByDatetime(t *testing.T) { + dbName := "test2" + tableName := "app_1" + args := &RecoverInstanceArgs{ + Datetime: "2021-11-03T11:38:04Z", + RecoverData: []RecoverData{ + { + DbName: dbName, + NewDbName: dbName + "_new", + RestoreMode: "database", + }, + { + DbName: dbName, + NewDbName: dbName + "_new", + RestoreMode: "table", + RecoverTables: []RecoverTable{ + { + TableName: tableName, + NewTableName: tableName + "_new", + }, + }, + }, + }, + } + taskResult, err := DDCRDS_CLIENT.RecoverToSourceInstanceByDatetime(instanceId, args) + if err != nil { + fmt.Printf("recover instance database error: %+v\n", err) + return + } + fmt.Printf("recover instance database success. taskId:%s\n", taskResult.TaskID) +} +func TestClient_UpdateDatabaseRemark(t *testing.T) { + args := &UpdateDatabaseRemarkArgs{ + Remark: DB_REMARK + "_update", + } + err := DDCRDS_CLIENT.UpdateDatabaseRemark(DDC_INSTANCE_ID, DB_NAME, args) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.UpdateDatabaseRemark(RDS_INSTANCE_ID, DB_NAME, args) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +func TestClient_DeleteDatabase(t *testing.T) { + err := DDCRDS_CLIENT.DeleteDatabase(DDC_INSTANCE_ID, DB_NAME) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.DeleteDatabase(RDS_INSTANCE_ID, DB_NAME) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// Account +func TestClient_CreateAccount(t *testing.T) { + args := &CreateAccountArgs{ + ClientToken: getClientToken(), + AccountName: ACCOUNT_NAME, + Password: ACCOUNT_PASSWORD, + AccountType: "Common", + Desc: ACCOUNT_REMARK, + DatabasePrivileges: []DatabasePrivilege{ + { + DbName: DB_NAME, + AuthType: "ReadOnly", + }, + }, + } + + err := DDCRDS_CLIENT.CreateAccount(DDC_INSTANCE_ID, args) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.CreateAccount(RDS_INSTANCE_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetAccount(t *testing.T) { + result, err := DDCRDS_CLIENT.GetAccount(DDC_INSTANCE_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Available", result.Status) + + result, err = DDCRDS_CLIENT.GetAccount(RDS_INSTANCE_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(Json(result)) + ExpectEqual(t.Errorf, "Available", result.Status) +} + +func TestClient_ListAccount(t *testing.T) { + result, err := DDCRDS_CLIENT.ListAccount(DDC_INSTANCE_ID) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Accounts { + if e.AccountName == ACCOUNT_NAME { + ExpectEqual(t.Errorf, "Available", e.Status) + } + } + + result, err = DDCRDS_CLIENT.ListAccount(RDS_INSTANCE_ID) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Accounts { + if e.AccountName == ACCOUNT_NAME { + ExpectEqual(t.Errorf, "Available", e.Status) + } + } +} + +// Only DDC +func TestClient_UpdateAccountPassword(t *testing.T) { + args := &UpdateAccountPasswordArgs{ + Password: ACCOUNT_PASSWORD + "_update", + } + err := DDCRDS_CLIENT.UpdateAccountPassword(DDC_INSTANCE_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.UpdateAccountPassword(RDS_INSTANCE_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// Only DDC +func TestClient_UpdateAccountDesc(t *testing.T) { + args := &UpdateAccountDescArgs{ + Desc: ACCOUNT_REMARK + "_update", + } + err := DDCRDS_CLIENT.UpdateAccountDesc(DDC_INSTANCE_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.UpdateAccountDesc(RDS_INSTANCE_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +// Only DDC +func TestClient_UpdateAccountPrivileges(t *testing.T) { + databasePrivileges := []DatabasePrivilege{ + { + DbName: DB_NAME, + AuthType: "ReadWrite", + }, + } + args := &UpdateAccountPrivilegesArgs{ + DatabasePrivileges: databasePrivileges, + } + err := DDCRDS_CLIENT.UpdateAccountPrivileges(DDC_INSTANCE_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.UpdateAccountPrivileges(RDS_INSTANCE_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, RDSNotSupportError(), err) +} + +func TestClient_DeleteAccount(t *testing.T) { + err := DDCRDS_CLIENT.DeleteAccount(DDC_INSTANCE_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) + + err = DDCRDS_CLIENT.DeleteAccount(RDS_INSTANCE_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) +} + +// util +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateRds(t *testing.T) { + args := &CreateRdsArgs{ + PurchaseCount: 1, + InstanceName: "mysql57fromgo", + //SourceInstanceId: "ddc-mmqptugx", + Engine: "mysql", + EngineVersion: "5.7", + CpuCount: 1, + MemoryCapacity: 1, + VolumeCapacity: 50, + Billing: Billing{ + PaymentTiming: "Postpaid", + Reservation: Reservation{ReservationLength: 1, ReservationTimeUnit: "Month"}, + }, + VpcId: "vpc-fhsajv3w2j7h", + ZoneNames: []string{ + "cn-bj-a", + }, + Subnets: []SubnetMap{ + { + ZoneName: "cn-bj-a", + SubnetId: "sbn-7zdak3vr8jv2", + }, + }, + //DeployId: "86be443c-a40d-be6a-58d5-e3aedc966cc1", + PoolId: "xdb_005a2d79-a4f4-4bfb-8284-0ffe9ddaa307_pool", + Category: STANDARD, + SyncMode: "Semi_sync", + } + subnetArgs := &ListSubnetsArgs{VpcId: args.VpcId} + resp, err := DDCRDS_CLIENT.ListSubnets(subnetArgs, "ddc") + ExpectEqual(t.Errorf, nil, err) + if len(resp.Subnets) > 0 { + subnet := resp.Subnets[0] + fmt.Printf("ddc use subnet: %s\n", Json(subnet)) + // DDC使用ShortId + args.Subnets[0].SubnetId = subnet.ShortId + } + ddc, err := DDCRDS_CLIENT.CreateRds(args, "ddc") + ExpectEqual(t.Errorf, nil, err) + fmt.Println(Json(ddc)) + + // 修改VPCId和子网Id + //subnetArgs = &ListSubnetsArgs{ZoneName: "cn-su-c"} + //resp, err = DDCRDS_CLIENT.ListSubnets(subnetArgs, "rds") + //ExpectEqual(t.Errorf, nil, err) + //if len(resp.Subnets) > 0 { + // subnet := resp.Subnets[0] + // fmt.Printf("rds use subnet: %s\n", Json(subnet)) + // args.VpcId = subnet.VpcId + // args.Subnets[0].SubnetId = subnet.ShortId + //} + //rds, err := DDCRDS_CLIENT.CreateRds(args, "rds") + //ExpectEqual(t.Errorf, nil, err) + //fmt.Println(Json(rds)) +} + +func TestClient_CreateReadReplica(t *testing.T) { + client := DDCRDS_CLIENT + instanceId := "ddc-m1b5gjr5" + args := &CreateReadReplicaArgs{ + ClientToken: "320cfd8dceaf98529bd9f7c1d43a52c5", + // 计费相关参数,DDC 只读实例只支持预付费,RDS 只读实例只支持后付费Postpaid,必选 + Billing: Billing{ + PaymentTiming: "Prepaid", + Reservation: Reservation{ReservationLength: 5, ReservationTimeUnit: "Month"}, + }, + PurchaseCount: 3, + //主实例ID,必选 + SourceInstanceId: instanceId, + InstanceName: "go_tester_read", + // CPU核数,必选 + CpuCount: 2, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 8, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 20, + //批量创建云数据库 ddc 只读实例个数, 目前只支持一次创建一个,可选 + //PurchaseCount: 2, + //实例名称,允许小写字母、数字,长度限制为1~32,默认命名规则:{engine} + {engineVersion},可选 + //指定zone信息,默认为空,由系统自动选择,可选 + //zoneName命名规范是小写的“国家-region-可用区序列",例如北京可用区A为"cn-bj-a"。 + //ZoneNames: []string{"cn-su-c"}, + //与主实例 vpcId 相同,可选 + //VpcId: "vpc-IyrqYIQ7", + //是否进行直接支付,默认false,设置为直接支付的变配订单会直接扣款,不需要再走支付逻辑,可选 + IsDirectPay: false, + //vpc内,每个可用区的subnetId;如果不是默认vpc则必须指定 subnetId,可选 + //Subnets: []SubnetMap{ + // { + // ZoneName: "cn-su-c", + // SubnetId: "sbn-8v3p33vhyhq5", + // }, + //}, + // 资源池id 必选与主实例保持一致 + //PoolId:"xdb_5cf97afb-ee06-4b80-9146-4a840e5d0288_pool", + // RO组ID。(创建只读实例时) 可选 + // 如果不传,默认会创建一个RO组,并将该只读加入RO组中 + RoGroupId: "yyzzcc2", + // RO组是否启用延迟剔除,默认不启动。(创建只读实例时)可选 + EnableDelayOff: "0", + // 延迟阈值。(创建只读实例时)可选 + DelayThreshold: "1", + // RO组最少保留实例数目。默认为1. (创建只读实例时)可选 + LeastInstanceAmount: "1", + // 只读实例在RO组中的读流量权重。默认为1(创建只读实例时)可选 + RoGroupWeight: "1", + } + result, err := client.CreateReadReplica(args) + if err != nil { + fmt.Printf("create ddc readReplica error: %+v\n", err) + return + } + + for _, e := range result.InstanceIds { + fmt.Println("create ddc readReplica success, instanceId: ", e) + } +} + +func TestClient_ListRds(t *testing.T) { + args := &ListRdsArgs{ + // 批量获取列表的查询的起始位置,实例列表中Marker需要指定实例Id,可选 + Marker: "-1", + // 指定每页包含的最大数量(主实例),最大数量不超过1000,缺省值为1000,可选 + MaxKeys: 10, + } + resp, err := DDCRDS_CLIENT.ListRds(args) + + if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return + } + + // 返回标记查询的起始位置 + fmt.Println("list marker: ", resp.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("list isTruncated: ", resp.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("list nextMarker: ", resp.NextMarker) + // 每页包含的最大数量 + fmt.Println("list maxKeys: ", resp.MaxKeys) + + // 获取instance的列表信息 + for _, e := range resp.Instances { + fmt.Println("=====================================>") + fmt.Println("instance productType: ", e.ProductType()) + fmt.Println("instanceId: ", e.InstanceId) + fmt.Println("instanceName: ", e.InstanceName) + fmt.Println("engine: ", e.Engine) + fmt.Println("engineVersion: ", e.EngineVersion) + fmt.Println("instanceStatus: ", e.InstanceStatus) + fmt.Println("cpuCount: ", e.CpuCount) + fmt.Println("memoryCapacity: ", e.MemoryCapacity) + fmt.Println("volumeCapacity: ", e.VolumeCapacity) + fmt.Println("usedStorage: ", e.UsedStorage) + fmt.Println("paymentTiming: ", e.PaymentTiming) + fmt.Println("instanceType: ", e.InstanceType) + fmt.Println("instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("publiclyAccessible: ", e.PubliclyAccessible) + fmt.Println("backup expireInDays: ", e.BackupPolicy.ExpireInDaysInt) + fmt.Println("vpcId: ", e.VpcId) + fmt.Println("endpoint: ", e.Endpoint) + fmt.Println("vnetIp: ", e.Endpoint.VnetIp) + fmt.Println("vnetIpBackup: ", e.Endpoint.VnetIpBackup) + fmt.Println("long BBC Id: ", e.LongBBCId) + fmt.Println("bbc hostname: ", e.HostName) + if e.AutoRenewRule != nil { + fmt.Println("renewTime: ", e.AutoRenewRule.RenewTime) + fmt.Println("renewTimeUnit: ", e.AutoRenewRule.RenewTimeUnit) + } + } +} + +func TestClient_ListPage(t *testing.T) { + args := &ListPageArgs{ + // 页码 + PageNo: 1, + // 页大小 + PageSize: 10, + // 筛选条件 + // 筛选字段类型,各筛选条件只能单独筛选,当取值为type、status、dbType、zone时可在集合中增加筛选项 + // all:匹配全部 + // instanceName:匹配实例名称 + // instanceId:匹配实例id; + // vnetIpBackup:备库ip; + // vnetIp:主库ip + //Filters: []Filter{ + // {KeywordType: "all", Keyword: "mysql"}, + // {KeywordType: "zone", Keyword: "cn-bj-a"}, + //}, + } + resp, err := DDCRDS_CLIENT.ListPage(args) + + if err != nil { + fmt.Printf("get instance error: %+v\n", err) + return + } + + // 返回分页页码 + fmt.Println("list pageNo: ", resp.Page.PageNo) + // 返回页大小 + fmt.Println("list pageSize: ", resp.Page.PageSize) + // 返回总数量 + fmt.Println("list totalCount: ", resp.Page.TotalCount) + + // 获取instance的列表信息 + for _, e := range resp.Page.Result { + fmt.Println("=====================================>") + fmt.Println("instanceId: ", e.InstanceId) + fmt.Println("instanceName: ", e.InstanceName) + fmt.Println("engine: ", e.Engine) + fmt.Println("engineVersion: ", e.EngineVersion) + fmt.Println("instanceStatus: ", e.InstanceStatus) + fmt.Println("cpuCount: ", e.CpuCount) + fmt.Println("memoryCapacity: ", e.MemoryCapacity) + fmt.Println("volumeCapacity: ", e.VolumeCapacity) + fmt.Println("usedStorage: ", e.UsedStorage) + fmt.Println("paymentTiming: ", e.PaymentTiming) + fmt.Println("instanceType: ", e.InstanceType) + fmt.Println("instanceCreateTime: ", e.InstanceCreateTime) + fmt.Println("instanceExpireTime: ", e.InstanceExpireTime) + fmt.Println("publiclyAccessible: ", e.PubliclyAccessible) + fmt.Println("backup expireInDays: ", e.BackupPolicy.ExpireInDaysInt) + fmt.Println("vpcId: ", e.VpcId) + fmt.Println("endpoint: ", e.Endpoint) + fmt.Println("vnetIp: ", e.Endpoint.VnetIp) + fmt.Println("vnetIpBackup: ", e.Endpoint.VnetIpBackup) + fmt.Println("long BBC Id: ", e.LongBBCId) + fmt.Println("bbc hostname: ", e.HostName) + if e.AutoRenewRule != nil { + fmt.Println("renewTime: ", e.AutoRenewRule.RenewTime) + fmt.Println("renewTimeUnit: ", e.AutoRenewRule.RenewTimeUnit) + } + } +} + +func TestClient_UpdateInstanceName(t *testing.T) { + args := &UpdateInstanceNameArgs{ + // DDC实例名称,允许小写字母、数字,中文,长度限制为1~64 + InstanceName: "备份恢复测试-勿删-02", + } + err := DDCRDS_CLIENT.UpdateInstanceName(DDC_INSTANCE_ID, args) + if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return + } + fmt.Printf("update instance name success\n") + + args = &UpdateInstanceNameArgs{ + // DDC实例名称,允许小写字母、数字,中文,长度限制为1~64 + InstanceName: "mysql56_rds", + } + err = DDCRDS_CLIENT.UpdateInstanceName(RDS_INSTANCE_ID, args) + if err != nil { + fmt.Printf("update instance name error: %+v\n", err) + return + } + fmt.Printf("update instance name success\n") +} + +// 以下操作仅支持RDS +// Only RDS +func TestClient_CreateRdsProxy(t *testing.T) { + args := &CreateRdsProxyArgs{ + SourceInstanceId: RDS_INSTANCE_ID, + NodeAmount: 2, + Billing: Billing{ + PaymentTiming: "Postpaid", + }, + ClientToken: getClientToken(), + } + assertAvailable(RDS_INSTANCE_ID, t) + _, err := DDCRDS_CLIENT.CreateRdsProxy(args) + ExpectEqual(t.Errorf, nil, err) +} + +// Only RDS +func TestClient_ResizeRds(t *testing.T) { + args := &ResizeRdsArgs{ + CpuCount: 1, + MemoryCapacity: 2, + VolumeCapacity: 10, + IsResizeNow: true, + IsDirectPay: true, + ClientToken: getClientToken(), + } + orderIdResponse, err := DDCRDS_CLIENT.ResizeRds(DDC_INSTANCE_ID, args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println("resize ddc success, orderId: ", orderIdResponse.OrderId) + time.Sleep(30 * time.Second) + assertAvailable(DDC_INSTANCE_ID, t) +} + +func TestClient_RebootInstance(t *testing.T) { + // client := DDCRDS_CLIENT + // err := client.RebootInstance("rds-deaaDuV9") + // if err != nil { + // fmt.Printf("reboot error: %+v\n", err) + // return + // } + + // 延迟重启(仅支持DDC) + args := &RebootArgs{ + IsRebootNow: false, + } + result, err := client.RebootInstanceWithArgs(instanceId, args) + if err != nil { + fmt.Printf("reboot ddc error: %+v\n", err) + return + } + if result != nil { + fmt.Printf("reboot ddc success, taskId: %+v\n", result.TaskID) + } +} + +func TestClient_ModifySyncMode(t *testing.T) { + assertAvailable(DDC_INSTANCE_ID, t) + listRdsArgs := &ListRdsArgs{} + result, err := DDCRDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if "Available" == e.InstanceStatus { + args := &ModifySyncModeArgs{ + SyncMode: "Semi_sync", // Semi_sync + } + err := DDCRDS_CLIENT.ModifySyncMode(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +// Only RDS +func TestClient_ModifyEndpoint(t *testing.T) { + assertAvailable(RDS_INSTANCE_ID, t) + listRdsArgs := &ListRdsArgs{} + result, err := DDCRDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if "Available" == e.InstanceStatus { + args := &ModifyEndpointArgs{ + Address: "gosdk", + } + err := DDCRDS_CLIENT.ModifyEndpoint(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +// Only RDS +func TestClient_ModifyPublicAccess(t *testing.T) { + assertAvailable(RDS_INSTANCE_ID, t) + listRdsArgs := &ListRdsArgs{} + result, err := DDCRDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if "Available" == e.InstanceStatus { + args := &ModifyPublicAccessArgs{ + PublicAccess: true, + } + err := DDCRDS_CLIENT.ModifyPublicAccess(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_AutoRenew(t *testing.T) { + args := &AutoRenewArgs{ + // 自动续费时长(续费单位为year 不大于3,续费单位为month 不大于9)必选 + AutoRenewTime: 1, + // 自动续费单位("year";"month")必选 + AutoRenewTimeUnit: "month", + // 实例id集合 必选 + InstanceIds: []string{ + "rds-OtTkC1OD", + "rds-rbmh6gJl", + }, + } + err := client.AutoRenew(args, "rds") + if err != nil { + fmt.Printf("create auto renew error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetMaintainTime(t *testing.T) { + maintainTime, err := client.GetMaintainTime(instanceId) + if err != nil { + fmt.Printf("get maintain time error: %+v\n", err) + return + } + fmt.Println("maintainTime duration", maintainTime.Duration) + fmt.Println("maintainTime period", maintainTime.Period) + fmt.Println("maintainTime startTime", maintainTime.StartTime) +} + +func TestClient_UpdateMaintainTime(t *testing.T) { + args := &MaintainTime{ + // 时长间隔 + Duration: 2, + // 1-7分别代表周一到周日 + Period: "1,2,3,4,5,0", + // 所有涉及的时间皆为北京时间24小时制 + StartTime: "14:07", + } + err := client.UpdateMaintainTime(instanceId, args) + if err != nil { + fmt.Printf("update maintain time error: %+v\n", err) + } +} +func TestClient_ListRecycleInstances(t *testing.T) { + marker := &Marker{MaxKeys: 10} + instances, err := client.ListRecycleInstances(marker, "ddc") + if err != nil { + fmt.Printf("list recycler instances error: %+v\n", err) + return + } + fmt.Println(Json(instances)) + for _, instance := range instances.Result { + fmt.Println("+-------------------------------------------+") + fmt.Println("instanceId: ", instance.InstanceId) + fmt.Println("instanceName: ", instance.InstanceName) + fmt.Println("engine: ", instance.Engine) + fmt.Println("engineVersion: ", instance.EngineVersion) + fmt.Println("instanceStatus: ", instance.InstanceStatus) + fmt.Println("cpuCount: ", instance.CpuCount) + fmt.Println("memoryCapacity: ", instance.MemoryCapacity) + fmt.Println("volumeCapacity: ", instance.VolumeCapacity) + fmt.Println("usedStorage: ", instance.UsedStorage) + fmt.Println("instanceType: ", instance.InstanceType) + fmt.Println("instanceCreateTime: ", instance.InstanceCreateTime) + fmt.Println("instanceExpireTime: ", instance.InstanceExpireTime) + fmt.Println("publicAccessStatus: ", instance.PublicAccessStatus) + fmt.Println("vpcId: ", instance.VpcId) + } +} + +func TestClient_RecoverRecyclerInstances(t *testing.T) { + instanceIds := []string{ + "ddc-mv8zcy6u", + "ddc-mof1m3hb", + } + orderIdResponse, err := client.RecoverRecyclerInstances(instanceIds) + if err != nil { + fmt.Printf("recover recycler instances error: %+v\n", err) + return + } + fmt.Println("recover recycler instances success, orderId: ", orderIdResponse.OrderId) +} + +func TestClient_DeleteRecyclerInstances(t *testing.T) { + instanceIds := []string{ + "ddc-mof1m3hb", + "ddc-moxgq5dm", + } + err := client.DeleteRecyclerInstances(instanceIds) + if err != nil { + fmt.Printf("delete recycler instances error: %+v\n", err) + return + } + fmt.Println("delete recycler instances success.") +} + +func TestClient_ListSecurityGroupByVpcId(t *testing.T) { + vpcId := "vpc-j1vaxw1cx2mw" + securityGroups, err := client.ListSecurityGroupByVpcId(vpcId) + if err != nil { + fmt.Printf("list security group by vpcId error: %+v\n", err) + return + } + for _, group := range *securityGroups { + fmt.Println("+-------------------------------------------+") + fmt.Println("id: ", group.SecurityGroupID) + fmt.Println("name: ", group.Name) + fmt.Println("description: ", group.Description) + fmt.Println("associateNum: ", group.AssociateNum) + fmt.Println("createdTime: ", group.CreatedTime) + fmt.Println("version: ", group.Version) + fmt.Println("defaultSecurityGroup: ", group.DefaultSecurityGroup) + fmt.Println("vpc name: ", group.VpcName) + fmt.Println("vpc id: ", group.VpcShortID) + fmt.Println("tenantId: ", group.TenantID) + } + fmt.Println("list security group by vpcId success.") +} + +func TestClient_ListSecurityGroupByInstanceId(t *testing.T) { + instanceId := "ddc-m1h4mma5" + result, err := client.ListSecurityGroupByInstanceId(instanceId) + if err != nil { + fmt.Printf("list security group by instanceId error: %+v\n", err) + return + } + for _, group := range result.Groups { + fmt.Println("+-------------------------------------------+") + fmt.Println("securityGroupId: ", group.SecurityGroupID) + fmt.Println("securityGroupName: ", group.SecurityGroupName) + fmt.Println("securityGroupRemark: ", group.SecurityGroupRemark) + fmt.Println("projectId: ", group.ProjectID) + fmt.Println("vpcId: ", group.VpcID) + fmt.Println("vpcName: ", group.VpcName) + fmt.Println("inbound: ", group.Inbound) + fmt.Println("outbound: ", group.Outbound) + } + fmt.Println("list security group by instanceId success.") +} + +func TestClient_BindSecurityGroups(t *testing.T) { + instanceIds := []string{ + "ddc-mf4c901b", + } + securityGroupIds := []string{ + "g-mi74p78rtq07", + } + args := &SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, + } + + err := client.BindSecurityGroups(args) + if err != nil { + fmt.Printf("bind security groups to instances error: %+v\n", err) + return + } + fmt.Println("bind security groups to instances success.") +} + +func TestClient_UnBindSecurityGroups(t *testing.T) { + instanceIds := []string{ + "ddc-mjafcdu0", + } + securityGroupIds := []string{ + "g-iutg5rtcydsk", + } + args := &SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, + } + + err := client.UnBindSecurityGroups(args) + if err != nil { + fmt.Printf("unbind security groups to instances error: %+v\n", err) + return + } + fmt.Println("unbind security groups to instances success.") +} + +func TestClient_ReplaceSecurityGroups(t *testing.T) { + instanceIds := []string{ + "ddc-mjafcdu0", + } + securityGroupIds := []string{ + "g-iutg5rtcydsk", + } + args := &SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, + } + + err := client.ReplaceSecurityGroups(args) + if err != nil { + fmt.Printf("replace security groups to instances error: %+v\n", err) + return + } + fmt.Println("replace security groups to instances success.") +} + +func TestClient_ListLogByInstanceId(t *testing.T) { + // 两天前 + date := time.Now(). + AddDate(0, 0, -2). + Format("2006-01-02") + fmt.Println(date) + args := &ListLogArgs{ + LogType: "error", + Datetime: date, + } + logs, err := client.ListLogByInstanceId(instanceId, args) + if err != nil { + fmt.Printf("list logs of instance error: %+v\n", err) + return + } + fmt.Println("list logs of instance success.") + for _, log := range *logs { + fmt.Println("+-------------------------------------------+") + fmt.Println("id: ", log.LogID) + fmt.Println("size: ", log.LogSizeInBytes) + fmt.Println("start time: ", log.LogStartTime) + fmt.Println("end time: ", log.LogEndTime) + } +} + +func TestClient_GetLogById(t *testing.T) { + args := &GetLogArgs{ + ValidSeconds: 20, + } + logId := "errlog.202103091300" + log, err := client.GetLogById(instanceId, logId, args) + if err != nil { + fmt.Printf("get log detail of instance error: %+v\n", err) + return + } + fmt.Println("list logs of instances success.") + fmt.Println("+-------------------------------------------+") + fmt.Println("id: ", log.LogID) + fmt.Println("size: ", log.LogSizeInBytes) + fmt.Println("start time: ", log.LogStartTime) + fmt.Println("end time: ", log.LogEndTime) + fmt.Println("download url: ", log.DownloadURL) + fmt.Println("download url expires: ", log.DownloadExpires) +} + +func TestClient_LazyDropCreateHardLink(t *testing.T) { + dbName := "test2" + tableName := "app_3" + err := client.LazyDropCreateHardLink(instanceId, dbName, tableName) + if err != nil { + fmt.Printf("[lazy drop] create hard link error: %+v\n", err) + return + } + fmt.Println("[lazy drop] create hard link success.") +} + +func TestClient_LazyDropDeleteHardLink(t *testing.T) { + dbName := "test2" + tableName := "app_1" + result, err := client.LazyDropDeleteHardLink(instanceId, dbName, tableName) + if err != nil { + fmt.Printf("[lazy drop] delete hard link error: %+v\n", err) + return + } + fmt.Println("[lazy drop] delete hard link success.taskId:", result.TaskID) +} + +func TestClient_GetDisk(t *testing.T) { + disk, err := client.GetDisk(instanceId) + if err != nil { + fmt.Printf("get disk of instance error: %+v\n", err) + return + } + fmt.Println("get disk of instance success.") + for _, diskItem := range disk.Response.Items { + fmt.Println("instance id: ", diskItem.InstanceID) + fmt.Println("instance role: ", diskItem.InstanceRole) + fmt.Println("disk disk partition: ", diskItem.DiskPartition) + fmt.Println("disk totle size in bytes: ", diskItem.TotalSize) + fmt.Println("disk used size in bytes: ", diskItem.UsedSize) + fmt.Println("disk report time: ", diskItem.ReportTime) + } +} + +func TestClient_GetMachineInfo(t *testing.T) { + machine, err := client.GetMachineInfo(instanceId) + if err != nil { + fmt.Printf("get machine info error: %+v\n", err) + return + } + fmt.Println("get machine info success.") + for _, machine := range machine.Response.Items { + fmt.Println("instance id: ", machine.InstanceID) + fmt.Println("instance role: ", machine.Role) + fmt.Println("cpu(core): ", machine.CPUInCore) + fmt.Println("cpu(core) free: ", machine.FreeCPUInCore) + fmt.Println("memory(MB): ", machine.MemSizeInMB) + fmt.Println("memory(MB) free: ", machine.FreeMemSizeInMB) + fmt.Println("disk info: ", machine.SizeInGB) + fmt.Println("----------------------") + } +} + +func TestClient_GetResidual(t *testing.T) { + residual, err := client.GetResidual(POOL) + if err != nil { + fmt.Printf("get residual of pool error: %+v\n", err) + return + } + fmt.Println("get residual of pool success.") + for zoneName, residualByZone := range residual.Residual { + fmt.Println("zone name: ", zoneName) + fmt.Printf("Single residual: disk %v GB, memory %v GB, cpu cores %d\n", + residualByZone.Single.DiskInGb, residualByZone.Single.MemoryInGb, residualByZone.Single.CPUInCore) + fmt.Printf("Slave residual: disk %v GB, memory %v GB, cpu cores %d\n", + residualByZone.Slave.DiskInGb, residualByZone.Slave.MemoryInGb, residualByZone.Slave.CPUInCore) + fmt.Printf("HA residual: disk %v GB, memory %v GB, cpu cores %d\n", + residualByZone.HA.DiskInGb, residualByZone.HA.MemoryInGb, residualByZone.HA.CPUInCore) + } +} + +func TestClient_GetFlavorCapacity(t *testing.T) { + args := &GetFlavorCapacityArgs{ + CpuInCore: 2, + MemoryInGb: 4, + DiskInGb: 50, + Affinity: 2, + } + + args = NewDefaultGetFlavorCapacityArgs(2, 4, 50) + capacityResult, err := client.GetFlavorCapacity(POOL, args) + if err != nil { + fmt.Printf("get flavor capacity of pool error: %+v\n", err) + return + } + fmt.Println("get flavor capacity of pool success.") + for zoneName, residualByZone := range capacityResult.Capacity { + fmt.Println("zone name: ", zoneName) + fmt.Printf("HA capacity: %d\n", residualByZone.HA) + fmt.Printf("Single capacity: %d\n", residualByZone.Single) + fmt.Printf("Slave capacity: %d\n", residualByZone.Slave) + } +} + +func TestClient_KillSession(t *testing.T) { + args := &KillSessionArgs{ + Role: "master", + SessionIds: []int{8661, 8662}, + } + result, err := client.KillSession(instanceId, args) + if err != nil { + fmt.Printf("start kill session task error: %+v\n", err) + return + } + fmt.Println("start kill session task success. TaskID:", result.TaskID) +} + +func TestClient_GetKillSessionTaskResult(t *testing.T) { + taskId := 285647 + result, err := client.GetKillSessionTask(instanceId, taskId) + if err != nil { + fmt.Printf("get kill session task error: %+v\n", err) + return + } + fmt.Println("get kill session task success.") + for _, task := range result.Tasks { + fmt.Println("sessionId: ", task.SessionID) + fmt.Println("task status: ", task.Status) + } +} + +func TestClient_GetMaintainTaskList(t *testing.T) { + args := &GetMaintainTaskListArgs{ + Marker: Marker{ + MaxKeys: 10, + }, + // 任务起始时间 必选 + StartTime: "2021-08-10 00:00:00", + } + result, err := client.GetMaintainTaskList(args) + if err != nil { + fmt.Printf("get tasks error: %+v\n", err) + return + } + fmt.Println("get tasks success.") + // 返回标记查询的起始位置 + fmt.Println("list marker: ", result.Marker) + // true表示后面还有数据,false表示已经是最后一页 + fmt.Println("list isTruncated: ", result.IsTruncated) + // 获取下一页所需要传递的marker值。当isTruncated为false时,该域不出现 + fmt.Println("list nextMarker: ", result.NextMarker) + // 每页包含的最大数量 + fmt.Println("list maxKeys: ", result.MaxKeys) + for _, task := range result.Result { + fmt.Println("task id: ", task.TaskID) + fmt.Println("task name: ", task.TaskName) + fmt.Println("task status: ", task.TaskStatus) + fmt.Println("instance id: ", task.InstanceID) + fmt.Println("instance name: ", task.InstanceName) + fmt.Println("instance region: ", task.Region) + fmt.Println("start time: ", task.StartTime) + fmt.Println("end time: ", task.EndTime) + fmt.Println("--------------------------") + } +} + +func TestClient_GetMaintainTaskDetail(t *testing.T) { + result, err := client.GetMaintainTaskDetail(TASK_ID) + if err != nil { + fmt.Printf("get task detail error: %+v\n", err) + return + } + fmt.Println("get task detail success.") + for _, task := range result.Tasks { + fmt.Println("task id: ", task.TaskID) + fmt.Println("task name: ", task.TaskName) + fmt.Println("instance instanceId: ", task.InstanceID) + fmt.Println("instance instanceName: ", task.InstanceName) + fmt.Println("instance instanceName: ", task.AppID) + fmt.Println("instance task type: ", task.TaskType) + fmt.Println("task status: ", task.TaskStatus) + fmt.Println("instance create time: ", task.CreateTime) + fmt.Println("instance create time: ", task.TaskSpecialAction) + fmt.Println("instance create time: ", task.TaskSpecialActionTime) + fmt.Println("--------------------------") + } +} + +func TestClient_ExecuteMaintainTaskImmediately(t *testing.T) { + taskId := "880337" + err := client.ExecuteMaintainTaskImmediately(taskId) + if err != nil { + fmt.Printf("execute task invoke error: %+v\n", err) + return + } + fmt.Println("execute task invoke success.") +} + +func TestClient_CancelMaintainTask(t *testing.T) { + taskId := "880337" + err := client.CancelMaintainTask(taskId) + if err != nil { + fmt.Printf("cancel task invoke error: %+v\n", err) + return + } + fmt.Println("cancel task invoke success.") +} + +func TestClient_GetAccessLog(t *testing.T) { + date := "20210810" + downloadInfo, err := client.GetAccessLog(date) + if err != nil { + fmt.Printf("get access logs error: %+v\n", err) + return + } + fmt.Println("get access logs success.") + fmt.Println("mysql access logs link: ", downloadInfo.Downloadurl.Mysql) + fmt.Println("bbc access logs link: ", downloadInfo.Downloadurl.Bbc) + fmt.Println("bos access logs link: ", downloadInfo.Downloadurl.Bos) +} + +func TestClient_GetErrorLogs(t *testing.T) { + args := &GetErrorLogsArgs{ + InstanceId: "ddc-mp8lme9w", + StartTime: "2021-08-16T02:28:51Z", + EndTime: "2021-08-17T02:28:51Z", + PageNo: 1, + PageSize: 10, + Role: "master", + KeyWord: "Aborted", + } + errorLogsResponse, err := client.GetErrorLogs(args) + if err != nil { + fmt.Printf("get error logs error: %+v\n", err) + return + } + fmt.Println("get error logs success.") + fmt.Println("error logs count: ", errorLogsResponse.Count) + for _, errorLog := range errorLogsResponse.ErrorLogs { + fmt.Println("=================================================") + fmt.Println("error log instanceId: ", errorLog.InstanceId) + fmt.Println("error log executeTime: ", errorLog.ExecuteTime) + fmt.Println("error log logLevel: ", errorLog.LogLevel) + fmt.Println("error log logText: ", errorLog.LogText) + } +} + +func TestClient_GetSlowLogs(t *testing.T) { + args := &GetSlowLogsArgs{ + InstanceId: "ddc-mp8lme9w", + StartTime: "2021-08-16T02:28:51Z", + EndTime: "2021-08-17T02:28:51Z", + PageNo: 1, + PageSize: 10, + Role: "master", + DbName: []string{"baidu_dba"}, + UserName: []string{"_root"}, + HostIp: []string{"localhost"}, + Sql: "update heartbeat set id=?, value=?", + } + slowLogsResponse, err := client.GetSlowLogs(args) + if err != nil { + fmt.Printf("get slow logs error: %+v\n", err) + return + } + fmt.Println("get slow logs success.") + fmt.Println("slow logs count: ", slowLogsResponse.Count) + for _, slowLog := range slowLogsResponse.SlowLogs { + fmt.Println("=================================================") + fmt.Println("slow log instanceId: ", slowLog.InstanceId) + fmt.Println("slow log userName: ", slowLog.UserName) + fmt.Println("slow log dbName: ", slowLog.DbName) + fmt.Println("slow log hostIp: ", slowLog.HostIp) + fmt.Println("slow log queryTime: ", slowLog.QueryTime) + fmt.Println("slow log lockTime: ", slowLog.LockTime) + fmt.Println("slow log rowsExamined: ", slowLog.RowsExamined) + fmt.Println("slow log rowsSent: ", slowLog.RowsSent) + fmt.Println("slow log sql: ", slowLog.Sql) + fmt.Println("slow log executeTime: ", slowLog.ExecuteTime) + } +} + +func TestClient_GetInstanceBackupStatus(t *testing.T) { + instanceId = "ddc-mvxhc1fq" + backupStatusResult, err := client.GetInstanceBackupStatus(instanceId) + if err != nil { + fmt.Printf("get backup status error: %+v\n", err) + return + } + fmt.Println("get backup status success.") + fmt.Println("instance is backuping: ", backupStatusResult.IsBackuping) + if backupStatusResult.IsBackuping { + fmt.Println("instance backup start time: ", backupStatusResult.SnapshotStartTime) + } +} + +func TestClient_InstanceVersionRollBack(t *testing.T) { + instanceId = "ddc-mvxhc1fq" + args := &InstanceVersionRollBackArg{ + // 是否维护时间执行 + WaitSwitch: true, + } + result, err := client.InstanceVersionRollBack(instanceId, args) + if err != nil { + fmt.Printf("rollback instance version faild: %+v\n", err) + return + } + fmt.Printf("rollback instance version success. taskId:%s\n", result.TaskID) +} + +func TestClient_InstanceVersionUpgrade(t *testing.T) { + instanceId = "ddc-mvxhc1fq" + args := &InstanceVersionUpgradeArg{ + // 是否立即执行 + IsUpgradeNow: true, + } + result, err := client.InstanceVersionUpgrade(instanceId, args) + if err != nil { + fmt.Printf("upgrade instance version faild: %+v\n", err) + return + } + fmt.Printf("upgrade instance version success. taskId:%s\n", result.TaskID) +} + +func TestClient_GetInstanceSyncDelay(t *testing.T) { + instanceId = "ddc-mvxhc1fq" + result, err := client.GetInstanceSyncDelay(instanceId) + if err != nil { + fmt.Printf("get readonly instance syncDelay and syncStatus faild: %+v\n", err) + return + } + fmt.Println("get readonly instance syncDelay and syncStatus success.") + if result.Success { + fmt.Println("instance is SyncDelay: ", result.Result.SyncDelay) + fmt.Println("instance is SyncStatus: ", result.Result.SyncStatus) + } +} + +func TestClient_InstanceSyncDelayReplication(t *testing.T) { + instanceId = "ddc-mvxhc1fq" + args := &InstanceSyncDelayReplicationArg{ + // 开启 + Action: "start", + } + result, err := client.InstanceSyncDelayReplication(instanceId, args) + if err != nil { + fmt.Printf("instance syncDelay replication faild: %+v\n", err) + return + } + fmt.Printf("instance syncDelay replication success. success:%+v\n", result.Success) +} + +func TestClient_BinlogAccessDetail(t *testing.T) { + args := &AccessDetailArgs{ + StartDateTime: "2023-02-02T01:00:00Z", + EndDateTime: "2023-02-02T10:00:00Z", + Marker: "0", + MaxKeys: 100, + } + result, err := client.BinlogAccessDetail(args) + if err != nil { + fmt.Printf("get binlog access detail error: %+v\n", err) + return + } + fmt.Printf("get binlog access detail success\n") + fmt.Println("result: ", result) +} + +func TestClient_SnapshotAccessDetail(t *testing.T) { + args := &AccessDetailArgs{ + StartDateTime: "2023-02-02T01:00:00Z", + EndDateTime: "2023-02-02T10:00:00Z", + Marker: "0", + MaxKeys: 100, + } + result, err := client.SnapshotAccessDetail(args) + if err != nil { + fmt.Printf("get snapshot access detail error: %+v\n", err) + return + } + fmt.Printf("get snapshot access detail success\n %+v", result) +} diff --git a/bce-sdk-go/services/ddc/v2/ddc.go b/bce-sdk-go/services/ddc/v2/ddc.go new file mode 100644 index 0000000..c3acdff --- /dev/null +++ b/bce-sdk-go/services/ddc/v2/ddc.go @@ -0,0 +1,2524 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// ddc.go - the ddc APIs definition supported by the DDC service +package ddcrds + +import ( + "encoding/json" + "errors" + "fmt" + "strconv" + "strings" + "time" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + KEY_CLIENT_TOKEN = "clientToken" + KEY_MARKER = "marker" + KEY_MAX_KEYS = "maxKeys" + COMMA = "," +) + +// Convert marker to request params +func getMarkerParams(marker *Marker) map[string]string { + if marker == nil { + marker = &Marker{Marker: "-1"} + } + params := make(map[string]string, 2) + params[KEY_MARKER] = marker.Marker + if marker.MaxKeys > 0 { + params[KEY_MAX_KEYS] = strconv.Itoa(marker.MaxKeys) + } + return params +} + +// Convert struct to request params +func getQueryParams(val interface{}) (map[string]string, error) { + var params map[string]string + if val != nil { + err := json.Unmarshal([]byte(Json(val)), ¶ms) + if err != nil { + return nil, err + } + } + return params, nil +} + +// CreateInstance - create a Instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create a instance +// +// RETURNS: +// - *InstanceIds: the result of create RDS, contains new RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateInstance(args *CreateInstanceArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + result := &CreateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDdcInstanceUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateRds - create a DDC with the specific parameters +// +// PARAMS: +// - args: the arguments to create a ddc +// +// RETURNS: +// - *InstanceIds: the result of create DDC, contains new DDC's instanceIds +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateRds(args *CreateRdsArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.Engine == "" { + return nil, fmt.Errorf("unset Engine") + } + + if args.EngineVersion == "" { + return nil, fmt.Errorf("unset EngineVersion") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + + newArgs := &CreateInstanceArgs{ + InstanceType: "RDS", + Number: args.PurchaseCount, + ClientToken: args.ClientToken, + Instance: CreateInstance{ + InstanceName: args.InstanceName, + Engine: strings.ToLower(args.Engine), + EngineVersion: args.EngineVersion, + CpuCount: args.CpuCount, + AllocatedMemoryInGB: int(args.MemoryCapacity), + AllocatedStorageInGB: args.VolumeCapacity, + DiskIoType: "ssd", + DeployId: args.DeployId, + PoolId: args.PoolId, + IsDirectPay: args.IsDirectPay, + Billing: args.Billing, + AutoRenewTime: args.AutoRenewTime, + AutoRenewTimeUnit: args.AutoRenewTimeUnit, + Tags: args.Tags, + Category: args.Category, + SyncMode: strings.ToLower(args.SyncMode), + }, + } + + info, err := c.SupplyVpcInfo(newArgs, args) + if err != nil { + return nil, err + } + result, err2 := c.CreateInstance(info) + if err2 != nil { + return nil, err2 + } + return result, nil +} + +func (c *DDCClient) SupplyVpcInfo(newArgs *CreateInstanceArgs, args *CreateRdsArgs) (*CreateInstanceArgs, error) { + + info := newArgs + vpc, err := c.ListVpc() + if err != nil { + fmt.Printf("list vpc error: %+v\n", err) + return nil, err + } + defaultVpcId := "" + if args.VpcId == "" { + for _, e := range *vpc { + defaultVpcId = e.VpcId + info.Instance.VpcId = e.VpcId + args.VpcId = e.VpcId + } + } + if args.VpcId == defaultVpcId { + for _, e := range *vpc { + if e.VpcId == args.VpcId { + info.Instance.VpcId = e.VpcId + args.VpcId = e.VpcId + } + } + info, err = c.UnDefaultVpcInfo(info, args) + if err != nil { + fmt.Printf("set vpc error: %+v\n", err) + return nil, err + } + } else { + for _, e := range *vpc { + if args.VpcId == e.ShortId { + info.Instance.VpcId = e.VpcId + args.VpcId = e.VpcId + } + } + info, err = c.UnDefaultVpcInfo(info, args) + if err != nil { + fmt.Printf("supply zoneAndSubnet info error: %+v\n", err) + return nil, err + } + } + return info, nil +} + +func (c *DDCClient) SupplyZoneAndSubnetInfo(newArgs *CreateInstanceArgs, args *CreateRdsArgs) (*CreateInstanceArgs, error) { + newZoneName := "" + if args.Subnets != nil { + for _, e := range args.Subnets { + newZoneName += e.ZoneName + "," + } + if newZoneName != "" && newZoneName[0:len(newZoneName)-1] != strings.Join(args.ZoneNames, ",") { + fmt.Printf("subnets and zoneNames not matcher: %+v\n", nil) + return nil, errors.New("subnets and zoneNames not matcher") + } else { + listSubnetsArgs := &ListSubnetsArgs{ + VpcId: args.VpcId, + } + subnets, err1 := c.ListSubnets(listSubnetsArgs) + if err1 != nil { + fmt.Printf("list subnets error: %+v\n", err1) + return nil, err1 + } + subnetId := "" + if args.Subnets != nil { + for _, e := range subnets.Subnets { + for _, e1 := range args.Subnets { + if e.ShortId == e1.SubnetId { + subnetId += e.Az + ":" + e.LongId + "," + } + } + } + if subnetId == "" { + return nil, errors.New("subnetId no match vpc or pool") + } + newArgs.Instance.SubnetId = subnetId[0 : len(subnetId)-1] + } + } + } else { + var subnetStr string + for _, e := range args.ZoneNames { + if !strings.Contains(e, ",") { + listSubnetsArgs := &ListSubnetsArgs{ + VpcId: args.VpcId, + ZoneName: e, + } + subnets, err := c.ListSubnets(listSubnetsArgs) + if err != nil { + fmt.Printf("list subnets error: %+v\n", err) + return nil, err + } + if subnets != nil && len(subnets.Subnets) > 0 { + subnetId := subnets.Subnets[0].LongId + subnetStr += e + ":" + subnetId + "," + } + } + } + if len(subnetStr) < 1 { + return nil, errors.New("Have no available subnet") + } + newArgs.Instance.SubnetId = subnetStr[:len(subnetStr)-1] + } + return newArgs, nil +} + +func (c *DDCClient) UnDefaultVpcInfo(newArgs *CreateInstanceArgs, args *CreateRdsArgs) (*CreateInstanceArgs, error) { + info := newArgs + list, err2 := c.GetZoneList() + if err2 != nil { + fmt.Printf("get zone list error: %+v\n", err2) + return nil, err2 + } + newZoneName := "" + if args.ZoneNames == nil { + if args.Subnets == nil { + subnets, _ := c.ListSubnets(&ListSubnetsArgs{VpcId: args.VpcId}) + if subnets == nil || len(subnets.Subnets) == 0 { + return nil, errors.New("Have no available subnet or zone") + } + + for _, e := range subnets.Subnets { + info.Instance.AZone = e.Az + args.ZoneNames = append(args.ZoneNames, e.Az) + break + } + //for _, e := range list.Zones { + // info.Instance.AZone = e.ApiZoneNames[0] + // args.ZoneNames = append(args.ZoneNames, e.ApiZoneNames[0]) + // break + //} + } else { + for _, e := range args.Subnets { + newZoneName += e.ZoneName + "," + args.ZoneNames = append(args.ZoneNames, e.ZoneName) + } + for _, e := range list.Zones { + if newZoneName == strings.Join(e.ApiZoneNames, ",") { + info.Instance.AZone = strings.Join(e.ApiZoneNames, ",") + } + } + } + if args.ZoneNames == nil { + return nil, errors.New("Have no available zone for your operation.") + } + } else { + newZoneName = "" + for _, e1 := range list.Zones { + if strings.Join(args.ZoneNames, ",") == strings.Join(e1.ZoneNames, ",") { + newZoneName = strings.Join(e1.ApiZoneNames, ",") + } + } + info.Instance.AZone = newZoneName + } + + info, err2 = c.SupplyZoneAndSubnetInfo(info, args) + if err2 != nil { + return nil, err2 + } + return info, nil +} + +// CreateReadReplica - create a readReplica ddc with the specific parameters +// +// PARAMS: +// - args: the arguments to create a readReplica ddc +// +// RETURNS: +// - *InstanceIds: the result of create a readReplica ddc, contains the readReplica DDC's instanceIds +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateReadReplica(args *CreateReadReplicaArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.SourceInstanceId == "" { + return nil, fmt.Errorf("unset SourceInstanceId") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + detail, err2 := c.GetDdcDetail(args.SourceInstanceId) + if err2 != nil { + return nil, err2 + } + newArgs := &CreateInstanceArgs{ + InstanceType: "RDS", + Number: args.PurchaseCount, + ClientToken: args.ClientToken, + Instance: CreateInstance{ + SourceInstanceId: args.SourceInstanceId, + InstanceName: args.InstanceName, + Engine: strings.ToLower(detail.Instance.Engine), + EngineVersion: detail.Instance.EngineVersion, + CpuCount: args.CpuCount, + AllocatedMemoryInGB: int(args.MemoryCapacity), + AllocatedStorageInGB: args.VolumeCapacity, + DiskIoType: "ssd", + DeployId: args.DeployId, + PoolId: args.PoolId, + RoGroupId: args.RoGroupId, + RoGroupWeight: Int(args.RoGroupWeight), + EnableDelayOff: Int(args.EnableDelayOff), + DelayThreshold: Int(args.DelayThreshold), + LeastInstanceAmount: Int(args.LeastInstanceAmount), + Billing: args.Billing, + IsDirectPay: args.IsDirectPay, + AutoRenewTime: args.AutoRenewTime, + AutoRenewTimeUnit: args.AutoRenewTimeUnit, + Tags: args.Tags, + }, + } + + createRdsArgs := &CreateRdsArgs{ + VpcId: args.VpcId, + Subnets: args.Subnets, + ZoneNames: args.ZoneNames, + } + + info, err := c.SupplyVpcInfo(newArgs, createRdsArgs) + if err != nil { + return nil, err + } + result, err2 := c.CreateInstance(info) + if err2 != nil { + return nil, err2 + } + + return result, err +} + +// UpdateRoGroup - update a roGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateRoGroup(roGroupId string, args *UpdateRoGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + body := &UpdateRoGroupRealArgs{ + RoGroupName: args.RoGroupName, + // 处理零值序列化问题 + EnableDelayOff: Int(args.EnableDelayOff), + DelayThreshold: Int(args.DelayThreshold), + LeastInstanceAmount: Int(args.LeastInstanceAmount), + IsBalanceRoLoad: Int(args.IsBalanceRoLoad), + MasterDelay: Int(args.MasterDelay), + } + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUpdateRoGroupUriWithId(roGroupId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(body). + Do() + return err +} + +// UpdateRoGroupReplicaWeight- update repica weight in roGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateRoGroupReplicaWeight(roGroupId string, args *UpdateRoGroupWeightArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + body := &UpdateRoGroupWeightRealArgs{ + RoGroupName: args.RoGroupName, + // 处理零值序列化问题 + EnableDelayOff: Int(args.EnableDelayOff), + DelayThreshold: Int(args.DelayThreshold), + LeastInstanceAmount: Int(args.LeastInstanceAmount), + IsBalanceRoLoad: Int(args.IsBalanceRoLoad), + MasterDelay: Int(args.MasterDelay), + ReplicaList: args.ReplicaList, + } + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUpdateRoGroupWeightUriWithId(roGroupId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(body). + Do() + return err +} + +// ReBalanceRoGroup- Initiate a rebalance for foGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) ReBalanceRoGroup(roGroupId string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getReBalanceRoGroupUriWithId(roGroupId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + return err +} + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateDeploySet(poolId string, args *CreateDeployRequest) (*CreateDeployResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.Strategy) < 1 { + args.Strategy = "centralized" + } + if !(args.Strategy == "distributed" || args.Strategy == "centralized") { + return nil, fmt.Errorf("Only support strategy centralized, current strategy: %v", args.Strategy) + } + + result := &CreateDeployResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDeploySetUri(poolId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpdateDeploySet - update a deploy set +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateDeploySet(poolId string, deployId string, args *UpdateDeployRequest) error { + if args == nil { + return fmt.Errorf("unset args") + } + if !(args.Strategy == "distributed" || args.Strategy == "centralized") { + return fmt.Errorf("Only support strategy distributed/centralized, current strategy: %v", args.Strategy) + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDeploySetUriWithId(poolId, deployId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListRds - list all instances +// RETURNS: +// - *ListRdsResult: the result of list instances with marker +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListRds(marker *ListRdsArgs) (*ListRdsResult, error) { + req := &bce.BceRequest{} + req.SetUri(getDdcInstanceUri() + "/list") + req.SetMethod(http.GET) + if marker != nil { + req.SetParam(KEY_MARKER, marker.Marker) + req.SetParam(KEY_MAX_KEYS, strconv.Itoa(marker.MaxKeys)) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &ListRdsResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// ListPage - list all instances with page +// RETURNS: +// - *ListPageResult: the result of list instances with marker +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListPage(args *ListPageArgs) (*ListPageResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + result := &ListPageResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDdcInstanceUri()+"/listPage"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetDdcDetail - get details of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// +// RETURNS: +// - *InstanceModelResult: the detail of the instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetDdcDetail(instanceId string) (*InstanceModelResult, error) { + result := &InstanceModelResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)). + WithResult(result). + Do() + + return result, err +} + +// GetDetail - get a specific ddc Instance's detail +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *Instance: the specific ddc Instance's detail +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetDetail(instanceId string) (*Instance, error) { + detail, err := c.GetDdcDetail(instanceId) + result := &Instance{ + InstanceName: detail.Instance.InstanceName, + InstanceId: detail.Instance.InstanceId, + SourceInstanceId: detail.Instance.SourceInstanceId, + Endpoint: detail.Instance.Endpoint, + Engine: detail.Instance.Engine, + EngineVersion: detail.Instance.EngineVersion, + InstanceStatus: detail.Instance.InstanceStatus, + CpuCount: detail.Instance.CpuCount, + MemoryCapacity: detail.Instance.AllocatedMemoryInGB, + VolumeCapacity: detail.Instance.AllocatedStorageInGB, + UsedStorage: detail.Instance.UsedStorageInGB, + InstanceType: detail.Instance.Type, + InstanceCreateTime: detail.Instance.InstanceCreateTime, + InstanceExpireTime: detail.Instance.InstanceExpireTime, + PubliclyAccessible: detail.Instance.PublicAccessStatus, + PaymentTiming: detail.Instance.PaymentTiming, + SyncMode: detail.Instance.SyncMode, + Region: detail.Instance.Region, + VpcId: detail.Instance.VpcId, + BackupPolicy: detail.Instance.BackupPolicy, + RoGroupList: detail.Instance.RoGroupList, + NodeMaster: detail.Instance.NodeMaster, + NodeSlave: detail.Instance.NodeSlave, + NodeReadReplica: detail.Instance.NodeReadReplica, + Subnets: detail.Instance.Subnets, + DeployId: detail.Instance.DeployId, + ZoneNames: detail.Instance.ZoneNames, + Category: detail.Instance.Category, + LongBBCId: detail.Instance.LongBBCId, + InstanceTopoForReadonly: detail.Instance.InstanceTopoForReadonly, + AutoRenewRule: detail.Instance.AutoRenewRule, + } + // 兼容RDS字段 + result.PublicAccessStatus = strconv.FormatBool(result.PubliclyAccessible) + return result, err +} + +// DeleteRds - delete instances +// +// PARAMS: +// - instanceIds: id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) DeleteRds(instanceIds string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getDdcInstanceUri()+"/delete"). + WithQueryParam("instanceIds", instanceIds). + Do() +} + +// RebootInstance - reboot a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebooted +// - args: reboot args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) RebootInstanceWithArgs(instanceId string, args *RebootArgs) (*MaintainTaskIdResult, error) { + result := &MaintainTaskIdResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/reboot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpdateInstanceName - update name of a specified instance +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to update instanceName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateInstanceName(instanceId string, args *UpdateInstanceNameArgs) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/updateName"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return err +} + +// GetBackupList - get backup list of the instance +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *GetBackupListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetBackupList(instanceId string, args *GetBackupListArgs) (*GetBackupListResult, error) { + result := &GetBackupListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/snapshot"). + WithResult(result). + Do() + + if args != nil && result.Backups != nil { + backups := result.Backups + backupsLen := len(backups) + if backupsLen > args.MaxKeys { + // marker 分页,兼容rds sdk + find := false + start, end := 0, 0 + masterCount, markerIndex := 0, 1 + if "-1" == args.Marker || "" == args.Marker { + find = true + } + for i := 0; i < backupsLen; i++ { + backup := backups[i] + masterCount++ + if ("-1" != args.Marker) && backup.SnapshotId == args.Marker { + start = i + find = true + markerIndex = masterCount + } + if find && masterCount == markerIndex+args.MaxKeys { + end = i + } + } + if end == 0 { + end = backupsLen + } else { + // 设置下个Marker + result.NextMarker = backups[end].SnapshotId + result.IsTruncated = true + } + result.Backups = result.Backups[start:end] + } + result.MaxKeys = args.MaxKeys + } + + return result, err +} + +// GetZoneList - list all zone +// +// PARAMS: +// - c: the client agent which can perform sending request +// +// RETURNS: +// - *GetZoneListResult: result of the zone list +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetZoneList() (*GetZoneListResult, error) { + result := &GetZoneListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(URI_PREFIX + "/zone"). + WithResult(result). + Do() + + return result, err +} + +// ListsSubnet - list all Subnets +// +// PARAMS: +// - c: the client agent which can perform sending request +// - args: the arguments to list all subnets, not necessary +// +// RETURNS: +// - *ListSubnetsResult: result of the subnet list +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListSubnets(args *ListSubnetsArgs) (*ListSubnetsResult, error) { + if args == nil { + args = &ListSubnetsArgs{} + } + result := &ListSubnetsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(URI_PREFIX+"/subnet"). + WithQueryParam("vpcId", args.VpcId). + WithResult(result). + Do() + if args.ZoneName == "" { + return result, err + } + // to compat rds api, filter by zone and vpcId + if result.Subnets != nil && len(result.Subnets) > 0 { + var filterd = []Subnet{} + for _, subnet := range result.Subnets { + // subnet az is logical zone + if subnet.Az == args.ZoneName { + if args.VpcId == "" || args.VpcId == subnet.VpcId { + filterd = append(filterd, subnet) + } + } + } + result.Subnets = filterd + } + return result, err +} + +// ListPool - list current pools +// RETURNS: +// - *ListResultWithMarker: the result of list hosts with marker +// - error: nil if success otherwise the specific error +func (cli *DDCClient) ListPool(marker *Marker) (*ListPoolResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getPoolUri()) + req.SetMethod(http.GET) + if marker != nil { + req.SetParam(KEY_MARKER, marker.Marker) + req.SetParam(KEY_MAX_KEYS, strconv.Itoa(marker.MaxKeys)) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPoolResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// ListDeploySets - list all deploy sets +// RETURNS: +// - *ListResultWithMarker: the result of list deploy sets with marker +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListDeploySets(poolId string, marker *Marker) (*ListDeploySetResult, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUri(poolId)) + req.SetMethod(http.GET) + if marker != nil { + req.SetParam(KEY_MARKER, marker.Marker) + req.SetParam(KEY_MAX_KEYS, strconv.Itoa(marker.MaxKeys)) + } + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListDeploySetResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - poolId: the id of the pool +// - deploySetId: the id of the deploy set +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) DeleteDeploySet(poolId string, deploySetId string) error { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(poolId, deploySetId)) + req.SetMethod(http.DELETE) + + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + defer func() { resp.Body().Close() }() + + return nil +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - poolId: the id of the pool +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *DeploySet: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetDeploySet(poolId string, deploySetId string) (*DeploySet, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getDeploySetUriWithId(poolId, deploySetId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &DeploySet{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return jsonBody, nil +} + +// GetSecurityIps - get all SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *GetSecurityIpsResult: all security IP +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetSecurityIps(instanceId string) (*GetSecurityIpsResult, error) { + rowResult := &SecurityIpsRawResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/authIp"). + WithResult(rowResult). + Do() + // to compat rds api,json annotations for SecurityIps are different + result := &GetSecurityIpsResult{ + SecurityIps: rowResult.SecurityIps, + } + return result, err +} + +// UpdateSecurityIps - update SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: all SecurityIps +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateSecurityIps(instacneId string, args *UpdateSecurityIpsArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instacneId)+"/updateAuthIp"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ListParameters - list all parameters of a RDS instance +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListParametersResult: the result of list all parameters +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListParameters(instanceId string) (*ListParametersResult, error) { + result := &ListParametersResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/parameter" + "/list"). + WithResult(result). + Do() + + return result, err +} + +// UpdateParameter - update Parameter +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: *UpdateParameterArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateParameter(instanceId string, args *UpdateParameterArgs) (*ProducedMaintainTaskResult, error) { + + result := &ProducedMaintainTaskResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceIdV2(instanceId)+"/parameter"+"/modify"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateBackup - create backup of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateBackup(instanceId string) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDdcUriWithInstanceId(instanceId)+"/snapshot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return err +} + +// GetBackupDetail - get details of the instance'Backup +// +// PARAMS: +// - instanceId: the id of the instance +// - snapshotId: the id of the backup +// +// RETURNS: +// - *BackupDetailResult: the detail of the backup +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetBackupDetail(instanceId string, snapshotId string) (*BackupDetailResult, error) { + result := &BackupDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/snapshot" + "/" + snapshotId). + WithResult(result). + Do() + + return result, err +} + +// ModifyBackupPolicy - update backupPolicy +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: the specific rds Instance's BackupPolicy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) ModifyBackupPolicy(instanceId string, args *BackupPolicy) error { + + result := &bce.BceResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/snapshot"+"/update"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return err +} + +// GetBinlogList - get backup list of the instance +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *BinlogListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetBinlogList(instanceId string, datetime string) (*BinlogListResult, error) { + + result := &BinlogListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)+"/binlog"). + WithQueryParam("datetime", datetime). + WithResult(result). + Do() + + return result, err +} + +// GetBinlogDetail - get details of the instance'Binlog +// +// PARAMS: +// - instanceId: the id of the instance +// - binlog: the id of the binlog +// +// RETURNS: +// - *BinlogDetailResult: the detail of the binlog +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetBinlogDetail(instanceId string, binlog string) (*BinlogDetailResult, error) { + result := &BinlogDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId) + "/binlog" + "/" + binlog). + WithResult(result). + Do() + + return result, err +} + +// SwitchInstance - main standby switching of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// - args: switch now or wait to the maintain time +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) SwitchInstance(instanceId string, args *SwitchArgs) (*ProducedMaintainTaskResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + result := &ProducedMaintainTaskResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/switchMaster"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateDatabase - create a database with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateDatabase(instanceId string, args *CreateDatabaseArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.DbName == "" { + return fmt.Errorf("unset DbName") + } + + if args.CharacterSetName == "" { + return fmt.Errorf("unset CharacterSetName") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDatabaseUriWithInstanceId(instanceId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteDatabase - delete an database of a DDC instance +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - dbName: the specific database's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) DeleteDatabase(instanceId, dbName string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getDatabaseUriWithDbName(instanceId, dbName)). + Do() +} + +// UpdateDatabaseRemark - update a database remark with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - dbName: the specific accountName +// - args: the arguments to update a database remark +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateDatabaseRemark(instanceId string, dbName string, args *UpdateDatabaseRemarkArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + //if args.Remark == "" { + // return fmt.Errorf("unset Remark") + //} + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDatabaseUriWithDbName(instanceId, dbName)). + WithQueryParam("remark", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetDatabase - get an database of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - dbName: the specific database's name +// +// RETURNS: +// - *Database: the database's meta +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetDatabase(instanceId, dbName string) (*Database, error) { + result := &DatabaseResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDatabaseUriWithDbName(instanceId, dbName)). + WithResult(result). + Do() + + result.Database.DbStatus = strings.Title(result.Database.DbStatus) + return &result.Database, err +} + +// ListDatabase - list all database of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *ListDatabaseResult: the result of list all database, contains all databases' meta +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListDatabase(instanceId string) (*ListDatabaseResult, error) { + result := &ListDatabaseResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDatabaseUriWithInstanceId(instanceId)). + WithResult(result). + Do() + + if result.Databases != nil { + for idx, _ := range result.Databases { + result.Databases[idx].DbStatus = strings.Title(result.Databases[idx].DbStatus) + } + } + return result, err +} + +// GetTableAmount - query amount of tables +// +// PARAMS: +// - args: the specific ddc instanceId, dbName and search pattern +// +// RETURNS: +// - *TableAmountResult: the size of the table that meets the criteria +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetTableAmount(args *GetTableAmountArgs) (*TableAmountResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.InstanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(args.DbName) < 1 { + return nil, fmt.Errorf("unset dbName") + } + result := &TableAmountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParam("pattern", args.Pattern). + WithURL(getQueryDatabaseUriWithDbName(args.InstanceId, args.DbName)). + WithResult(result). + Do() + + return result, err +} + +// GetDatabaseDiskUsage - get the disk footprint and the remaining space for database +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *ListDatabaseResult: the disk footprint and the remaining space for database +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetDatabaseDiskUsage(instanceId, dbName string) (*DatabaseDiskUsageResult, error) { + result := &DatabaseDiskUsageResult{} + req := bce.NewRequestBuilder(c) + if len(dbName) > 0 { + req.WithQueryParam("pattern", dbName) + } + err := req. + WithMethod(http.GET). + WithURL(getDatabaseDiskUsageUriWithInstanceId(instanceId)). + WithResult(result). + Do() + return result, err +} + +// GetRecoverableDateTime - get a list of recoverable times +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *GetRecoverableDateTimeResult: the result of list all recoverable datetimes +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetRecoverableDateTime(instanceId string) (*GetRecoverableDateTimeResult, error) { + result := &GetRecoverableDateTimeResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDatabaseRecoverTimeUriWithInstanceId(instanceId)). + WithResult(result). + Do() + return result, err +} + +// RecoverToSourceInstanceByDatetime - recover database or tables for the specific instance by a datetime +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *MaintainTaskIdResult: ID of generated maintain task +// - error: nil if success otherwise the specific error +func (c *DDCClient) RecoverToSourceInstanceByDatetime(instanceId string, args *RecoverInstanceArgs) (*MaintainTaskIdResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.Datetime) < 1 { + return nil, fmt.Errorf("unset datetime. Please query recoverable datetime by GetRecoverableDateTime()") + } + if args.RecoverData == nil || len(args.RecoverData) < 1 { + return nil, fmt.Errorf("unset recover data") + } + result := &MaintainTaskIdResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRecoverInstanceDatabaseUriWithInstanceId(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// CreateAccount - create a account with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) CreateAccount(instanceId string, args *CreateAccountArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.AccountName == "" { + return fmt.Errorf("unset AccountName") + } + + if args.Password == "" { + return fmt.Errorf("unset Password") + } + + if args.AccountType == "" { + args.AccountType = "common" + } + if args.AccountType == "Super" { + args.AccountType = "rdssuper" + } + if args.AccountType == "Common" { + args.AccountType = "common" + } + if args.DatabasePrivileges != nil { + for idx, _ := range args.DatabasePrivileges { + if args.DatabasePrivileges[idx].AuthType == "ReadOnly" { + args.DatabasePrivileges[idx].AuthType = "readOnly" + } else if args.DatabasePrivileges[idx].AuthType == "ReadWrite" { + args.DatabasePrivileges[idx].AuthType = "readWrite" + } + } + } + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getAccountUriWithInstanceId(instanceId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteAccount - delete an account of a RDS instance +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - accountName: the specific account's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) DeleteAccount(instanceId, accountName string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + Do() +} + +// UpdateAccountPassword - update a account password with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateAccountPassword(instanceId string, accountName string, args *UpdateAccountPasswordArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.Password == "" { + return fmt.Errorf("unset Password") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithQueryParam("password", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateAccountDesc - update a account desc with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account remark +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateAccountDesc(instanceId string, accountName string, args *UpdateAccountDescArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + //if args.Remark == "" { + // return fmt.Errorf("unset Remark") + //} + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithQueryParam("remark", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateAccountPrivileges - update a account privileges with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account privileges +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateAccountPrivileges(instanceId string, accountName string, args *UpdateAccountPrivilegesArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + for idx, _ := range args.DatabasePrivileges { + if args.DatabasePrivileges[idx].AuthType == "ReadOnly" { + args.DatabasePrivileges[idx].AuthType = "readOnly" + } else if args.DatabasePrivileges[idx].AuthType == "ReadWrite" { + args.DatabasePrivileges[idx].AuthType = "readWrite" + } + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithQueryParam("privileges", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetAccount - get an account of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - accountName: the specific account's name +// +// RETURNS: +// - *Account: the account's meta +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetAccount(instanceId, accountName string) (*Account, error) { + result := &AccountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAccountUriWithAccountName(instanceId, accountName)). + WithResult(result). + Do() + + if result.Account.AccountType == "common" { + result.Account.AccountType = "Common" + } else if result.Account.AccountType == "rdssuper" { + result.Account.AccountType = "Super" + } + + for idx, _ := range result.Account.DatabasePrivileges { + if result.Account.DatabasePrivileges[idx].AuthType == "readOnly" { + result.Account.DatabasePrivileges[idx].AuthType = "ReadOnly" + } else if result.Account.DatabasePrivileges[idx].AuthType == "readWrite" { + result.Account.DatabasePrivileges[idx].AuthType = "ReadWrite" + } + } + result.Account.Status = strings.Title(result.Account.Status) + return &result.Account, err +} + +// ListAccount - list all account of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListAccountResult: the result of list all account, contains all accounts' meta +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListAccount(instanceId string) (*ListAccountResult, error) { + result := &ListAccountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAccountUriWithInstanceId(instanceId)). + WithResult(result). + Do() + for idx, _ := range result.Accounts { + if result.Accounts[idx].AccountType == "common" { + result.Accounts[idx].AccountType = "Common" + } else if result.Accounts[idx].AccountType == "rdssuper" { + result.Accounts[idx].AccountType = "Super" + } + result.Accounts[idx].Status = strings.Title(result.Accounts[idx].Status) + + for iidx, _ := range result.Accounts[idx].DatabasePrivileges { + if result.Accounts[idx].DatabasePrivileges[iidx].AuthType == "readOnly" { + result.Accounts[idx].DatabasePrivileges[iidx].AuthType = "ReadOnly" + } else if result.Accounts[idx].DatabasePrivileges[iidx].AuthType == "readWrite" { + result.Accounts[idx].DatabasePrivileges[iidx].AuthType = "ReadWrite" + } + } + } + return result, err +} + +// ListRoGroup - list all roGroups of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListRoGroupResult: All roGroups of the current instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListRoGroup(instanceId string) (*ListRoGroupResult, error) { + result := &ListRoGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRoGroupUriWithInstanceId(instanceId) + "/list"). + WithResult(result). + Do() + + return result, err +} + +// ListVpc - list all Vpc +// +// PARAMS: +// RETURNS: +// - *ListVpc: All vpc of +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListVpc() (*[]VpcVo, error) { + result := &[]VpcVo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUri() + "/vpcList"). + WithResult(result). + Do() + + return result, err +} + +// GetMaintainTime - get details of the maintainTime +// +// PARAMS: +// - poolId: the id of the pool +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *MaintainTime: the maintainTime of the instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetMaintainTime(instanceId string) (*MaintainTime, error) { + // Build the request + req := &bce.BceRequest{} + req.SetUri(getMaintainTimeUriWithInstanceId(instanceId)) + req.SetMethod(http.GET) + + // Send request and get response + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &MaintainWindow{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + + return &jsonBody.MaintainTime, nil +} + +// UpdateMaintainTime - update UpdateMaintainTime of instance +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UpdateMaintainTime(instanceId string, args *MaintainTime) error { + if args == nil { + return fmt.Errorf("unset args") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUpdateMaintainTimeUriWithInstanceId(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListRecycleInstances - list all instances in recycler with marker +// +// PARAMS: +// - marker: marker page +// +// RETURNS: +// - *RecyclerInstanceList: the result of instances in recycler +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListRecycleInstances(marker *Marker) (*RecyclerInstanceList, error) { + result := &RecyclerInstanceList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParams(getMarkerParams(marker)). + WithURL(getRecyclerUrl()). + WithResult(result). + Do() + + return result, err +} + +// RecoverRecyclerInstances - batch recover instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to recover +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) RecoverRecyclerInstances(instanceIds []string) (*OrderIdResponse, error) { + if instanceIds == nil || len(instanceIds) < 1 { + return nil, fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return nil, fmt.Errorf("the instanceIds length max value is 10") + } + + args := &BatchInstanceIds{ + InstanceIds: strings.Join(instanceIds, COMMA), + } + + result := &OrderIdResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRecyclerRecoverUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// DeleteRecyclerInstances - batch delete instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) DeleteRecyclerInstances(instanceIds []string) error { + if instanceIds == nil || len(instanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return fmt.Errorf("the instanceIds length max value is 10") + } + + // delete use query params + instanceIdsParam := strings.Join(instanceIds, COMMA) + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRecyclerDeleteUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("instanceIds", instanceIdsParam). + Do() + return err +} + +// ListSecurityGroupByVpcId - list security groups by vpc id +// +// PARAMS: +// - vpcId: id of vpc +// +// RETURNS: +// - *[]SecurityGroup:security groups of vpc +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListSecurityGroupByVpcId(vpcId string) (*[]SecurityGroup, error) { + if len(vpcId) < 1 { + return nil, fmt.Errorf("unset vpcId") + } + result := &[]SecurityGroup{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupWithVpcIdUrl(vpcId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// ListSecurityGroupByInstanceId - list security groups by instance id +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *ListSecurityGroupResult: list secrity groups result of instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListSecurityGroupByInstanceId(instanceId string) (*ListSecurityGroupResult, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + result := &ListSecurityGroupResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupWithInstanceIdUrl(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// BindSecurityGroups - bind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) BindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(args.InstanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(args.SecurityGroupIds) < 1 { + return fmt.Errorf("unset securityGroupIds") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBindSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// UnBindSecurityGroups - unbind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) UnBindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(args.InstanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(args.SecurityGroupIds) < 1 { + return fmt.Errorf("unset securityGroupIds") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUnBindSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ReplaceSecurityGroups - replace SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) ReplaceSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(args.InstanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(args.SecurityGroupIds) < 1 { + return fmt.Errorf("unset securityGroupIds") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getReplaceSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListLogByInstanceId - list error or slow logs of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *[]Log:logs of instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) ListLogByInstanceId(instanceId string, args *ListLogArgs) (*[]Log, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if args == nil { + return nil, fmt.Errorf("unset list args") + } + if "error" != args.LogType && "slow" != args.LogType { + return nil, fmt.Errorf("invalid logType, should be 'error' or 'slow'") + } + result := &[]Log{} + _, err := time.Parse("2006-01-02", args.Datetime) + if err != nil { + return nil, err + } + err = bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getLogsUrlWithInstanceId(instanceId)). + WithQueryParam("logType", strings.ToLower(args.LogType)). + WithQueryParam("datetime", args.Datetime). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetLogById - get log's detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Log:log's detail of instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetLogById(instanceId, logId string, args *GetLogArgs) (*LogDetail, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(logId) < 1 { + return nil, fmt.Errorf("unset logId") + } + if args == nil { + return nil, fmt.Errorf("unset get log args") + } + + result := &LogDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getLogsUrlWithLogId(instanceId, logId)). + WithQueryParam("downloadValidTimeInSec", strconv.Itoa(args.ValidSeconds)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// LazyDropCreateHardLink - create a hard link for specified large table +// +// PARAMS: +// - instanceId: id of instance +// - dbName: name of database +// - tableName: name of table +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) LazyDropCreateHardLink(instanceId, dbName, tableName string) error { + if len(instanceId) < 1 { + return fmt.Errorf("unset instanceId") + } + if len(dbName) < 1 { + return fmt.Errorf("unset dbName") + } + if len(tableName) < 1 { + return fmt.Errorf("unset tableName") + } + + args := &CreateTableHardLinkArgs{ + TableName: tableName, + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getCreateTableHardLinkUrl(instanceId, dbName)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// LazyDropDeleteHardLink - delete the hard link for specified large table +// +// PARAMS: +// - instanceId: id of instance +// - dbName: name of database +// - tableName: name of table +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) LazyDropDeleteHardLink(instanceId, dbName, tableName string) (*MaintainTaskIdResult, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(dbName) < 1 { + return nil, fmt.Errorf("unset dbName") + } + if len(tableName) < 1 { + return nil, fmt.Errorf("unset tableName") + } + result := &MaintainTaskIdResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getTableHardLinkUrl(instanceId, dbName, tableName)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// ResizeRds - resize an RDS with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to resize an RDS +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) ResizeRds(instanceId string, args *ResizeRdsArgs) (*OrderIdResponse, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + result := &OrderIdResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/resize"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateSyncMode - update sync mode of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update syncMode +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) ModifySyncMode(instanceId string, args *ModifySyncModeArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getChangeSemiSyncStatusUrlWithId(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetDisk - get disk detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Disk:disk of instance +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetDisk(instanceId string) (*Disk, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &Disk{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)+"/disk"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetMachineInfo - get machine info of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *MachineInfo:info of machine resource +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetMachineInfo(instanceId string) (*MachineInfo, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &MachineInfo{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUriWithInstanceId(instanceId)+"/machine"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetResidual - get residual of pool +// +// PARAMS: +// - poolId: id of pool +// - zoneName: the zone name +// +// RETURNS: +// - *GetResidualResult:residual of pool +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetResidual(poolId string) (*GetResidualResult, error) { + if len(poolId) < 1 { + return nil, fmt.Errorf("unset poolId") + } + + result := &GetResidualResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getPoolUriWithId(poolId)+"/residual"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetFlavorCapacity - get flavor capacity of pool +// +// PARAMS: +// - poolId: id of pool +// - args: request params +// +// RETURNS: +// - *GetResidualResult:get flavor capacity of pool +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetFlavorCapacity(poolId string, args *GetFlavorCapacityArgs) (*GetFlavorCapacityResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(poolId) < 1 { + return nil, fmt.Errorf("unset poolId") + } + + result := &GetFlavorCapacityResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getPoolUriWithId(poolId)+"/flavorCap"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("cpuInCore", strconv.Itoa(args.CpuInCore)). + WithQueryParam("diskInGb", strconv.FormatInt(args.DiskInGb, 10)). + WithQueryParam("memoryInGb", strconv.FormatInt(args.MemoryInGb, 10)). + WithQueryParam("affinity", strconv.FormatInt(args.Affinity, 10)). + WithResult(result). + Do() + return result, err +} + +// KillSession - start kill session tasks +// +// PARAMS: +// - instanceId: id of the instance +// - args: instance role and sessionIds +// +// RETURNS: +// - *KillSessionResult: the response of kill session task id +// - error: nil if success otherwise the specific error +func (c *DDCClient) KillSession(instanceId string, args *KillSessionArgs) (*KillSessionResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + result := &KillSessionResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getKillSessionUri(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + if err != nil { + return nil, err + } + return result, err +} + +// GetKillSessionTask - get kill session tasks by taskId +// +// PARAMS: +// - instanceId: the specific instanceId of ddc +// - taskId: kill session returned id +// +// RETURNS: +// - *GetKillSessionTaskResult: the response of kill session task +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetKillSessionTask(instanceId string, taskId int) (*GetKillSessionTaskResult, error) { + result := &GetKillSessionTaskResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getKillSessionTaskUri(instanceId, taskId)). + WithResult(result). + Do() + + return result, err +} + +// GetMaintainTaskList - get maintain tasks by taskId +// +// PARAMS: +// RETURNS: +// - *ListMaintainTaskResult: the response of maintain tasks +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetMaintainTaskList(args *GetMaintainTaskListArgs) (*ListMaintainTaskResult, error) { + if args == nil || len(args.StartTime) < 1 { + return nil, fmt.Errorf("unset startTime") + } + result := &ListMaintainTaskResult{} + req := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getMaintainTaskUri()). + WithResult(result). + WithQueryParams(getMarkerParams(&args.Marker)). + WithQueryParam("startTime", args.StartTime) + if len(args.EndTime) > 0 { + req.WithQueryParam("endTime", args.EndTime) + } + err := req.Do() + return result, err +} + +// GetMaintainTaskDetail - get maintain task detail by taskId +// +// PARAMS: +// RETURNS: +// - *MaintainTaskDetailList: the response of maintain task detail +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetMaintainTaskDetail(taskIds string) (*MaintainTaskDetailList, error) { + if len(taskIds) < 1 { + return nil, fmt.Errorf("unset taskIds") + } + result := &MaintainTaskDetailList{} + req := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getMaintainTaskDetailUri()). + WithResult(result). + WithQueryParam("taskId", taskIds) + err := req.Do() + return result, err +} + +// ExecuteMaintainTaskImmediately - execute maintain task immediately +// +// PARAMS: +// - taskId: id of the task +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) ExecuteMaintainTaskImmediately(taskId string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getMaintainTaskUriWithTaskId(taskId)+"/executeNow"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + if err != nil { + return err + } + return nil +} + +// CancelMaintainTask - cancel maintain task +// +// PARAMS: +// - taskId: id of the task +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *DDCClient) CancelMaintainTask(taskId string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getMaintainTaskUriWithTaskId(taskId)+"/cancel"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + if err != nil { + return err + } + return nil +} + +// GetAccessLog - get access logs's download info by date +// +// PARAMS: +// RETURNS: +// - *AccessLog: the access logs's download info +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetAccessLog(date string) (*AccessLog, error) { + if len(date) < 1 { + return nil, fmt.Errorf("unset date") + } + result := &AccessLog{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getAccessLogUrl()). + WithResult(result). + WithQueryParam("date", date). + Do() + + return result, err +} + +// GetErrorLog - get error logs +// +// PARAMS: +// RETURNS: +// - *ErrorLogsResponse: the error logs +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetErrorLogs(args *GetErrorLogsArgs) (*ErrorLogsResponse, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.InstanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(args.StartTime) < 1 { + return nil, fmt.Errorf("unset startTime") + } + if len(args.EndTime) < 1 { + return nil, fmt.Errorf("unset endTime") + } + if args.PageNo < 1 { + return nil, fmt.Errorf("unset pageNo") + } + if args.PageSize < 1 { + return nil, fmt.Errorf("unset pageSize") + } + if len(args.Role) < 1 { + return nil, fmt.Errorf("unset role") + } + + result := &ErrorLogsResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getErrorLogsUrlWithInstanceId(args.InstanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetSlowLog - get slow logs +// +// PARAMS: +// RETURNS: +// - *SlowLogsResponse: the slow logs +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetSlowLogs(args *GetSlowLogsArgs) (*SlowLogsResponse, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.InstanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(args.StartTime) < 1 { + return nil, fmt.Errorf("unset startTime") + } + if len(args.EndTime) < 1 { + return nil, fmt.Errorf("unset endTime") + } + if args.PageNo < 1 { + return nil, fmt.Errorf("unset pageNo") + } + if args.PageSize < 1 { + return nil, fmt.Errorf("unset pageSize") + } + if len(args.Role) < 1 { + return nil, fmt.Errorf("unset role") + } + + result := &SlowLogsResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getSlowLogsUrlWithInstanceId(args.InstanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetInstanceBackupStatus - get instance backup status and backup start time +// +// PARAMS: +// RETURNS: +// - *GetBackupStatusResponse: the response of backup status +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetInstanceBackupStatus(instanceId string) (*GetBackupStatusResponse, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &GetBackupStatusResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceBackupStatusUrl(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// InstanceVersionRollBack - rollback instance version from 5.7 to 5.6 +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to set WaitSwitch +// +// RETURNS: +// - *MaintainTaskIdResult: ID of generated maintain task +// - error: nil if success otherwise the specific error +func (c *DDCClient) InstanceVersionRollBack(instanceId string, args *InstanceVersionRollBackArg) (*MaintainTaskIdResult, error) { + + result := &MaintainTaskIdResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/rollback"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// InstanceVersionUpgrade - upgrade instance version from 5.6 to 5.7 +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to set IsUpgradeNow +// +// RETURNS: +// - *MaintainTaskIdResult: ID of generated maintain task +// - error: nil if success otherwise the specific error +func (c *DDCClient) InstanceVersionUpgrade(instanceId string, args *InstanceVersionUpgradeArg) (*MaintainTaskIdResult, error) { + + result := &MaintainTaskIdResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDdcUriWithInstanceId(instanceId)+"/upgrade"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// GetInstanceSyncDelay - get readonly instance syncDelay and syncStatus. +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *InstanceSyncDelayResponse: the response of syncDelay +// - error: nil if success otherwise the specific error +func (c *DDCClient) GetInstanceSyncDelay(instanceId string) (*InstanceSyncDelayResponse, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &InstanceSyncDelayResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceSyncDelayUrl(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// InstanceSyncDelayReplication - start or stop readonly instance syncDelay. +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *InstanceSyncDelayReplicationResponse: the response of success +// - error: nil if success otherwise the specific error +func (c *DDCClient) InstanceSyncDelayReplication(instanceId string, args *InstanceSyncDelayReplicationArg) (*InstanceSyncDelayReplicationResponse, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &InstanceSyncDelayReplicationResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceSyncDelayReplicationUrl(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// SnapshotAccessDetail - get snapshot access detail +// +// PARAMS: +// - args: the arguments to get snapshot access detail +// +// RETURNS: +// - *AccessDetail +// - error: nil if success otherwise the specific error +func (c *DDCClient) SnapshotAccessDetail(args *AccessDetailArgs) (*BackupAccessDetail, error) { + + result := &BackupAccessDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUri()+"/snapshot/accessdetail"). + WithQueryParam("startDateTime", args.StartDateTime). + WithQueryParam("endDateTime", args.EndDateTime). + WithQueryParam("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("dataType", args.DataType). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// BinlogAccessDetail - get snapshot access detail +// +// PARAMS: +// - args: the arguments to get snapshot access detail +// +// RETURNS: +// - *AccessDetail +// - error: nil if success otherwise the specific error +func (c *DDCClient) BinlogAccessDetail(args *AccessDetailArgs) (*BackupAccessDetail, error) { + + result := &BackupAccessDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDdcUri()+"/binlog/accessdetail"). + WithQueryParam("startDateTime", args.StartDateTime). + WithQueryParam("endDateTime", args.EndDateTime). + WithQueryParam("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("dataType", args.DataType). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} diff --git a/bce-sdk-go/services/ddc/v2/ddcrds.go b/bce-sdk-go/services/ddc/v2/ddcrds.go new file mode 100644 index 0000000..fcb98b1 --- /dev/null +++ b/bce-sdk-go/services/ddc/v2/ddcrds.go @@ -0,0 +1,1636 @@ +package ddcrds + +import ( + "encoding/json" + "fmt" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/services/ddc/ddc_util" + "github.com/baidubce/bce-sdk-go/services/rds" +) + +// Int int point helper +func Int(value string) *int { + if len(value) < 1 { + return nil + } + intPtr, err := strconv.Atoi(value) + if err != nil { + panic("please pass valid int value ") + } + return &intPtr +} + +func Json(v interface{}) string { + jsonStr, err := json.Marshal(v) + if err != nil { + panic("convert to json faild") + } + return string(jsonStr) +} + +func isDDC(productType string) bool { + return productType == "ddc" || productType == "DDC" +} + +// 根据实例ID判断产品类型是否为DDC +func isDDCId(instanceId string) bool { + if strings.HasPrefix(instanceId, "rds") { + return false + } + return true +} + +func getDDCAndRDSIds(instanceIds string) (string, string) { + instanceIdArr := strings.Split(instanceIds, ",") + ddcIds, rdsIds := "", "" + if len(instanceIdArr) > 0 { + for _, id := range instanceIdArr { + if isDDCId(id) { + ddcIds += id + "," + } else { + rdsIds += id + "," + } + } + } + if strings.HasSuffix(ddcIds, ",") { + ddcIds = ddcIds[:len(ddcIds)-1] + } + if strings.HasSuffix(rdsIds, ",") { + rdsIds = rdsIds[:len(rdsIds)-1] + } + return ddcIds, rdsIds +} + +// CreateInstance - create a Instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create a instance +// +// RETURNS: +// - *InstanceIds: the result of create RDS, contains new RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateRds(args *CreateRdsArgs, productType string) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + // 限制InstanceName + if strings.Contains(args.InstanceName, ".") { + return nil, fmt.Errorf("invalid InstanceName:. not support") + } + var result *CreateResult + var err error + if isDDC(productType) { + result, err = c.ddcClient.CreateRds(args) + } else { + rdsArgs := &rds.CreateRdsArgs{} + // copy 请求参数 + err = ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return nil, err + } + var rdsRes *rds.CreateResult + rdsRes, err = c.rdsClient.CreateRds(rdsArgs) + if rdsRes != nil { + result = &CreateResult{InstanceIds: rdsRes.InstanceIds} + } + } + + return result, err +} + +// CreateReadReplica - create a readReplica RDS with the specific parameters +// +// PARAMS: +// - args: the arguments to create a readReplica rds +// +// RETURNS: +// - *InstanceIds: the result of create a readReplica RDS, contains the readReplica RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateReadReplica(args *CreateReadReplicaArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.SourceInstanceId) < 1 { + return nil, fmt.Errorf("unset SourceInstanceId") + } + + // 默认创建1个只读实例 + if args.PurchaseCount < 1 { + args.PurchaseCount = 1 + } + var result *CreateResult + var err error + if isDDCId(args.SourceInstanceId) { + result, err = c.ddcClient.CreateReadReplica(args) + } else { + rdsArgs := &rds.CreateReadReplicaArgs{} + // copy 请求参数 + err = ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return nil, err + } + var rdsRes *rds.CreateResult + rdsRes, err = c.rdsClient.CreateReadReplica(rdsArgs) + if rdsRes != nil { + result = &CreateResult{InstanceIds: rdsRes.InstanceIds} + } + } + return result, err +} + +// UpdateRoGroup - update a roGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateRoGroup(roGroupId string, args *UpdateRoGroupArgs, productType string) error { + if isDDC(productType) { + return c.ddcClient.UpdateRoGroup(roGroupId, args) + } + return RDSNotSupportError() +} + +// UpdateRoGroupReplicaWeight- update repica weight in roGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateRoGroupReplicaWeight(roGroupId string, args *UpdateRoGroupWeightArgs, productType string) error { + if isDDC(productType) { + return c.ddcClient.UpdateRoGroupReplicaWeight(roGroupId, args) + } + return RDSNotSupportError() +} + +// ReBalanceRoGroup- Initiate a rebalance for foGroup +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ReBalanceRoGroup(roGroupId, productType string) error { + if len(roGroupId) < 1 { + return fmt.Errorf("unset roGroupId") + } + if isDDC(productType) { + return c.ddcClient.ReBalanceRoGroup(roGroupId) + } + return RDSNotSupportError() +} + +// CreateRdsProxy - create a proxy RDS with the specific parameters +// +// PARAMS: +// - args: the arguments to create a readReplica rds +// +// RETURNS: +// - *InstanceIds: the result of create a readReplica RDS, contains the readReplica RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateRdsProxy(args *CreateRdsProxyArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if len(args.SourceInstanceId) < 1 { + return nil, fmt.Errorf("unset SourceInstanceId") + } + + if isDDCId(args.SourceInstanceId) { + return nil, DDCNotSupportError() + } + // copy请求参数 + rdsArgs := &rds.CreateRdsProxyArgs{} + err := ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return nil, err + } + // copy返回结果 + rdsRes, err := c.rdsClient.CreateRdsProxy(rdsArgs) + if err != nil { + return nil, err + } + result := &CreateResult{InstanceIds: rdsRes.InstanceIds} + return result, err +} + +func (c *Client) listRdsInstance(marker *ListRdsArgs) (*ListRdsResult, error) { + rdsArgs := &rds.ListRdsArgs{} + // copy请求参数 + err := ddc_util.SimpleCopyProperties(rdsArgs, marker) + if err != nil { + return nil, err + } + var rdsRes *rds.ListRdsResult + rdsRes, err = c.rdsClient.ListRds(rdsArgs) + // copy返回结果 + result := &ListRdsResult{} + if rdsRes != nil { + err = ddc_util.SimpleCopyProperties(result, rdsRes) + } + if result.Instances != nil && + len(result.Instances) > 0 { + for i := range result.Instances { + err = convertRdsInstance(&result.Instances[i]) + } + } + return result, err +} + +// ListPage - list all instances with page +// RETURNS: +// - *ListRdsResult: the result of list instances with page +// - error: nil if success otherwise the specific error +func (c *Client) ListPage(args *ListPageArgs) (*ListPageResult, error) { + result, err := c.ddcClient.ListPage(args) + return result, err +} + +// ListRds - list all instances +// RETURNS: +// - *ListRdsResult: the result of list instances with marker +// - error: nil if success otherwise the specific error +func (c *Client) ListRds(marker *ListRdsArgs) (*ListRdsResult, error) { + var result *ListRdsResult + var err error + // 先获取DDC列表 + if len(marker.Marker) < 1 || marker.Marker == "-1" || isDDCId(marker.Marker) { + result, err = c.ddcClient.ListRds(marker) + if err != nil { + return nil, err + } + // 数量不够时获取RDS列表 + if len(result.Instances) < marker.MaxKeys { + // 修改marker + marker.MaxKeys = marker.MaxKeys - len(result.Instances) + rdsResult, err := c.listRdsInstance(marker) + if err != nil { + return nil, err + } + // 合并结果到result + if rdsResult != nil && len(rdsResult.Instances) > 0 { + result.Instances = append(result.Instances, rdsResult.Instances...) + result.Marker = rdsResult.Marker + result.IsTruncated = rdsResult.IsTruncated + result.NextMarker = rdsResult.NextMarker + } + } else if !result.IsTruncated { + // 使用IsTruncated判断DDC实例是否已查询完 + marker.MaxKeys = 1 + rdsResult, err := c.listRdsInstance(marker) + if err != nil { + return nil, err + } + if rdsResult != nil && len(rdsResult.Instances) > 0 { + result.NextMarker = rdsResult.Instances[0].InstanceId + result.IsTruncated = true + } + } + return result, err + } + // marker 到达rds时,直接取rds列表 + result, err = c.listRdsInstance(marker) + return result, err +} + +// GetDetail - get a specific ddc Instance's detail +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *Instance: the specific ddc Instance's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetDetail(instanceId string) (*Instance, error) { + var result *Instance + var err error + if isDDCId(instanceId) { + result, err = c.ddcClient.GetDetail(instanceId) + } else { + rdsRes, err1 := c.rdsClient.GetDetail(instanceId) + if err1 != nil { + return nil, err + } + // copy返回结果 + if rdsRes != nil { + result = &Instance{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + if err != nil { + return nil, err + } + err = convertRdsInstance(result) + } + } + + return result, err +} + +// 修改RDS中参数类型无法匹配的字段 +func convertRdsInstance(result *Instance) error { + // rds公网访问 + // Closed 未开放外网权限 + // Creating 公网开通中,成功后状态为Available + // Available 已开通公网 + result.PubliclyAccessible = result.PublicAccessStatus == "Available" + days := result.BackupPolicy.ExpireInDaysStr + var err error + if len(days) > 0 { + result.BackupPolicy.ExpireInDaysInt, err = strconv.Atoi(days) + } + return err +} + +// DeleteRds - delete instances +// +// PARAMS: +// - instanceIds: id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRds(instanceIds string) error { + var err error + ddcIds, rdsIds := getDDCAndRDSIds(instanceIds) + if len(ddcIds) > 0 { + err = c.ddcClient.DeleteRds(ddcIds) + } + if err != nil { + return err + } + if len(rdsIds) > 0 { + err = c.rdsClient.DeleteRds(rdsIds) + } + return err +} + +// ResizeRds - resize an RDS with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to resize an RDS +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeRds(instanceId string, args *ResizeRdsArgs) (*OrderIdResponse, error) { + if isDDCId(instanceId) { + return c.ddcClient.ResizeRds(instanceId, args) + } + // copy请求参数 + resReq := &rds.ResizeRdsArgs{} + err := ddc_util.SimpleCopyProperties(resReq, args) + if err != nil { + return nil, err + } + err = c.rdsClient.ResizeRds(instanceId, resReq) + return nil, err +} + +// CreateAccount - create a account with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateAccount(instanceId string, args *CreateAccountArgs) error { + var err error + if isDDCId(instanceId) { + err = c.ddcClient.CreateAccount(instanceId, args) + } else { + rdsArgs := &rds.CreateAccountArgs{} + // copy请求参数 + err = ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return err + } + err = c.rdsClient.CreateAccount(instanceId, rdsArgs) + } + + return err +} + +// ListAccount - list all account of a RDS instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListAccountResult: the result of list all account, contains all accounts' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListAccount(instanceId string) (*ListAccountResult, error) { + var result *ListAccountResult + var err error + if isDDCId(instanceId) { + result, err = c.ddcClient.ListAccount(instanceId) + } else { + var rdsRes *rds.ListAccountResult + rdsRes, err = c.rdsClient.ListAccount(instanceId) + // copy返回结果 + if rdsRes != nil { + result = &ListAccountResult{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + } + } + + return result, err +} + +// GetAccount - get an account of a RDS instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - accountName: the specific account's name +// +// RETURNS: +// - *Account: the account's meta +// - error: nil if success otherwise the specific error +func (c *Client) GetAccount(instanceId, accountName string) (*Account, error) { + var result *Account + var err error + if isDDCId(instanceId) { + result, err = c.ddcClient.GetAccount(instanceId, accountName) + } else { + var rdsRes *rds.Account + rdsRes, err = c.rdsClient.GetAccount(instanceId, accountName) + // copy返回结果 + if rdsRes != nil { + result = &Account{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + } + } + + return result, err +} + +// DeleteAccount - delete an account of a RDS instance +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - accountName: the specific account's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAccount(instanceId, accountName string) error { + var err error + if isDDCId(instanceId) { + err = c.ddcClient.DeleteAccount(instanceId, accountName) + } else { + err = c.rdsClient.DeleteAccount(instanceId, accountName) + } + return err +} + +// RebootInstance - reboot a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebooted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstance(instanceId string) error { + if isDDCId(instanceId) { + args := &RebootArgs{IsRebootNow: true} + _, err := c.ddcClient.RebootInstanceWithArgs(instanceId, args) + return err + } + err := c.rdsClient.RebootInstance(instanceId) + return err +} + +// RebootInstance - reboot a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebooted +// - args: reboot args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstanceWithArgs(instanceId string, args *RebootArgs) (*MaintainTaskIdResult, error) { + if isDDCId(instanceId) { + return c.ddcClient.RebootInstanceWithArgs(instanceId, args) + } + return nil, RDSNotSupportError() +} + +// UpdateInstanceName - update name of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update instanceName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceName(instanceId string, args *UpdateInstanceNameArgs) error { + var err error + if isDDCId(instanceId) { + err = c.ddcClient.UpdateInstanceName(instanceId, args) + } else { + rdsArgs := &rds.UpdateInstanceNameArgs{ + InstanceName: args.InstanceName, + } + err = c.rdsClient.UpdateInstanceName(instanceId, rdsArgs) + } + return err +} + +// UpdateSyncMode - update sync mode of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update syncMode +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifySyncMode(instanceId string, args *ModifySyncModeArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if isDDCId(instanceId) { + return c.ddcClient.ModifySyncMode(instanceId, args) + } + rdsArgs := &rds.ModifySyncModeArgs{SyncMode: args.SyncMode} + err := c.rdsClient.ModifySyncMode(instanceId, rdsArgs) + return err +} + +// ModifyEndpoint - modify the prefix of endpoint +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to modify endpoint +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyEndpoint(instanceId string, args *ModifyEndpointArgs) error { + if isDDCId(instanceId) { + return DDCNotSupportError() + } + rdsArgs := &rds.ModifyEndpointArgs{Address: args.Address} + err := c.rdsClient.ModifyEndpoint(instanceId, rdsArgs) + return err +} + +// ModifyPublicAccess - modify public access +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to modify public access +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyPublicAccess(instanceId string, args *ModifyPublicAccessArgs) error { + if isDDCId(instanceId) { + return DDCNotSupportError() + } + rdsArgs := &rds.ModifyPublicAccessArgs{PublicAccess: args.PublicAccess} + err := c.rdsClient.ModifyPublicAccess(instanceId, rdsArgs) + return err +} + +// GetBackupList - get backup list of the instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetBackupListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupList(instanceId string, args *GetBackupListArgs) (*GetBackupListResult, error) { + + var result *GetBackupListResult + var err error + if isDDCId(instanceId) { + result, err = c.ddcClient.GetBackupList(instanceId, args) + } else { + rdsArgs := &rds.GetBackupListArgs{} + // copy请求参数 + err = ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return nil, err + } + var rdsRes *rds.GetBackupListResult + rdsRes, err = c.rdsClient.GetBackupList(instanceId, rdsArgs) + // 转换返回结果 + if rdsRes != nil { + result = &GetBackupListResult{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + } + } + + return result, err +} + +// GetZoneList - list all zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *GetZoneListResult: result of the zone list +// - error: nil if success otherwise the specific error +func (c *Client) GetZoneList(productType string) (*GetZoneListResult, error) { + if isDDC(productType) { + return c.ddcClient.GetZoneList() + } + rdsRes, err := c.rdsClient.GetZoneList() + if err != nil { + return nil, err + } + result := &GetZoneListResult{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + if err != nil { + return nil, err + } + return result, err +} + +// ListsSubnet - list all Subnets +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list all subnets, not necessary +// +// RETURNS: +// - *ListSubnetsResult: result of the subnet list +// - error: nil if success otherwise the specific error +func (c *Client) ListSubnets(args *ListSubnetsArgs, productType string) (*ListSubnetsResult, error) { + if isDDC(productType) { + return c.ddcClient.ListSubnets(args) + } + rdsArgs := &rds.ListSubnetsArgs{} + err := ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return nil, err + } + rdsRes, err := c.rdsClient.ListSubnets(rdsArgs) + if err != nil { + return nil, err + } + result := &ListSubnetsResult{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + return result, err +} + +// GetSecurityIps - get all SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *GetSecurityIpsResult: all security IP +// - error: nil if success otherwise the specific error +func (c *Client) GetSecurityIps(instanceId string) (*GetSecurityIpsResult, error) { + if isDDCId(instanceId) { + return c.ddcClient.GetSecurityIps(instanceId) + } + rdsRes, err := c.rdsClient.GetSecurityIps(instanceId) + if err != nil { + return nil, err + } + result := &GetSecurityIpsResult{} + err = ddc_util.SimpleCopyProperties(result, rdsRes) + return result, err +} + +// UpdateSecurityIps - update SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Etag: get latest etag by GetSecurityIps +// - Args: all SecurityIps +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSecurityIps(instanceId, Etag string, args *UpdateSecurityIpsArgs) error { + if isDDCId(instanceId) { + return c.ddcClient.UpdateSecurityIps(instanceId, args) + } + rdsArgs := &rds.UpdateSecurityIpsArgs{SecurityIps: args.SecurityIps} + err := c.rdsClient.UpdateSecurityIps(instanceId, Etag, rdsArgs) + return err +} + +// ListParameters - list all parameters of a RDS instance +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListParametersResult: the result of list all parameters +// - error: nil if success otherwise the specific error +func (c *Client) ListParameters(instanceId string) (*ListParametersResult, error) { + if isDDCId(instanceId) { + return c.ddcClient.ListParameters(instanceId) + } + rdsRes, err := c.rdsClient.ListParameters(instanceId) + result := &ListParametersResult{} + err1 := ddc_util.SimpleCopyProperties(result, rdsRes) + if err1 != nil { + return nil, err1 + } + // 兼容rds处理 + if result.Parameters != nil && len(result.Parameters) > 0 { + for i, parameter := range result.Parameters { + result.Parameters[i].IsDynamic = parameter.Dynamic == "true" + result.Parameters[i].ISModifiable = parameter.Modifiable == "true" + } + } + return result, err +} + +// UpdateParameter - update Parameter +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Etag: get latest etag by ListParameters +// - Args: *UpdateParameterArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateParameter(instanceId, Etag string, args *UpdateParameterArgs) (*ProducedMaintainTaskResult, error) { + if isDDCId(instanceId) { + return c.ddcClient.UpdateParameter(instanceId, args) + } + rdsArgs := &rds.UpdateParameterArgs{} + err1 := ddc_util.SimpleCopyProperties(rdsArgs, args) + if err1 != nil { + return nil, err1 + } + err := c.rdsClient.UpdateParameter(instanceId, Etag, rdsArgs) + return nil, err +} + +// CreateDeploySet - create a deploy set +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateDeploySet(poolId string, args *CreateDeployRequest) (*CreateDeployResult, error) { + return c.ddcClient.CreateDeploySet(poolId, args) +} + +// UpdateDeploySet - create a deploy set +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateDeploySet(poolId, deployId string, args *UpdateDeployRequest) error { + return c.ddcClient.UpdateDeploySet(poolId, deployId, args) +} + +// ListDeploySets - list all deploy sets +// RETURNS: +// - *ListResultWithMarker: the result of list deploy sets with marker +// - error: nil if success otherwise the specific error +func (c *Client) ListDeploySets(poolId string, marker *Marker) (*ListDeploySetResult, error) { + return c.ddcClient.ListDeploySets(poolId, marker) +} + +// ListPool - list current pools +// RETURNS: +// - *ListResultWithMarker: the result of list hosts with marker +// - error: nil if success otherwise the specific error +func (c *Client) ListPool(marker *Marker, productType string) (*ListPoolResult, error) { + if !isDDC(productType) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListPool(marker) +} + +// GetDeploySet - get details of the deploy set +// +// PARAMS: +// - poolId: the id of the pool +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *DeploySet: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *Client) GetDeploySet(poolId string, deploySetId string) (*DeploySet, error) { + return c.ddcClient.GetDeploySet(poolId, deploySetId) +} + +// DeleteDeploySet - delete a deploy set +// +// PARAMS: +// - poolId: the id of the pool +// - deploySetId: the id of the deploy set +// - clientToken: idempotent token, an ASCII string no longer than 64 bits +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDeploySet(poolId string, deploySetId string) error { + return c.ddcClient.DeleteDeploySet(poolId, deploySetId) +} + +// CreateBackup - create backup of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateBackup(instanceId string) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.CreateBackup(instanceId) +} + +// ModifyBackupPolicy - update backupPolicy +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Args: the specific rds Instance's BackupPolicy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyBackupPolicy(instanceId string, args *BackupPolicy) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.ModifyBackupPolicy(instanceId, args) +} + +// GetBackupDetail - get details of the instance'Backup +// +// PARAMS: +// - instanceId: the id of the instance +// - snapshotId: the id of the backup +// +// RETURNS: +// - *BackupDetailResult: the detail of the backup +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupDetail(instanceId string, snapshotId string) (*BackupDetailResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetBackupDetail(instanceId, snapshotId) +} + +// GetBinlogList - get backup list of the instance +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *BinlogListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *Client) GetBinlogList(instanceId string, datetime string) (*BinlogListResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetBinlogList(instanceId, datetime) +} + +// GetBinlogDetail - get details of the instance'Binlog +// +// PARAMS: +// - instanceId: the id of the instance +// - binlog: the id of the binlog +// +// RETURNS: +// - *BinlogDetailResult: the detail of the binlog +// - error: nil if success otherwise the specific error +func (c *Client) GetBinlogDetail(instanceId string, binlog string) (*BinlogDetailResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetBinlogDetail(instanceId, binlog) +} + +// SwitchInstance - main standby switching of the instance +// +// PARAMS: +// - instanceId: the id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SwitchInstance(instanceId string, args *SwitchArgs) (*ProducedMaintainTaskResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.SwitchInstance(instanceId, args) +} + +// CreateDatabase - create a database with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateDatabase(instanceId string, args *CreateDatabaseArgs) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.CreateDatabase(instanceId, args) +} + +// DeleteDatabase - delete an database of a DDC instance +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - dbName: the specific database's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDatabase(instanceId, dbName string) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.DeleteDatabase(instanceId, dbName) +} + +// UpdateDatabaseRemark - update a database remark with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - dbName: the specific accountName +// - args: the arguments to update a database remark +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateDatabaseRemark(instanceId string, dbName string, args *UpdateDatabaseRemarkArgs) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.UpdateDatabaseRemark(instanceId, dbName, args) +} + +// GetDatabase - get an database of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - dbName: the specific database's name +// +// RETURNS: +// - *Database: the database's meta +// - error: nil if success otherwise the specific error +func (c *Client) GetDatabase(instanceId, dbName string) (*Database, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetDatabase(instanceId, dbName) +} + +// ListDatabase - list all database of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *ListDatabaseResult: the result of list all database, contains all databases' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListDatabase(instanceId string) (*ListDatabaseResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListDatabase(instanceId) +} + +// GetTableAmount - query amount of tables +// +// PARAMS: +// - args: the specific ddc instanceId, dbName and search pattern +// +// RETURNS: +// - *TableAmountResult: the size of the table that meets the criteria +// - error: nil if success otherwise the specific error +func (c *Client) GetTableAmount(args *GetTableAmountArgs) (*TableAmountResult, error) { + return c.ddcClient.GetTableAmount(args) +} + +// GetDatabaseDiskUsage - get the disk footprint and the remaining space for database +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *ListDatabaseResult: the disk footprint and the remaining space for database +// - error: nil if success otherwise the specific error +func (c *Client) GetDatabaseDiskUsage(instanceId, dbName string) (*DatabaseDiskUsageResult, error) { + return c.ddcClient.GetDatabaseDiskUsage(instanceId, dbName) +} + +// GetRecoverableDateTime - get a list of recoverable times +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// +// RETURNS: +// - *GetRecoverableDateTimeResult: the result of list all recoverable datetimes +// - error: nil if success otherwise the specific error +func (c *Client) GetRecoverableDateTime(instanceId string) (*GetRecoverableDateTimeResult, error) { + return c.ddcClient.GetRecoverableDateTime(instanceId) +} + +// RecoverToSourceInstanceByDatetime - recover database or tables for the specific instance by a datetime +// +// PARAMS: +// - instanceId: the specific ddc Instance's ID +// - args: recover instance args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecoverToSourceInstanceByDatetime(instanceId string, args *RecoverInstanceArgs) (*MaintainTaskIdResult, error) { + return c.ddcClient.RecoverToSourceInstanceByDatetime(instanceId, args) +} + +// UpdateAccountPassword - update a account password with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPassword(instanceId string, accountName string, args *UpdateAccountPasswordArgs) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.UpdateAccountPassword(instanceId, accountName, args) +} + +// UpdateAccountDesc - update a account desc with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account remark +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountDesc(instanceId string, accountName string, args *UpdateAccountDescArgs) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.UpdateAccountDesc(instanceId, accountName, args) +} + +// UpdateAccountPrivileges - update a account privileges with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific accountName +// - args: the arguments to update a account privileges +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPrivileges(instanceId string, accountName string, args *UpdateAccountPrivilegesArgs) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.UpdateAccountPrivileges(instanceId, accountName, args) +} + +// ListRoGroup - list all roGroups of a DDC instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListRoGroupResult: All roGroups of the current instance +// - error: nil if success otherwise the specific error +func (c *Client) ListRoGroup(instanceId string) (*ListRoGroupResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListRoGroup(instanceId) +} + +// ListVpc - list all Vpc +// +// PARAMS: +// RETURNS: +// - *ListVpc: All vpc of +// - error: nil if success otherwise the specific error +func (c *Client) ListVpc(productType string) (*[]VpcVo, error) { + if !isDDC(productType) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListVpc() +} + +// autoRenew - create autoRenew +// +// PARAMS: +// - Args: *autoRenewArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AutoRenew(args *AutoRenewArgs, productType string) error { + if isDDC(productType) { + return DDCNotSupportError() + } + // 实例列表不能为空 + if len(args.InstanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + rdsArgs := &rds.AutoRenewArgs{} + err := ddc_util.SimpleCopyProperties(rdsArgs, args) + if err != nil { + return err + } + return c.rdsClient.AutoRenew(rdsArgs) +} + +// GetMaintenTime - get details of the maintenTime +// +// PARAMS: +// - poolId: the id of the pool +// - cli: the client agent which can perform sending request +// - deploySetId: the id of the deploy set +// +// RETURNS: +// - *DeploySet: the detail of the deploy set +// - error: nil if success otherwise the specific error +func (c *Client) GetMaintainTime(instanceId string) (*MaintainTime, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetMaintainTime(instanceId) +} + +// UpdateMaintenTime - update UpdateMaintenTime of instance +// +// PARAMS: +// - body: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateMaintainTime(instanceId string, args *MaintainTime) error { + if args == nil { + return fmt.Errorf("unset args") + } + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.UpdateMaintainTime(instanceId, args) +} + +// ListRecycleInstances - list all instances in recycler with marker +// +// PARAMS: +// - marker: marker page +// +// RETURNS: +// - *RecyclerInstanceList: the result of instances in recycler +// - error: nil if success otherwise the specific error +func (c *Client) ListRecycleInstances(marker *Marker, productType string) (*RecyclerInstanceList, error) { + if !isDDC(productType) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListRecycleInstances(marker) +} + +// RecoverRecyclerInstances - batch recover instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to recover +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecoverRecyclerInstances(instanceIds []string) (*OrderIdResponse, error) { + if instanceIds == nil || len(instanceIds) < 1 { + return nil, fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return nil, fmt.Errorf("the instanceIds length max value is 10") + } + + for _, id := range instanceIds { + if !isDDCId(id) { + return nil, RDSNotSupportError() + } + } + return c.ddcClient.RecoverRecyclerInstances(instanceIds) +} + +// DeleteRecyclerInstances - batch delete instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecyclerInstances(instanceIds []string) error { + if instanceIds == nil || len(instanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return fmt.Errorf("the instanceIds length max value is 10") + } + + for _, id := range instanceIds { + if !isDDCId(id) { + return RDSNotSupportError() + } + } + return c.ddcClient.DeleteRecyclerInstances(instanceIds) +} + +// ListSecurityGroupByVpcId - list security groups by vpc id +// +// PARAMS: +// - vpcId: id of vpc +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroupByVpcId(vpcId string) (*[]SecurityGroup, error) { + return c.ddcClient.ListSecurityGroupByVpcId(vpcId) +} + +// ListSecurityGroupByInstanceId - list security groups by instance id +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *ListSecurityGroupResult: list secrity groups result of instance +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroupByInstanceId(instanceId string) (*ListSecurityGroupResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListSecurityGroupByInstanceId(instanceId) +} + +// BindSecurityGroups - bind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + for _, id := range args.InstanceIds { + if !isDDCId(id) { + return RDSNotSupportError() + } + } + return c.ddcClient.BindSecurityGroups(args) +} + +// UnBindSecurityGroups - unbind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + for _, id := range args.InstanceIds { + if !isDDCId(id) { + return RDSNotSupportError() + } + } + return c.ddcClient.UnBindSecurityGroups(args) +} + +// ReplaceSecurityGroups - replace SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ReplaceSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + for _, id := range args.InstanceIds { + if !isDDCId(id) { + return RDSNotSupportError() + } + } + return c.ddcClient.ReplaceSecurityGroups(args) +} + +// ListLogByInstanceId - list error or slow logs of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *[]Log:logs of instance +// - error: nil if success otherwise the specific error +func (c *Client) ListLogByInstanceId(instanceId string, args *ListLogArgs) (*[]Log, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.ListLogByInstanceId(instanceId, args) +} + +// GetLogById - list log's detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Log:log's detail of instance +// - error: nil if success otherwise the specific error +func (c *Client) GetLogById(instanceId, logId string, args *GetLogArgs) (*LogDetail, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetLogById(instanceId, logId, args) +} + +// LazyDropCreateHardLink - create a hard link for specified large table +// +// PARAMS: +// - instanceId: id of instance +// - dbName: name of database +// - tableName: name of table +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) LazyDropCreateHardLink(instanceId, dbName, tableName string) error { + if !isDDCId(instanceId) { + return RDSNotSupportError() + } + return c.ddcClient.LazyDropCreateHardLink(instanceId, dbName, tableName) +} + +// LazyDropDeleteHardLink - delete the hard link for specified large table +// +// PARAMS: +// - instanceId: id of instance +// - dbName: name of database +// - tableName: name of table +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) LazyDropDeleteHardLink(instanceId, dbName, tableName string) (*MaintainTaskIdResult, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.LazyDropDeleteHardLink(instanceId, dbName, tableName) +} + +// GetMachineInfo - get machine detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *MachineInfo:info of machine resource +// - error: nil if success otherwise the specific error +func (c *Client) GetMachineInfo(instanceId string) (*MachineInfo, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetMachineInfo(instanceId) +} + +// GetDisk - get disk detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Disk:disk of instance +// - error: nil if success otherwise the specific error +func (c *Client) GetDisk(instanceId string) (*Disk, error) { + if !isDDCId(instanceId) { + return nil, RDSNotSupportError() + } + return c.ddcClient.GetDisk(instanceId) +} + +// GetResidual - get residual of pool +// +// PARAMS: +// - poolId: id of pool +// - zoneName: the zone name +// +// RETURNS: +// - *GetResidualResult:residual of pool +// - error: nil if success otherwise the specific error +func (c *Client) GetResidual(poolId string) (*GetResidualResult, error) { + return c.ddcClient.GetResidual(poolId) +} + +// GetFlavorCapacity - get flavor capacity of pool +// +// PARAMS: +// - poolId: id of pool +// - args: request params +// +// RETURNS: +// - *GetResidualResult:get flavor capacity of pool +// - error: nil if success otherwise the specific error +func (c *Client) GetFlavorCapacity(poolId string, args *GetFlavorCapacityArgs) (*GetFlavorCapacityResult, error) { + return c.ddcClient.GetFlavorCapacity(poolId, args) +} + +// KillSession - start kill session tasks +// +// PARAMS: +// - instanceId: id of the instance +// - args: instance role and sessionIds +// +// RETURNS: +// - *KillSessionResult: the response of kill session task id +// - error: nil if success otherwise the specific error +func (c *Client) KillSession(instanceId string, args *KillSessionArgs) (*KillSessionResult, error) { + return c.ddcClient.KillSession(instanceId, args) +} + +// GetKillSessionTask - get kill session tasks by taskId +// +// PARAMS: +// - instanceId: the specific instanceId of ddc +// - taskId: kill session returned id +// +// RETURNS: +// - *GetKillSessionTaskResult: the response of kill session task +// - error: nil if success otherwise the specific error +func (c *Client) GetKillSessionTask(instanceId string, taskId int) (*GetKillSessionTaskResult, error) { + return c.ddcClient.GetKillSessionTask(instanceId, taskId) +} + +// GetMaintainTaskList - get maintain tasks by taskId +// +// PARAMS: +// RETURNS: +// - *ListMaintainTaskResult: the response of maintain tasks +// - error: nil if success otherwise the specific error +func (c *Client) GetMaintainTaskList(args *GetMaintainTaskListArgs) (*ListMaintainTaskResult, error) { + return c.ddcClient.GetMaintainTaskList(args) +} + +// GetTaskDetail - get maintain task detail by taskId +// +// PARAMS: +// RETURNS: +// - *MaintainTaskDetailList: the response of maintain task detail +// - error: nil if success otherwise the specific error +func (c *Client) GetMaintainTaskDetail(taskIds string) (*MaintainTaskDetailList, error) { + return c.ddcClient.GetMaintainTaskDetail(taskIds) +} + +// ExecuteMaintainTaskImmediately - execute maintain task immediately +// +// PARAMS: +// - taskId: id of the task +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ExecuteMaintainTaskImmediately(taskId string) error { + return c.ddcClient.ExecuteMaintainTaskImmediately(taskId) +} + +// CancelMaintainTask - cancel maintain task +// +// PARAMS: +// - taskId: id of the task +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CancelMaintainTask(taskId string) error { + return c.ddcClient.CancelMaintainTask(taskId) +} + +// GetAccessLog - get access logs's download info by date +// +// PARAMS: +// RETURNS: +// - *AccessLog: the access logs's download info +// - error: nil if success otherwise the specific error +func (c *Client) GetAccessLog(date string) (*AccessLog, error) { + return c.ddcClient.GetAccessLog(date) +} + +// GetErrorLogs - get error logs +// +// PARAMS: +// RETURNS: +// - *ErrorLogsResponse: the error logs +// - error: nil if success otherwise the specific error +func (c *Client) GetErrorLogs(args *GetErrorLogsArgs) (*ErrorLogsResponse, error) { + return c.ddcClient.GetErrorLogs(args) +} + +// GetSlowLogs - get slow logs +// +// PARAMS: +// RETURNS: +// - *SlowLogsResponse: the slow logs +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowLogs(args *GetSlowLogsArgs) (*SlowLogsResponse, error) { + return c.ddcClient.GetSlowLogs(args) +} + +// GetInstanceBackupStatus - get instance backup status and backup start time +// +// PARAMS: +// RETURNS: +// - *GetBackupStatusResponse: the response of backup status +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceBackupStatus(instanceId string) (*GetBackupStatusResponse, error) { + return c.ddcClient.GetInstanceBackupStatus(instanceId) +} + +// InstanceVersionRollBack - rollback instance version from 5.7 to 5.6 +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to set WaitSwitch +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceVersionRollBack(instanceId string, args *InstanceVersionRollBackArg) (*MaintainTaskIdResult, error) { + return c.ddcClient.InstanceVersionRollBack(instanceId, args) +} + +// InstanceVersionUpgrade - upgrade instance version from 5.6 to 5.7 +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to set IsUpgradeNow +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceVersionUpgrade(instanceId string, args *InstanceVersionUpgradeArg) (*MaintainTaskIdResult, error) { + return c.ddcClient.InstanceVersionUpgrade(instanceId, args) +} + +// GetInstanceSyncDelay - get readonly instance syncDelay and syncStatus. +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *InstanceSyncDelayResponse: the response of syncDelay +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceSyncDelay(instanceId string) (*InstanceSyncDelayResponse, error) { + return c.ddcClient.GetInstanceSyncDelay(instanceId) +} + +// InstanceSyncDelayReplication - start or stop readonly instance syncDelay. +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *InstanceSyncDelayReplicationResponse: the response of success +// - error: nil if success otherwise the specific error +func (c *Client) InstanceSyncDelayReplication(instanceId string, args *InstanceSyncDelayReplicationArg) (*InstanceSyncDelayReplicationResponse, error) { + return c.ddcClient.InstanceSyncDelayReplication(instanceId, args) +} + +// SnapshotAccessDetail - get snapshot access detail +// +// PARAMS: +// - args: the arguments to get snapshot access detail +// +// RETURNS: +// - *AccessDetail +// - error: nil if success otherwise the specific error +func (c *Client) SnapshotAccessDetail(args *AccessDetailArgs) (*BackupAccessDetail, error) { + + return c.ddcClient.SnapshotAccessDetail(args) +} + +// BinlogAccessDetail - get snapshot access detail +// +// PARAMS: +// - args: the arguments to get snapshot access detail +// +// RETURNS: +// - *AccessDetail +// - error: nil if success otherwise the specific error +func (c *Client) BinlogAccessDetail(args *AccessDetailArgs) (*BackupAccessDetail, error) { + + return c.ddcClient.BinlogAccessDetail(args) +} diff --git a/bce-sdk-go/services/ddc/v2/model.go b/bce-sdk-go/services/ddc/v2/model.go new file mode 100644 index 0000000..39c4f87 --- /dev/null +++ b/bce-sdk-go/services/ddc/v2/model.go @@ -0,0 +1,1237 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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 ddcrds + +const ( + STANDARD string = "Standard" + SINGLETON string = "Singleton" +) + +type Integer *int + +type TagModel struct { + TagKey string `json:"tagKey"` + TagValue string `json:"tagValue"` +} + +type CreateInstanceArgs struct { + ClientToken string `json:"-"` + InstanceType string `json:"instanceType,omitempty"` + Number int `json:"number,omitempty"` + Instance CreateInstance `json:"instance,omitempty"` +} + +type CreateRdsArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + Engine string `json:"engine,omitempty"` + EngineVersion string `json:"engineVersion,omitempty"` + Category string `json:"category,omitempty"` + CpuCount int `json:"cpuCount,omitempty"` + MemoryCapacity float64 `json:"memoryCapacity,omitempty"` + VolumeCapacity int `json:"volumeCapacity,omitempty"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []TagModel `json:"tags,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + DeployId string `json:"deployId,omitempty"` + PoolId string `json:"poolId"` + SyncMode string `json:"syncMode"` +} + +type CreateReadReplicaArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing,omitempty"` + PurchaseCount int `json:"purchaseCount,omitempty"` + SourceInstanceId string `json:"sourceInstanceId"` + InstanceName string `json:"instanceName,omitempty"` + CpuCount int `json:"cpuCount,omitempty"` + MemoryCapacity float64 `json:"memoryCapacity,omitempty"` + VolumeCapacity int `json:"volumeCapacity,omitempty"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []TagModel `json:"tags,omitempty"` + DeployId string `json:"deployId,omitempty"` + PoolId string `json:"poolId,omitempty"` + RoGroupId string `json:"roGroupId,omitempty"` + EnableDelayOff string `json:"enableDelayOff,omitempty"` + DelayThreshold string `json:"delayThreshold,omitempty"` + LeastInstanceAmount string `json:"leastInstanceAmount,omitempty"` + RoGroupWeight string `json:"roGroupWeight,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` +} + +type Instance struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + Category string `json:"category"` + InstanceStatus string `json:"instanceStatus"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"allocatedMemoryInGB"` + VolumeCapacity int `json:"allocatedStorageInGB"` + NodeAmount int `json:"nodeAmount"` + UsedStorage float64 `json:"usedStorageInGB"` + PublicAccessStatus string `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + Endpoint Endpoint `json:"endpoint"` + SyncMode string `json:"syncMode"` + BackupPolicy BackupPolicy `json:"backupPolicy"` + Region string `json:"region"` + InstanceType string `json:"type"` + SourceInstanceId string `json:"sourceInstanceId"` + SourceRegion string `json:"sourceRegion"` + ZoneNames []string `json:"zoneNames"` + VpcId string `json:"vpcId"` + Subnets []Subnet `json:"subnets"` + Topology Topology `json:"topology"` + PaymentTiming string `json:"paymentTiming"` + + PubliclyAccessible bool `json:"publiclyAccessible"` + RoGroupList []RoGroup `json:"roGroupList"` + NodeMaster NodeInfo `json:"nodeMaster"` + NodeSlave NodeInfo `json:"nodeSlave"` + NodeReadReplica NodeInfo `json:"nodeReadReplica"` + DeployId string `json:"deployId"` + LongBBCId string `json:"longBBCId"` + HostName string `json:"hostname,omitempty"` + InstanceTopoForReadonly InstanceTopoForReadonly `json:"instanceTopoForReadonly,omitempty"` + AutoRenewRule *AutoRenewRule `json:"autoRenewRule,omitempty"` +} + +type AutoRenewRule struct { + RenewTime int `json:"renewTime"` + RenewTimeUnit string `json:"renewTimeUnit"` +} + +func (instance *Instance) ProductType() string { + if isDDCId(instance.InstanceId) { + return "ddc" + } + return "rds" +} + +type SubnetMap struct { + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation Reservation `json:"reservation,omitempty"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength,omitempty"` + ReservationTimeUnit string `json:"reservationTimeUnit,omitempty"` +} + +type CreateResult struct { + OrderId string `json:"orderId"` + InstanceIds []string `json:"instanceIds"` +} + +type InstanceModelResult struct { + Instance InstanceModel `json:"instance"` +} + +type CreateInstance struct { + InstanceId string `json:"instanceId,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + SourceInstanceId string `json:"sourceInstanceId,omitempty"` + Engine string `json:"engine,omitempty"` + EngineVersion string `json:"engineVersion,omitempty"` + CpuCount int `json:"cpuCount,omitempty"` + AllocatedMemoryInGB int `json:"allocatedMemoryInGB,omitempty"` + AllocatedStorageInGB int `json:"allocatedStorageInGB,omitempty"` + AZone string `json:"azone,omitempty"` + VpcId string `json:"vpcId,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + DiskIoType string `json:"diskIoType,omitempty"` + DeployId string `json:"deployId,omitempty"` + PoolId string `json:"poolId,omitempty"` + RoGroupId string `json:"roGroupId,omitempty"` + IsBalanceRoLoad Integer `json:"isBalanceRoLoad,omitempty"` + EnableDelayOff Integer `json:"enableDelayOff,omitempty"` + DelayThreshold Integer `json:"delayThreshold,omitempty"` + LeastInstanceAmount Integer `json:"leastInstanceAmount,omitempty"` + RoGroupWeight Integer `json:"roGroupWeight,omitempty"` + IsDirectPay bool `json:"IsDirectPay,omitempty"` + Billing Billing `json:"billing,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Category string `json:"category,omitempty"` + Tags []TagModel `json:"tags,omitempty"` + SyncMode string `json:"syncMode,omitempty"` +} + +type Pool struct { + CPUQuotaTotal int `json:"cpuQuotaTotal"` + CPUQuotaUsed int `json:"cpuQuotaUsed"` + CreateTime string `json:"createTime"` + DeployMethod string `json:"deployMethod"` + DiskQuotaTotal int `json:"diskQuotaTotal"` + DiskQuotaUsed int `json:"diskQuotaUsed"` + Engine string `json:"engine"` + Hosts []Host `json:"hosts"` + MaxMemoryUsedRatio string `json:"maxMemoryUsedRatio"` + MemoryQuotaTotal int `json:"memoryQuotaTotal"` + MemoryQuotaUsed int `json:"memoryQuotaUsed"` + PoolID string `json:"poolId"` + PoolName string `json:"poolName"` + VpcID string `json:"vpcId"` +} + +type Host struct { + Containers []Container `json:"containers"` + Flavor Flavor `json:"flavor"` + CPUQuotaTotal int `json:"cpuQuotaTotal"` + CPUQuotaUsed int `json:"cpuQuotaUsed"` + DeploymentStatus string `json:"deploymentStatus"` + DiskQuotaTotal int `json:"diskQuotaTotal"` + DiskQuotaUsed int `json:"diskQuotaUsed"` + HostID string `json:"hostId"` + HostName string `json:"hostName"` + ImageType string `json:"imageType"` + MemoryQuotaTotal int64 `json:"memoryQuotaTotal"` + MemoryQuotaUsed int64 `json:"memoryQuotaUsed"` + PnetIP string `json:"pnetIp"` + Role string `json:"role"` + Status string `json:"status"` + SubnetID string `json:"subnetId"` + VnetIP string `json:"vnetIp"` + VpcID string `json:"vpcId"` + Zone string `json:"zone"` +} + +type OperateHostRequest struct { + Action string `json:"action"` +} + +type Flavor struct { + CPUCount int `json:"cpuCount"` + CPUType string `json:"cpuType"` + Disk int `json:"disk"` + FlavorID string `json:"flavorId"` + MemoryCapacityInGB int `json:"memoryCapacityInGB"` +} + +type Container struct { + ContainerID string `json:"containerId"` + DeployID string `json:"deployId"` + DeployName string `json:"deployName"` + Engine string `json:"engine"` + HostID string `json:"hostId"` + HostName string `json:"hostName"` + PoolName string `json:"poolName"` + Role string `json:"role"` + Zone string `json:"zone"` +} + +type DeploySet struct { + CreateTime string `json:"createTime"` + DeployID string `json:"deployId"` + DeployName string `json:"deployName"` + Instances []string `json:"instances"` + PoolID string `json:"poolId"` + Strategy string `json:"strategy"` + CentralizeThreshold int `json:"centralizeThreshold"` +} + +type CreateDeployRequest struct { + ClientToken string `json:"-"` + DeployName string `json:"deployName"` + Strategy string `json:"strategy"` + CentralizeThreshold int `json:"centralizeThreshold"` +} + +type CreateDeployResult struct { + DeployID string `json:"deployId"` +} + +type UpdateDeployRequest struct { + ClientToken string `json:"-"` + Strategy string `json:"strategy"` + CentralizeThreshold int `json:"centralizeThreshold"` +} + +type Marker struct { + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListResultWithMarker struct { + IsTruncated bool `json:"isTruncated"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` +} + +type ListPoolResult struct { + ListResultWithMarker + Result []Pool `json:"result"` +} + +type ListHostResult struct { + ListResultWithMarker + Result []Host `json:"result"` +} + +type ListDeploySetResult struct { + ListResultWithMarker + Result []DeploySet `json:"result"` +} + +type InstanceModel struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + InstanceStatus string `json:"instanceStatus"` + CpuCount int `json:"cpuCount"` + AllocatedMemoryInGB float64 `json:"allocatedMemoryInGB"` + AllocatedStorageInGB int `json:"allocatedStorageInGB"` + NodeAmount int `json:"nodeAmount"` + UsedStorageInGB float64 `json:"usedStorageInGB"` + PublicAccessStatus bool `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + Endpoint Endpoint `json:"endpoint"` + SyncMode string `json:"syncMode"` + BackupPolicy BackupPolicy `json:"backupPolicy"` + Region string `json:"region"` + InstanceType string `json:"instanceType"` + SourceInstanceId string `json:"sourceInstanceId"` + SourceRegion string `json:"sourceRegion"` + ZoneNames []string `json:"zoneNames"` + VpcId string `json:"vpcId"` + Subnets []Subnet `json:"subnets"` + NodeMaster NodeInfo `json:"nodeMaster"` + NodeSlave NodeInfo `json:"nodeSlave"` + NodeReadReplica NodeInfo `json:"nodeReadReplica"` + DeployId string `json:"deployId"` + Topology Topology `json:"topology"` + DiskType string `json:"diskType"` + Type string `json:"type"` + ApplicationType string `json:"applicationType"` + RoGroupList []RoGroup `json:"roGroupList"` + PaymentTiming string `json:"paymentTiming"` + Category string `json:"category"` + LongBBCId string `json:"longBBCId"` + InstanceTopoForReadonly InstanceTopoForReadonly `json:"instanceTopoForReadonly,omitempty"` + AutoRenewRule *AutoRenewRule `json:"autoRenewRule,omitempty"` +} +type TopoInstance struct { + InstanceID string `json:"instanceId,omitempty"` + SyncMode string `json:"syncMode,omitempty"` + MasterSlaveDelay int `json:"masterSlaveDelay,omitempty"` + Type string `json:"type,omitempty"` + Region string `json:"region,omitempty"` + RoGroupID string `json:"roGroupId,omitempty"` + ZoneName string `json:"zoneName,omitempty"` + InstanceStatus string `json:"instanceStatus,omitempty"` +} +type InstanceTopoForReadonly struct { + ReadReplica []TopoInstance `json:"readReplica,omitempty"` + Master []TopoInstance `json:"master,omitempty"` +} + +type SubnetVo struct { + Name string `json:"name"` + SubnetId string `json:"subnetId"` + Az string `json:"az"` + Cidr string `json:"cidr"` + ShortId string `json:"shortId"` +} + +type RoGroup struct { + RoGroupID string `json:"roGroupId"` + RoGroupName string `json:"roGroupName"` + VnetIP string `json:"vnetIp"` + IsBalanceRoLoad int `json:"isBalanceRoLoad"` + EnableDelayOff int `json:"enableDelayOff"` + DelayThreshold int `json:"delayThreshold"` + LeastInstanceAmount int `json:"leastInstanceAmount"` + ReplicaList []Replica `json:"replicaList"` +} + +type UpdateRoGroupArgs struct { + RoGroupName string `json:"roGroupName,omitempty"` + IsBalanceRoLoad string `json:"isBalanceRoLoad,omitempty"` + EnableDelayOff string `json:"enableDelayOff,omitempty"` + DelayThreshold string `json:"delayThreshold,omitempty"` + LeastInstanceAmount string `json:"leastInstanceAmount,omitempty"` + MasterDelay string `json:"masterDelay,omitempty"` +} + +type UpdateRoGroupRealArgs struct { + RoGroupName string `json:"roGroupName,omitempty"` + IsBalanceRoLoad Integer `json:"isBalanceRoLoad,omitempty"` + EnableDelayOff Integer `json:"enableDelayOff,omitempty"` + DelayThreshold Integer `json:"delayThreshold,omitempty"` + LeastInstanceAmount Integer `json:"leastInstanceAmount,omitempty"` + MasterDelay Integer `json:"masterDelay,omitempty"` +} + +type UpdateRoGroupWeightArgs struct { + RoGroupName string `json:"roGroupName,omitempty"` + EnableDelayOff string `json:"enableDelayOff,omitempty"` + DelayThreshold string `json:"delayThreshold,omitempty"` + LeastInstanceAmount string `json:"leastInstanceAmount,omitempty"` + IsBalanceRoLoad string `json:"isBalanceRoLoad,omitempty"` + MasterDelay string `json:"masterDelay,omitempty"` + ReplicaList []ReplicaWeight `json:"replicaList,omitempty"` +} + +type UpdateRoGroupWeightRealArgs struct { + RoGroupName string `json:"roGroupName,omitempty"` + EnableDelayOff Integer `json:"enableDelayOff,omitempty"` + DelayThreshold Integer `json:"delayThreshold,omitempty"` + LeastInstanceAmount Integer `json:"leastInstanceAmount,omitempty"` + IsBalanceRoLoad Integer `json:"isBalanceRoLoad,omitempty"` + MasterDelay Integer `json:"masterDelay,omitempty"` + ReplicaList []ReplicaWeight `json:"replicaList,omitempty"` +} + +type ReplicaWeight struct { + InstanceId string `json:"instanceId"` + Weight int `json:"weight"` +} + +type Replica struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Status string `json:"status"` + RoGroupWeight int `json:"roGroupWeight"` +} + +type NodeInfo struct { + Id string `json:"id"` + Azone string `json:"azone"` + SubnetId string `json:"subnetId"` + Cidr string `json:"cidr"` + Name string `json:"name"` + HostName string `json:"hostname"` +} + +type Subnet struct { + Name string `json:"name"` + LongId string `json:"subnetId"` + ZoneName string `json:"zoneName"` + Cidr string `json:"cidr"` + ShortId string `json:"shortId"` + VpcId string `json:"vpcId"` + VpcShortId string `json:"vpcShortId"` + Az string `json:"az"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` +} + +type Endpoint struct { + Address string `json:"address"` + Port int `json:"port"` + VnetIp string `json:"vnetIp"` + VnetIpBackup string `json:"vnetIpBackup"` + InetIp string `json:"inetIp"` +} + +type BackupPolicy struct { + BackupDays string `json:"backupDays"` + BackupTime string `json:"backupTime"` + Persistent bool `json:"persistent"` + ExpireInDaysStr string `json:"expireInDaysStr"` + FreeSpaceInGB int `json:"freeSpaceInGb"` + + ExpireInDaysInt int `json:"expireInDays"` +} + +type Topology struct { + Rdsproxy []string `json:"rdsproxy"` + Master []string `json:"master"` + ReadReplica []string `json:"readReplica"` +} + +type DeleteDdcArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type UpdateInstanceNameArgs struct { + InstanceName string `json:"instanceName"` +} + +type ListRdsResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Instances []Instance `json:"result"` +} + +type ListRdsArgs struct { + Marker string + MaxKeys int +} + +type ListPageArgs struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Filters []Filter `json:"filters"` +} +type Filter struct { + KeywordType string `json:"keywordType"` + Keyword string `json:"keyword"` +} + +type ListPageResult struct { + Page Page `json:"page"` +} + +type Page struct { + Result []Instance `json:"result"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type GetBackupListResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Backups []Snapshot `json:"snapshots"` + FreeSpaceInMB int64 `json:"freeSpaceInMB"` + UsedSpaceInMB int64 `json:"usedSpaceInMB"` +} + +type GetZoneListResult struct { + Zones []ZoneName `json:"zones"` +} + +type ZoneName struct { + ZoneNames []string `json:"apiZoneNames"` + ApiZoneNames []string `json:"zoneNames"` + Available bool `json:"bool"` + DefaultSubnetId string `json:"defaultSubnetId"` +} + +type ListSubnetsArgs struct { + VpcId string `json:"vpcId"` + ZoneName string `json:"zoneName"` +} + +type ListSubnetsResult struct { + Subnets []Subnet `json:"subnets"` +} + +type SecurityIpsRawResult struct { + SecurityIps []string `json:"ip"` +} + +type UpdateSecurityIpsArgs struct { + SecurityIps []string `json:"securityIps"` +} + +type ListParametersResult struct { + Etag string `json:"etag"` + Parameters []Parameter `json:"items"` +} + +type Parameter struct { + Name string `json:"name"` + DefaultValue string `json:"defaultValue"` + Value string `json:"value"` + PendingValue string `json:"pendingValue"` + Type string `json:"type"` + IsDynamic bool `json:"dynamic"` + ISModifiable bool `json:"modifiable"` + AllowedValues string `json:"allowedValues"` + Desc string `json:"desc"` + // 多加字段,兼容RDS + Dynamic string `json:"dynamicStr"` + Modifiable string `json:"modifiableStr"` +} + +type UpdateParameterArgs struct { + Parameters []KVParameter `json:"parameters"` + WaitSwitch int `json:"waitSwitch"` +} + +type KVParameter struct { + Name string `json:"name"` + Value string `json:"value"` +} + +type Snapshot struct { + SnapshotId string `json:"snapshotId"` + SnapshotSizeInBytes string `json:"snapshotSizeInBytes"` + SnapshotType string `json:"snapshotType"` + SnapshotStatus string `json:"snapshotStatus"` + SnapshotStartTime string `json:"snapshotStartTime"` + SnapshotEndTime string `json:"snapshotEndTime"` +} + +type SnapshotModel struct { + SnapshotId string `json:"snapshotId"` + SnapshotSizeInBytes string `json:"snapshotSizeInBytes"` + SnapshotType string `json:"snapshotType"` + SnapshotStatus string `json:"snapshotStatus"` + SnapshotStartTime string `json:"snapshotStartTime"` + SnapshotEndTime string `json:"snapshotEndTime"` + DownloadUrl string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type BackupDetailResult struct { + Snapshot SnapshotModel `json:"snapshot"` +} + +type Binlog struct { + BinlogId string `json:"binlogId"` + BinlogSizeInBytes int64 `json:"binlogSizeInBytes"` + BinlogStatus string `json:"binlogStatus"` + BinlogStartTime string `json:"binlogStartTime"` + BinlogEndTime string `json:"binlogEndTime"` +} + +type BinlogModel struct { + BinlogId string `json:"binlogId"` + BinlogSizeInBytes int64 `json:"binlogSizeInBytes"` + BinlogStatus string `json:"binlogStatus"` + BinlogStartTime string `json:"binlogStartTime"` + BinlogEndTime string `json:"binlogEndTime"` + DownloadUrl string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type BinlogListResult struct { + Binlogs []Binlog `json:"binlogs"` +} + +type BinlogDetailResult struct { + Binlog BinlogModel `json:"binlog"` +} + +type AuthType string + +const ( + AuthType_ReadOnly AuthType = "readOnly" + AuthType_ReadWrite AuthType = "readWrite" +) + +type AccountPrivilege struct { + AccountName string `json:"accountName"` + AuthType AuthType `json:"authType"` +} + +type CreateDatabaseArgs struct { + ClientToken string `json:"-"` + DbName string `json:"dbName"` + CharacterSetName string `json:"characterSetName"` + Remark string `json:"remark"` +} + +type UpdateDatabaseRemarkArgs struct { + Remark string `json:"remark"` +} + +type Database struct { + DbName string `json:"dbName"` + CharacterSetName string `json:"characterSetName"` + DbStatus string `json:"dbStatus"` + Remark string `json:"remark"` + AccountPrivileges []AccountPrivilege `json:"accountPrivileges"` +} + +type DatabaseResult struct { + Database Database `json:"database"` +} + +type ListDatabaseResult struct { + Databases []Database `json:"databases"` +} + +// Account +type AccountType string + +const ( + AccountType_Super AccountType = "rdssuper" + AccountType_Common AccountType = "common" +) + +type CreateAccountArgs struct { + ClientToken string `json:"-"` + AccountName string `json:"accountName"` + Password string `json:"password"` + // 为了兼容 RDS 参数结构 + AccountType AccountType `json:"type"` + Desc string `json:"remark"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges,omitempty"` +} + +type DatabasePrivilege struct { + DbName string `json:"dbName"` + AuthType string `json:"authType"` +} + +type Account struct { + AccountName string `json:"accountName"` + Desc string `json:"remark"` + Status string `json:"accountStatus"` + AccountType string `json:"accountType"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` +} + +type AccountResult struct { + Account Account `json:"account"` +} + +type ListAccountResult struct { + Accounts []Account `json:"accounts"` +} + +type UpdateAccountPasswordArgs struct { + Password string `json:"password"` +} + +type UpdateAccountDescArgs struct { + Desc string `json:"remark"` +} + +type UpdateAccountPrivilegesArgs struct { + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` +} + +type ListRoGroupResult struct { + RoGroups []RoGroup `json:"roGroups"` +} + +type VpcVo struct { + VpcId string `json:"vpcId"` + ShortId string `json:"shortId"` + Name string `json:"name"` + Cidr string `json:"cidr"` + Status int `json:"status"` + CreateTime string `json:"createTime"` + Description string `json:"description"` + DefaultVpc bool `json:"defaultVpc"` + Ipv6Cidr string `json:"ipv6Cidr"` + AuxiliaryCidr []string `json:"auxiliaryCidr"` + Relay bool `json:"relay"` +} +type GetBackupListArgs struct { + Marker string + MaxKeys int +} +type GetSecurityIpsResult struct { + Etag string `json:"etag"` + SecurityIps []string `json:"securityIps"` +} + +// struct for rds + +type CreateRdsProxyArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing"` + SourceInstanceId string `json:"sourceInstanceId"` + InstanceName string `json:"instanceName,omitempty"` + NodeAmount int `json:"nodeAmount"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []TagModel `json:"tags,omitempty"` +} + +type ResizeRdsArgs struct { + ClientToken string `json:"-"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + NodeAmount int `json:"nodeAmount,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + IsResizeNow bool `json:"isResizeNow,omitempty"` +} + +type OrderIdResponse struct { + OrderId string `json:"orderId"` +} + +type ModifySyncModeArgs struct { + SyncMode string `json:"syncMode"` +} + +type ModifyEndpointArgs struct { + Address string `json:"address"` +} + +type ModifyPublicAccessArgs struct { + PublicAccess bool `json:"publicAccess"` +} + +type AutoRenewArgs struct { + InstanceIds []string `json:"instanceIds"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` +} + +type RebootArgs struct { + IsRebootNow bool `json:"isRebootNow"` +} + +type SwitchArgs struct { + IsSwitchNow bool `json:"isSwitchNow"` +} + +type MaintainWindow struct { + MaintainTime MaintainTime `json:"maintentime"` +} + +type MaintainTime struct { + Period string `json:"period"` + StartTime string `json:"startTime"` + Duration int `json:"duration"` +} + +type RecycleInstance struct { + EngineVersion string `json:"engineVersion"` + VolumeCapacity int `json:"volumeCapacity"` + ApplicationType string `json:"applicationType"` + InstanceName string `json:"instanceName"` + PublicAccessStatus string `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceType string `json:"instanceType"` + Type string `json:"type"` + InstanceStatus string `json:"instanceStatus"` + MemoryCapacity float64 `json:"memoryCapacity"` + InstanceId string `json:"instanceId"` + Engine string `json:"engine"` + VpcId string `json:"vpcId"` + PubliclyAccessible bool `json:"publiclyAccessible"` + InstanceExpireTime string `json:"instanceExpireTime"` + DiskType string `json:"diskType"` + Region string `json:"region"` + CpuCount int `json:"cpuCount"` + UsedStorage float64 `json:"usedStorage"` + LongBBCId string `json:"longBBCId"` +} + +type RecyclerInstanceList struct { + ListResultWithMarker + Result []RecycleInstance `json:"result"` +} + +type BatchInstanceIds struct { + InstanceIds string `json:"instanceIds"` +} + +type SecurityGroup struct { + Name string `json:"name"` + SecurityGroupID string `json:"securityGroupId"` + Description string `json:"description"` + TenantID string `json:"tenantId"` + AssociateNum int `json:"associateNum"` + VpcID string `json:"vpcId"` + VpcShortID string `json:"vpcShortId"` + VpcName string `json:"vpcName"` + CreatedTime string `json:"createdTime"` + Version int `json:"version"` + DefaultSecurityGroup int `json:"defaultSecurityGroup"` +} + +type SecurityGroupArgs struct { + InstanceIds []string `json:"instanceIds"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type ListSecurityGroupResult struct { + Groups []SecurityGroupDetail `json:"groups"` +} + +type SecurityGroupRule struct { + PortRange string `json:"portRange"` + Protocol string `json:"protocol"` + RemoteGroupID string `json:"remoteGroupId"` + RemoteIP string `json:"remoteIP"` + Ethertype string `json:"ethertype"` + TenantID string `json:"tenantId"` + Name string `json:"name"` + ID string `json:"id"` + SecurityGroupRuleID string `json:"securityGroupRuleId"` + Direction string `json:"direction"` +} + +type SecurityGroupDetail struct { + SecurityGroupName string `json:"securityGroupName"` + SecurityGroupID string `json:"securityGroupId"` + SecurityGroupRemark string `json:"securityGroupRemark"` + Inbound []SecurityGroupRule `json:"inbound"` + Outbound []SecurityGroupRule `json:"outbound"` + VpcName string `json:"vpcName"` + VpcID string `json:"vpcId"` + ProjectID string `json:"projectId"` +} + +type ListLogArgs struct { + LogType string `json:"logType"` + Datetime string `json:"datetime"` +} + +type Log struct { + LogStartTime string `json:"logStartTime"` + LogEndTime string `json:"logEndTime"` + LogID string `json:"logId"` + LogSizeInBytes int `json:"logSizeInBytes"` +} + +type LogDetail struct { + Log + DownloadURL string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type GetLogArgs struct { + ValidSeconds int `json:"downloadValidTimeInSec"` +} + +type CreateTableHardLinkArgs struct { + TableName string `json:"tableName"` +} +type Disk struct { + Response struct { + Items []struct { + DiskPartition string `json:"DiskPartition"` + InstanceID string `json:"InstanceId"` + InstanceRole string `json:"InstanceRole"` + PhysicalIP string `json:"PhysicalIp"` + ReportTime string `json:"ReportTime"` + TotalSize int `json:"TotalSize"` + UsedSize int `json:"UsedSize"` + } `json:"Items"` + } `json:"Response"` +} + +type MachineInfo struct { + Response struct { + Items []struct { + InstanceID string `json:"instanceId"` + Role string `json:"role"` + CPUInCore int `json:"cpuInCore"` + FreeCPUInCore int `json:"freeCpuInCore"` + MemSizeInMB int `json:"memSizeInMB"` + FreeMemSizeInMB int `json:"freeMemSizeInMB"` + SizeInGB []struct { + FreeSizeInGB int `json:"freeSizeInGB"` + Label map[string]string `json:"label"` + Path string `json:"path"` + SizeInGB int `json:"sizeInGB"` + } `json:"sizeInGB"` + } `json:"Items"` + } `json:"Response"` +} + +type GetResidualResult struct { + Residual map[string]ResidualOfZone `json:"residual"` +} +type Slave struct { + DiskInGb float64 `json:"diskInGb"` + MemoryInGb float64 `json:"memoryInGb"` + CPUInCore int `json:"cpuInCore"` +} +type Single struct { + DiskInGb float64 `json:"diskInGb"` + MemoryInGb float64 `json:"memoryInGb"` + CPUInCore int `json:"cpuInCore"` +} +type HA struct { + DiskInGb float64 `json:"diskInGb"` + MemoryInGb float64 `json:"memoryInGb"` + CPUInCore int `json:"cpuInCore"` +} +type ResidualOfZone struct { + Slave Slave `json:"slave"` + Single Single `json:"single"` + HA HA `json:"HA"` +} +type GetFlavorCapacityArgs struct { + CpuInCore int `json:"CpuInCore,omitempty"` + MemoryInGb int64 `json:"memoryInGb,omitempty"` + DiskInGb int64 `json:"diskInGb,omitempty"` + Affinity int64 `json:"affinity,omitempty"` +} + +func NewDefaultGetFlavorCapacityArgs(cpuInCore int, memoryInGb, diskInGb int64) *GetFlavorCapacityArgs { + return &GetFlavorCapacityArgs{ + CpuInCore: cpuInCore, + MemoryInGb: memoryInGb, + DiskInGb: diskInGb, + Affinity: 10, + } +} + +type GetFlavorCapacityResult struct { + Capacity map[string]CapacityOfZone `json:"capacity"` +} +type CapacityOfZone struct { + Single int `json:"single"` + Slave int `json:"slave"` + HA int `json:"HA"` +} + +type GetTableAmountArgs struct { + InstanceId string `json:"instanceId"` + DbName string `json:"dbName"` + Pattern string `json:"pattern"` +} + +type TableAmountResult struct { + Tables map[string]int `json:"tables"` + TotalAmount int `json:"totalAmount"` + ReturnAmount int `json:"returnAmount"` +} + +type DatabaseDiskUsageResult struct { + Databases map[string]int `json:"databases"` + RestDisk int64 `json:"restDisk"` + UsedDisk int64 `json:"usedDisk"` +} + +type GetRecoverableDateTimeResult struct { + RecoverableDateTimes []RecoverableDateTime `json:"recoverableDateTimes"` +} +type RecoverableDateTime struct { + StartDateTime string `json:"startDateTime"` + EndDateTime string `json:"endDateTime"` +} + +type RecoverInstanceArgs struct { + Datetime string `json:"datetime"` + RecoverData []RecoverData `json:"recoverData"` +} +type RecoverTable struct { + NewTableName string `json:"newTableName"` + TableName string `json:"tableName"` +} +type RecoverData struct { + RecoverTables []RecoverTable `json:"recoverTables"` + RestoreMode string `json:"restoreMode"` + DbName string `json:"dbName"` + NewDbName string `json:"newDbName"` +} + +type KillSessionArgs struct { + Role string `json:"role"` + SessionIds []int `json:"sessionIds"` +} +type KillSessionResult struct { + TaskID int `json:"taskId"` +} +type GetKillSessionTaskResult struct { + Tasks []KillSessionTask `json:"tasks"` +} +type KillSessionTask struct { + SessionID int `json:"sessionId"` + Status string `json:"status"` +} + +type MaintainTask struct { + TaskID string `json:"taskId"` + TaskName string `json:"taskName"` + TaskStatus string `json:"taskStatus"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + SupportedOperate []string `json:"supportedOperate"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + Region string `json:"region"` +} + +type ProducedMaintainTaskResult struct { + Success bool `json:"success"` + Result MaintainTaskIdResult `json:"result"` +} + +type MaintainTaskIdResult struct { + TaskID string `json:"taskId"` +} + +type ListMaintainTaskResult struct { + ListResultWithMarker + Result []MaintainTask `json:"result"` +} + +type GetMaintainTaskListArgs struct { + Marker + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` +} + +type MaintainTaskDetailList struct { + Tasks []MaintainTaskDetail `json:"tasks"` +} +type MaintainTaskDetail struct { + TaskID int `json:"taskId"` + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + AppID string `json:"appId"` + TaskName string `json:"taskName"` + TaskType string `json:"taskType"` + CreateTime string `json:"createTime"` + PickupTime string `json:"pickupTime"` + ErrNu int `json:"errNu"` + TaskStatus string `json:"taskStatus"` + TaskSpecialAction string `json:"taskSpecialAction"` + TaskSpecialActionTime string `json:"taskSpecialActionTime"` +} + +type AccessLog struct { + Downloadurl struct { + Bbc string `json:"bbc"` + Bos string `json:"bos"` + Mysql string `json:"mysql"` + } `json:"downloadurl"` +} + +type GetErrorLogsArgs struct { + InstanceId string `json:"instanceId"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Role string `json:"role"` + KeyWord string `json:"keyWord,omitempty"` +} + +type ErrorLog struct { + InstanceId string `json:"instanceId"` + LogLevel string `json:"logLevel"` + LogText string `json:"logText"` + ExecuteTime string `json:"executeTime"` +} + +type ErrorLogsResponse struct { + Count int `json:"count"` + ErrorLogs []ErrorLog `json:"errorLogs"` +} + +type GetSlowLogsArgs struct { + InstanceId string `json:"instanceId"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Role string `json:"role"` + DbName []string `json:"dbName,omitempty"` + UserName []string `json:"userName,omitempty"` + HostIp []string `json:"hostIp,omitempty"` + Sql string `json:"sql,omitempty"` +} + +type SlowLog struct { + InstanceId string `json:"instanceId"` + UserName string `json:"userName"` + DbName string `json:"dbName"` + HostIp string `json:"hostIp"` + QueryTime float64 `json:"queryTime"` + LockTime float64 `json:"lockTime"` + RowsExamined int `json:"rowsExamined"` + RowsSent int `json:"rowsSent"` + Sql string `json:"sql"` + ExecuteTime string `json:"executeTime"` +} + +type SlowLogsResponse struct { + Count int `json:"count"` + SlowLogs []SlowLog `json:"slowLogs"` +} + +type GetBackupStatusResponse struct { + IsBackuping bool `json:"isBackuping"` + SnapshotStartTime string `json:"snapshotStartTime"` +} + +type InstanceVersionRollBackArg struct { + WaitSwitch bool `json:"waitSwitch"` +} + +type InstanceVersionUpgradeArg struct { + IsUpgradeNow bool `json:"isUpgradeNow"` +} + +type InstanceSyncDelayResponse struct { + Success bool `json:"success"` + Result InstanceSyncDelay `json:"result"` +} + +type InstanceSyncDelay struct { + SyncDelay int `json:"sync_delay"` + SyncStatus string `json:"sync_status"` +} + +type InstanceSyncDelayReplicationArg struct { + Action string `json:"action"` +} + +type InstanceSyncDelayReplicationResponse struct { + Success bool `json:"success"` +} + +type AccessDetailItem struct { + BackupID string `json:"backupID"` + AccessDateTime string `json:"accessDateTime"` + AccessResult string `json:"accessResult"` + AccessSrcAddressType string `json:"accessSrcAddressType"` + AvailableZone string `json:"availableZone"` + AccessSrcAddress string `json:"accessSrcAddress"` + AccessOperationType string `json:"accessOperationType"` + StorageType string `json:"storageType"` + StorageAddress string `json:"storageAddress"` + Region string `json:"region"` + BackupName string `json:"backupName"` + AccessSrcAgent string `json:"accessSrcAgent"` + StorageID string `json:"storageID"` +} + +type Pagination struct { + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Marker string `json:"marker"` + TotalKeys int `json:"totalKeys"` +} +type BackupAccessDetail struct { + StartDateTime string `json:"startDateTime"` + EndDateTime string `json:"endDateTime"` + DataType string `json:"dataType"` + BackupAccessDetails []AccessDetailItem `json:"backupAccessDetails"` + Pagination Pagination `json:"pagination"` +} + +type AccessDetailArgs struct { + StartDateTime string `json:"startDateTime"` + EndDateTime string `json:"endDateTime"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + DataType string `json:"dataType,omitempty"` +} diff --git a/bce-sdk-go/services/dns/client.go b/bce-sdk-go/services/dns/client.go new file mode 100644 index 0000000..b110a0f --- /dev/null +++ b/bce-sdk-go/services/dns/client.go @@ -0,0 +1,287 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 dns + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "http://dns.baidubce.com" + DEFAULT_MAX_PARALLEL = 10 + MULTIPART_ALIGN = 1 << 20 // 1MB + MIN_MULTIPART_SIZE = 1 << 20 // 1MB + DEFAULT_MULTIPART_SIZE = 12 * (1 << 20) // 12MB + MAX_PART_NUMBER = 10000 +) + +// Client of bcd service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient + + // Fileds that used in parallel operation for BOS service + MaxParallel int64 + MultipartSize int64 +} + +// NewClient make the bcd service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer), + DEFAULT_MAX_PARALLEL, DEFAULT_MULTIPART_SIZE} + return client, nil +} + +// AddLineGroup - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) AddLineGroup(body *AddLineGroupRequest, clientToken string) error { + return AddLineGroup(c, body, clientToken) +} + +// CreatePaidZone - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreatePaidZone(body *CreatePaidZoneRequest, clientToken string) error { + return CreatePaidZone(c, body, clientToken) +} + +// CreateRecord - +// +// PARAMS: +// - zoneName: 域名名称。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateRecord(zoneName string, body *CreateRecordRequest, clientToken string) error { + return CreateRecord(c, zoneName, body, clientToken) +} + +// CreateZone - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateZone(body *CreateZoneRequest, clientToken string) error { + return CreateZone(c, body, clientToken) +} + +// DeleteLineGroup - +// +// PARAMS: +// - lineId: 线路组id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteLineGroup(lineId string, clientToken string) error { + return DeleteLineGroup(c, lineId, clientToken) +} + +// DeleteRecord - +// +// PARAMS: +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteRecord(zoneName string, recordId string, clientToken string) error { + return DeleteRecord(c, zoneName, recordId, clientToken) +} + +// DeleteZone - +// +// PARAMS: +// - zoneName: 域名的名称。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteZone(zoneName string, clientToken string) error { + return DeleteZone(c, zoneName, clientToken) +} + +// ListLineGroup - +// +// PARAMS: +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串。 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000,缺省值为1000。 +// - body: body参数 +// +// RETURNS: +// - *ListLineGroupResponse: +// - error: the return error if any occurs +func (c *Client) ListLineGroup(body *ListLineGroupRequest) (*ListLineGroupResponse, error) { + return ListLineGroup(c, body.Marker, body.MaxKeys) +} + +// ListRecord - +// +// PARAMS: +// - zoneName: 域名的名称。 +// - rr: 主机记录,例如“www”。 +// - id: 解析记录id。 +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串。 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000。 +// - body: body参数 +// +// RETURNS: +// - *ListRecordResponse: +// - error: the return error if any occurs +func (c *Client) ListRecord(zoneName string, request *ListRecordRequest) (*ListRecordResponse, error) { + return ListRecord(c, zoneName, request.Rr, request.Id, request.Marker, request.MaxKeys) +} + +// ListZone - +// +// PARAMS: +// - name: 域名的名称,支持模糊搜索。 +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 +// - body: body参数 +// +// RETURNS: +// - *ListZoneResponse: +// - error: the return error if any occurs +func (c *Client) ListZone(body *ListZoneRequest) ( + *ListZoneResponse, error) { + return ListZone(c, body, body.Name, body.Marker, body.MaxKeys) +} + +// RenewZone - +// +// PARAMS: +// - name: 续费的域名。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) RenewZone(name string, body *RenewZoneRequest, clientToken string) error { + return RenewZone(c, name, body, clientToken) +} + +// UpdateLineGroup - +// +// PARAMS: +// - lineId: 线路组id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateLineGroup(lineId string, body *UpdateLineGroupRequest, + clientToken string) error { + return UpdateLineGroup(c, lineId, body, clientToken) +} + +// UpdateRecord - +// +// PARAMS: +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateRecord(zoneName string, recordId string, body *UpdateRecordRequest, + clientToken string) error { + return UpdateRecord(c, zoneName, recordId, body, clientToken) +} + +// UpdateRecordDisable - +// +// PARAMS: +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateRecordDisable(zoneName string, recordId string, clientToken string) error { + return UpdateRecordDisable(c, zoneName, recordId, clientToken) +} + +// UpdateRecordEnable - +// +// PARAMS: +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateRecordEnable(zoneName string, recordId string, clientToken string) error { + return UpdateRecordEnable(c, zoneName, recordId, clientToken) +} + +// UpgradeZone - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpgradeZone(body *UpgradeZoneRequest, clientToken string) error { + return UpgradeZone(c, body, clientToken) +} diff --git a/bce-sdk-go/services/dns/client_test.go b/bce-sdk-go/services/dns/client_test.go new file mode 100644 index 0000000..00b572a --- /dev/null +++ b/bce-sdk-go/services/dns/client_test.go @@ -0,0 +1,217 @@ +package dns + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + DNS_CLIENT *Client + + // set these values before start test + Region = "bj" + RR = "rr" + TYPE = "A" + VALUE = "1.2.3.5" + ZONE_NAME = "ccq.com" + ZONE_NAME1 = "sdkdns.com" + PREPAID = "Prepaid" + ProductVersion = "discount" + RECORD_ID = "48526" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + DNS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateZone(t *testing.T) { + createArgs := &CreateZoneRequest{ + Name: ZONE_NAME1, + } + err := DNS_CLIENT.CreateZone(createArgs, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListZone(t *testing.T) { + listZoneRequest := &ListZoneRequest{ + Name: ZONE_NAME, + } + res, err := DNS_CLIENT.ListZone(listZoneRequest) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteZone(t *testing.T) { + err := DNS_CLIENT.DeleteZone(ZONE_NAME, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreatePaidZone(t *testing.T) { + createArgs := &CreatePaidZoneRequest{ + Names: []string{ZONE_NAME}, + ProductVersion: ProductVersion, + Billing: Billing{ + PaymentTiming: PREPAID, + Reservation: Reservation{ + ReservationLength: 1, + }, + }, + } + err := DNS_CLIENT.CreatePaidZone(createArgs, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpgradeZone(t *testing.T) { + createArgs := &UpgradeZoneRequest{ + Names: []string{ZONE_NAME1}, + Billing: Billing{ + PaymentTiming: PREPAID, + Reservation: Reservation{ + ReservationLength: 1, + }, + }, + } + err := DNS_CLIENT.UpgradeZone(createArgs, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RenewZone(t *testing.T) { + createArgs := &RenewZoneRequest{ + Billing: Billing{ + Reservation: Reservation{ + ReservationLength: 1, + }, + }, + } + err := DNS_CLIENT.RenewZone(ZONE_NAME1, createArgs, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateRecord(t *testing.T) { + createRecordRequest := &CreateRecordRequest{ + Rr: RR, + Type: TYPE, + Value: VALUE, + } + err := DNS_CLIENT.CreateRecord(ZONE_NAME, createRecordRequest, "") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListRecord(t *testing.T) { + listRecordRequest := &ListRecordRequest{} + res, err := DNS_CLIENT.ListRecord(ZONE_NAME, listRecordRequest) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateRecord(t *testing.T) { + updateRecordRequest := &UpdateRecordRequest{ + Rr: RR, + Type: TYPE, + Value: "1.1.1.1", + } + err := DNS_CLIENT.UpdateRecord(ZONE_NAME, RECORD_ID, updateRecordRequest, "") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateRecordEnable(t *testing.T) { + err := DNS_CLIENT.UpdateRecordEnable(ZONE_NAME, "48540", "") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateRecordDisable(t *testing.T) { + err := DNS_CLIENT.UpdateRecordDisable(ZONE_NAME, "48540", "") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteRecord(t *testing.T) { + err := DNS_CLIENT.DeleteRecord(ZONE_NAME, "48540", "") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateLineGroup(t *testing.T) { + addLineGroupRequest := &AddLineGroupRequest{ + Name: "ccq0826", + Lines: []string{"yunnan.ct"}, + } + err := DNS_CLIENT.AddLineGroup(addLineGroupRequest, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateLineGroup(t *testing.T) { + updateLineGroupRequest := &UpdateLineGroupRequest{ + Name: "ccq0826_1", + Lines: []string{"india.any"}, + } + err := DNS_CLIENT.UpdateLineGroup("6165", updateLineGroupRequest, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListLineGroup(t *testing.T) { + listLineGroupRequest := &ListLineGroupRequest{} + res, err := DNS_CLIENT.ListLineGroup(listLineGroupRequest) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteLineGroup(t *testing.T) { + err := DNS_CLIENT.DeleteLineGroup("6039", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/dns/dns.go b/bce-sdk-go/services/dns/dns.go new file mode 100644 index 0000000..64b0abb --- /dev/null +++ b/bce-sdk-go/services/dns/dns.go @@ -0,0 +1,606 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 dns + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" + "strings" +) + +// AddLineGroup - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func AddLineGroup(cli bce.Client, body *AddLineGroupRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/dns/customline" + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreatePaidZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreatePaidZone(cli bce.Client, body *CreatePaidZoneRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/dns/zone/order" + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreateRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名名称。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreateRecord(cli bce.Client, zoneName string, body *CreateRecordRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/dns/zone/[zoneName]/record" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreateZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func CreateZone(cli bce.Client, body *CreateZoneRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/dns/zone" + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteLineGroup - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - lineId: 线路组id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// +// RETURNS: +// - error: the return error if any occurs +func DeleteLineGroup(cli bce.Client, lineId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/dns/customline/[lineId]" + path = strings.Replace(path, "[lineId]", lineId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DeleteRecord(cli bce.Client, zoneName string, recordId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/dns/zone/[zoneName]/record/[recordId]" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名的名称。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DeleteZone(cli bce.Client, zoneName string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/dns/zone/[zoneName]" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// ListLineGroup - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串。 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000,缺省值为1000。 +// - body: +// +// RETURNS: +// - *api.ListLineGroupResponse: +// - error: the return error if any occurs +func ListLineGroup(cli bce.Client, marker string, maxKeys int) (*ListLineGroupResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/dns/customline" + req.SetUri(path) + if "" != marker { + req.SetParam("marker", marker) + } + if 0 != maxKeys { + req.SetParam("maxKeys", strconv.Itoa(maxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListLineGroupResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名的名称。 +// - rr: 主机记录,例如“www”。 +// - id: 解析记录id。 +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串。 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000。 +// - body: +// +// RETURNS: +// - *api.ListRecordResponse: +// - error: the return error if any occurs +func ListRecord(cli bce.Client, zoneName string, rr string, id string, + marker string, maxKeys int) (*ListRecordResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/dns/zone/[zoneName]/record" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + req.SetUri(path) + if "" != rr { + req.SetParam("rr", rr) + } + if "" != id { + req.SetParam("id", id) + } + if "" != marker { + req.SetParam("marker", marker) + } + if 0 != maxKeys { + req.SetParam("maxKeys", strconv.Itoa(maxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListRecordResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: 域名的名称,支持模糊搜索。 +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 +// - body: +// +// RETURNS: +// - *api.ListZoneResponse: +// - error: the return error if any occurs +func ListZone(cli bce.Client, body *ListZoneRequest, name string, marker string, maxKeys int) ( + *ListZoneResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/dns/zone" + req.SetUri(path) + if "" != name { + req.SetParam("name", name) + } + if "" != marker { + req.SetParam("marker", marker) + } + if 0 != maxKeys { + req.SetParam("maxKeys", strconv.Itoa(maxKeys)) + } + + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListZoneResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// RenewZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - name: 续费的域名。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func RenewZone(cli bce.Client, name string, body *RenewZoneRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/dns/zone/order/[name]" + path = strings.Replace(path, "[name]", name, -1) + req.SetUri(path) + req.SetParam("purchaseReserved", "") + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateLineGroup - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - lineId: 线路组id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateLineGroup(cli bce.Client, lineId string, body *UpdateLineGroupRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/dns/customline/[lineId]" + path = strings.Replace(path, "[lineId]", lineId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateRecord(cli bce.Client, zoneName string, recordId string, body *UpdateRecordRequest, + clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/dns/zone/[zoneName]/record/[recordId]" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateRecordDisable - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateRecordDisable(cli bce.Client, zoneName string, recordId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/dns/zone/[zoneName]/record/[recordId]" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("disable", "") + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateRecordEnable - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneName: 域名名称。 +// - recordId: 解析记录id。 +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateRecordEnable(cli bce.Client, zoneName string, recordId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/dns/zone/[zoneName]/record/[recordId]" + path = strings.Replace(path, "[zoneName]", zoneName, -1) + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("enable", "") + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpgradeZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串。 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpgradeZone(cli bce.Client, body *UpgradeZoneRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/dns/zone/order" + req.SetUri(path) + req.SetParam("upgradeToDiscount", "") + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/dns/model.go b/bce-sdk-go/services/dns/model.go new file mode 100644 index 0000000..db77ba9 --- /dev/null +++ b/bce-sdk-go/services/dns/model.go @@ -0,0 +1,200 @@ +/* + * Copyright Baidu, Inc. + * + * 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 dns + +type AddLineGroupRequest struct { + Name string `json:"name"` + Lines []string `json:"lines"` +} + +type AddLineGroupRequestLines struct { +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation Reservation `json:"reservation"` +} + +type CreatePaidZoneRequest struct { + Names []string `json:"names"` + ProductVersion string `json:"productVersion"` + Billing Billing `json:"billing"` +} + +type CreateRecordRequest struct { + Rr string `json:"rr"` + Type string `json:"type"` + Value string `json:"value"` + Ttl *int32 `json:"ttl"` + Line *string `json:"line"` + Description *string `json:"description"` + Priority *int32 `json:"priority"` +} + +type CreateZoneRequest struct { + Name string `json:"name"` +} + +type DeleteRecordRequest struct { + Rr string `json:"rr"` + Type string `json:"type"` + Value string `json:"value"` + Ttl *int32 `json:"ttl"` + Description *string `json:"description"` + Priority *int32 `json:"priority"` +} + +type DeleteZoneRequest struct { + Names []string `json:"names"` + ProductVersion string `json:"productVersion"` + Billing Billing `json:"billing"` +} + +type DeleteZoneRequestNames struct { +} + +type Line struct { + Id string `json:"id"` + Name string `json:"name"` + Lines []string `json:"lines"` + RelatedZoneCount int32 `json:"relatedZoneCount"` + RelatedRecordCount int32 `json:"relatedRecordCount"` +} + +type ListLineGroupRequest struct { + Marker string + MaxKeys int +} + +type ListLineGroupResponse struct { + Marker *string `json:"marker"` + IsTruncated *bool `json:"isTruncated"` + NextMarker *string `json:"nextMarker"` + MaxKeys *int32 `json:"maxKeys"` + LineList []Line `json:"lineList"` +} + +type ListRecordRequest struct { + Rr string + Id string + Marker string + MaxKeys int +} + +type ListRecordResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int32 `json:"maxKeys"` + Records []Record `json:"records"` +} + +type ListRecordResponseRecords struct { +} + +type ListZoneRequest struct { + Name string + Marker string + MaxKeys int +} + +type ListZoneResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int32 `json:"maxKeys"` + Zones []Zone `json:"zones"` +} + +type ListZoneResponseZones struct { +} + +type Record struct { + Id string `json:"id"` + Rr string `json:"rr"` + Status string `json:"status"` + Type string `json:"type"` + Value string `json:"value"` + Ttl int32 `json:"ttl"` + Line string `json:"line"` + Description string `json:"description"` + Priority int32 `json:"priority"` +} + +type RenewZoneRequest struct { + Billing Billing `json:"billing"` +} + +type Reservation struct { + ReservationLength int32 `json:"reservationLength"` +} + +type TagModel struct { + TagKey *string `json:"tagKey"` + TagValue *string `json:"tagValue"` +} + +type UpdateLineGroupRequest struct { + Name string `json:"name"` + Lines []string `json:"lines"` +} + +type UpdateLineGroupRequestLines struct { +} + +type UpdateRecordDisableRequest struct { + Rr string `json:"rr"` + Type string `json:"type"` + Value string `json:"value"` + Ttl *int32 `json:"ttl"` + Description *string `json:"description"` + Priority *int32 `json:"priority"` +} + +type UpdateRecordEnableRequest struct { + Rr string `json:"rr"` + Type string `json:"type"` + Value string `json:"value"` + Ttl *int32 `json:"ttl"` + Description *string `json:"description"` + Priority *int32 `json:"priority"` +} + +type UpdateRecordRequest struct { + Rr string `json:"rr"` + Type string `json:"type"` + Value string `json:"value"` + Ttl *int32 `json:"ttl"` + Description *string `json:"description"` + Priority *int32 `json:"priority"` +} + +type UpgradeZoneRequest struct { + Names []string `json:"names"` + Billing Billing `json:"billing"` +} + +type UpgradeZoneRequestNames struct { +} + +type Zone struct { + Id string `json:"id"` + Name string `json:"name"` + Status string `json:"status"` + ProductVersion string `json:"productVersion"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + Tags []TagModel `json:"tags"` +} diff --git a/bce-sdk-go/services/doc/api/document.go b/bce-sdk-go/services/doc/api/document.go new file mode 100644 index 0000000..abb71f3 --- /dev/null +++ b/bce-sdk-go/services/doc/api/document.go @@ -0,0 +1,261 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// document.go - the document APIs definition supported by the DOC service + +// Package api defines all APIs supported by the DOC service of BCE. +package api + +import ( + "errors" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// RegisterDocument - register document in doc service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - regParam title and format of the document being registered +// +// RETURNS: +// - *RegDocumentResp: id and document location in bos +// - error: the return error if any occurs +func RegisterDocument(cli bce.Client, regParam *RegDocumentParam) (*RegDocumentResp, error) { + if regParam == nil { + return nil, errors.New("param cannot be nil") + } + playload, err := regParam.String() + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromString(playload) + if err != nil { + return nil, err + } + + req := &bce.BceRequest{} + req.SetUri("/v2/document") + req.SetParam("register", "") + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &RegDocumentResp{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// PublishDocument - publish document +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - documentId: id of document in doc service +// +// RETURNS: +// - error: the return error if any occurs +func PublishDocument(cli bce.Client, documentId string) error { + req := &bce.BceRequest{} + urlPath := fmt.Sprintf("/v2/document/%s", documentId) + req.SetUri(urlPath) + req.SetParam("publish", "") + req.SetMethod(http.PUT) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil + +} + +// QueryDocument - query document's status +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - documentId: id of document in doc service +// - queryParam: enable/disable https of coverl url +// +// RETURNS: +// - *QueryDocumentResp +// - error: the return error if any occurs +func QueryDocument(cli bce.Client, documentId string, queryParam *QueryDocumentParam) (*QueryDocumentResp, error) { + req := &bce.BceRequest{} + urlPath := fmt.Sprintf("/v2/document/%s", documentId) + req.SetUri(urlPath) + if queryParam != nil { + req.SetParam("https", strconv.FormatBool(queryParam.Https)) + } + req.SetMethod(http.GET) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &QueryDocumentResp{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// ReadDocument - get document token for client sdk +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - documentId: id of document in doc service +// - readParam: expiration time of the doc's html +// +// RETURNS: +// - *ReadDocumentResp +// - error: the return error if any occurs +func ReadDocument(cli bce.Client, documentId string, readParam *ReadDocumentParam) (*ReadDocumentResp, error) { + req := &bce.BceRequest{} + urlPath := fmt.Sprintf("/v2/document/%s", documentId) + req.SetUri(urlPath) + req.SetParam("read", "") + if readParam != nil { + req.SetParam("expireInSeconds", strconv.FormatInt(readParam.ExpireInSeconds, 10)) + } + req.SetMethod(http.GET) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ReadDocumentResp{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// GetImages - Get the list of images generated by the document conversion +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - documentId: id of document in doc service +// +// RETURNS: +// - *ImagesListResp +// - error: the return error if any occurs +func GetImages(cli bce.Client, documentId string) (*GetImagesResp, error) { + req := &bce.BceRequest{} + urlPath := fmt.Sprintf("/v2/document/%s", documentId) + req.SetUri(urlPath) + req.SetParam("getImages", "") + req.SetMethod(http.GET) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetImagesResp{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteDocument - delete document in doc service +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - documentId: id of document in doc service +// +// RETURNS: +// - error: the return error if any occurs +func DeleteDocument(cli bce.Client, documentId string) error { + req := &bce.BceRequest{} + urlPath := fmt.Sprintf("/v2/document/%s", documentId) + req.SetUri(urlPath) + req.SetMethod(http.DELETE) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// ListDocuments - list all documents +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - param: the optional arguments to list documents +// +// RETURNS: +// - *ListDocumentsResp: the result docments list structure +// - error: nil if ok otherwise the specific error +func ListDocuments(cli bce.Client, listParam *ListDocumentsParam) (*ListDocumentsResp, error) { + err := listParam.Check() + if err != nil { + return nil, err + } + + req := &bce.BceRequest{} + req.SetUri("/v2/document/") + req.SetMethod(http.GET) + if listParam.Status != "" { + req.SetParam("status", string(listParam.Status)) + } + if listParam.Marker != "" { + req.SetParam("marker", listParam.Marker) + } + if listParam.MaxSize != 0 { + req.SetParam("maxSize", strconv.FormatInt(listParam.MaxSize, 10)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &ListDocumentsResp{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/doc/api/model.go b/bce-sdk-go/services/doc/api/model.go new file mode 100644 index 0000000..3d16cd0 --- /dev/null +++ b/bce-sdk-go/services/doc/api/model.go @@ -0,0 +1,180 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +import ( + "encoding/json" + "errors" +) + +type StatusType string + +const ( + DOC_TARGET_H5 = "h5" + DOC_TARGET_IMAGE = "image" + + DOC_PUBLIC = "PUBLIC" + DOC_PRIVATE = "PRIVATE" + + DOC_STATUS_UPLOADING StatusType = "UPLOADING" + DOC_STATUS_PROCESSING StatusType = "PROCESSING" + DOC_STATUS_PUBLISHED StatusType = "PUBLISHED" + DOC_STATUS_FAILED StatusType = "FAILED" +) + +type RegDocumentParam struct { + Title string `json:"title"` // must + Format string `json:"format"` // must,doc, docx, ppt, pptx, xls, xlsx, vsd, pot, pps, rtf, wps, et, dps, pdf, txt, epub + TargetType string `json:"targetType"` // h5|image, default: h5 + Notification string `json:"notification"` // notification + Access string `json:"access"` // PUBLIC|PRIVATE, default: PUBLIC +} + +// String - 格式化为json格式 +func (d *RegDocumentParam) String() (string, error) { + if d.Title == "" || d.Format == "" { + return "", errors.New("tile and format cannot be empty") + } + if d.TargetType == "" || (d.TargetType != DOC_TARGET_H5 && d.TargetType != DOC_TARGET_IMAGE) { + d.TargetType = DOC_TARGET_H5 + } + if d.Access != DOC_PUBLIC && d.Access != DOC_PRIVATE { + d.Access = DOC_PUBLIC + } + + j, e := json.Marshal(d) + if e != nil { + return "", e + } + + // 如果 notification 为空,则去掉该参数,不然请求会报错 + if d.Notification == "" { + var m map[string]string + json.Unmarshal(j, &m) + delete(m, "notification") + j, _ = json.Marshal(m) + } + + return string(j), nil +} + +// RegDocumentResp - 注册文档请求响应 +type RegDocumentResp struct { + DocumentId string `json:"documentId"` + Bucket string `json:"bucket"` + Object string `json:"object"` + BosEndpoint string `json:"bosEndpoint"` +} + +type GetImagesResp struct { + Images []ImageResp `json:"images"` +} + +type ImageResp struct { + PageIndex int64 `json:"pageIndex"` + Url string `json:"url"` +} + +type QueryDocumentParam struct { + Https bool +} + +type QueryDocumentResp struct { + DocumentId string `json:"documentId"` + Title string `json:"title"` + Format string `json:"format"` + TargetType string `json:"targetType"` + Status string `json:"status"` + UploadInfo UploadInfoResp `json:"uploadInfo"` + PublishInfo PublishInfoResp `json:"publishInfo"` + Notification string `json:"notification"` + Access string `json:"access"` + CreateTime string `json:"createTime"` + Error DocumentErrorResp `json:"error"` +} + +type UploadInfoResp struct { + Bucket string `json:"bucket"` + Object string `json:"object"` + BosEndpoint string `json:"bosEndpoint"` +} + +type PublishInfoResp struct { + PageCount int `json:"pageCount"` + SizeInBytes int `json:"sizeInBytes"` + CoverUrl string `json:"coverUrl"` + PublishTime string `json:"publishTime"` +} + +type DocumentErrorResp struct { + Code string `json:"code"` + Message string `json:"message"` +} + +type ReadDocumentParam struct { + ExpireInSeconds int64 +} + +type ReadDocumentResp struct { + DocumentId string `json:"documentId"` + DocId string `json:"docId"` + Host string `json:"host"` + Token string `json:"token"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` +} + +type ListDocumentsParam struct { + Status StatusType + Marker string + MaxSize int64 +} + +func (l *ListDocumentsParam) Check() error { + switch l.Status { + case DOC_STATUS_UPLOADING: + case DOC_STATUS_FAILED: + case DOC_STATUS_PROCESSING: + case DOC_STATUS_PUBLISHED: + case "": + default: + return errors.New("invalid DOC status") + } + if l.MaxSize > 200 || l.MaxSize < 0 { + return errors.New("invalid maxSize") + } + return nil +} + +type ListDocumentsResp struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker,omitempty"` + Docs []DocumentResp `json:"documents"` +} + +type DocumentResp struct { + DocumentId string `json:"documentId"` + Title string `json:"title"` + Format string `json:"format"` + TargetType string `json:"targetType"` + Status string `json:"status"` + Notification string `json:"notification"` + Access string `json:"access"` + CreateTime string `json:"createTime"` + Error DocumentErrorResp `json:"error"` +} diff --git a/bce-sdk-go/services/doc/client.go b/bce-sdk-go/services/doc/client.go new file mode 100644 index 0000000..d75aaa9 --- /dev/null +++ b/bce-sdk-go/services/doc/client.go @@ -0,0 +1,168 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for DOC service +// Package doc defines the DOC services of BCE. The supported APIs are all defined in sub-package + +package doc + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/doc/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "doc.bj.baidubce.com" +) + +// Client of DOC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// DocClientConfiguration defines the config components structure by user. +type DocClientConfiguration struct { + Ak string + Sk string + Endpoint string +} + +// NewClient make the DOC service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk string) (*Client, error) { + return NewClientWithConfig(&DocClientConfiguration{ + Ak: ak, + Sk: sk, + Endpoint: DEFAULT_SERVICE_DOMAIN, + }) +} + +func NewClientWithConfig(config *DocClientConfiguration) (*Client, error) { + var credentials *auth.BceCredentials + var err error + ak, sk, endpoint := config.Ak, config.Sk, config.Endpoint + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS, + RedirectDisabled: false} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// RegisterDocument - register document in doc service +// +// PARAMS: +// - regParam title and format of the document being registered +// +// RETURNS: +// - *api.RegDocumentResp: id and document location in bos +// - error: the return error if any occurs +func (c *Client) RegisterDocument(regParam *api.RegDocumentParam) (*api.RegDocumentResp, error) { + return api.RegisterDocument(c, regParam) +} + +// PublishDocument - publish document +// +// PARAMS: +// - documentId: id of document in doc service +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) PublishDocument(documentId string) error { + return api.PublishDocument(c, documentId) +} + +// QueryDocument - query document's status +// +// PARAMS: +// - documentId: id of document in doc service +// - queryParam: enable/disable https of coverl url +// +// RETURNS: +// - *api.QueryDocumentResp +// - error: the return error if any occurs +func (c *Client) QueryDocument(documentId string, queryParam *api.QueryDocumentParam) (*api.QueryDocumentResp, error) { + return api.QueryDocument(c, documentId, queryParam) +} + +// ReadDocument - get document token for client sdk +// +// PARAMS: +// - documentId: id of document in doc service +// - readParam: expiration time of the doc's html +// +// RETURNS: +// - *api.ReadDocumentResp +// - error: the return error if any occurs +func (c *Client) ReadDocument(documentId string, readParam *api.ReadDocumentParam) (*api.ReadDocumentResp, error) { + return api.ReadDocument(c, documentId, readParam) +} + +// GetImages - Get the list of images generated by the document conversion +// +// PARAMS: +// - documentId: id of document in doc service +// +// RETURNS: +// - *api.ImagesListResp +// - error: the return error if any occurs +func (c *Client) GetImages(documentId string) (*api.GetImagesResp, error) { + return api.GetImages(c, documentId) +} + +// DeleteDocument - delete document in doc service +// +// PARAMS: +// - documentId: id of document in doc service +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteDocument(documentId string) error { + return api.DeleteDocument(c, documentId) +} + +// ListDocuments - list all documents +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - param: the optional arguments to list documents +// +// RETURNS: +// - *ListDocumentsResp: the result docments list structure +// - error: nil if ok otherwise the specific error +func (c *Client) ListDocuments(listParam *api.ListDocumentsParam) (*api.ListDocumentsResp, error) { + return api.ListDocuments(c, listParam) +} diff --git a/bce-sdk-go/services/doc/client_test.go b/bce-sdk-go/services/doc/client_test.go new file mode 100644 index 0000000..d826ae4 --- /dev/null +++ b/bce-sdk-go/services/doc/client_test.go @@ -0,0 +1,172 @@ +package doc + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/services/bos" + "github.com/baidubce/bce-sdk-go/services/doc/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + DOC_CLIENT *Client + BOS_CLIENT *bos.Client +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given: %+v\n", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + DOC_CLIENT, _ = NewClient(confObj.AK, confObj.SK) + BOS_CLIENT, _ = bos.NewClient(confObj.AK, confObj.SK, "") + //log.SetLogHandler(log.STDERR | log.FILE) + //log.SetRotateType(log.ROTATE_SIZE) + log.SetLogLevel(log.WARN) + //log.SetLogHandler(log.STDERR) + //log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestGetDocHTML(t *testing.T) { + regParam := &api.RegDocumentParam{ + Title: "test.txt", + Format: "txt", + } + res, err := DOC_CLIENT.RegisterDocument(regParam) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + + etag, err := BOS_CLIENT.PutObjectFromString(res.Bucket, res.Object, "test\nline", nil) + ExpectEqual(t.Errorf, nil, err) + + t.Logf("%+v", etag) + + err = DOC_CLIENT.PublishDocument(res.DocumentId) + ExpectEqual(t.Errorf, nil, err) + + for { + time.Sleep(time.Duration(1) * time.Second) + qRes, err := DOC_CLIENT.QueryDocument(res.DocumentId, &api.QueryDocumentParam{Https: false}) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", qRes) + if qRes.Status == "PUBLISHED" { + break + } + } + rRes, err := DOC_CLIENT.ReadDocument(res.DocumentId, &api.ReadDocumentParam{ExpireInSeconds: 3600}) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "BCEDOC", rRes.Host) + t.Logf("%+v", rRes) +} + +func TestGetDocImages(t *testing.T) { + regParam := &api.RegDocumentParam{ + Title: "sudoku.pdf", + Format: "pdf", + TargetType: "image", + } + res, err := DOC_CLIENT.RegisterDocument(regParam) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + + etag, err := BOS_CLIENT.PutObjectFromFile(res.Bucket, res.Object, "./sudoku.pdf", nil) + ExpectEqual(t.Errorf, nil, err) + + t.Logf("%+v", etag) + + err = DOC_CLIENT.PublishDocument(res.DocumentId) + ExpectEqual(t.Errorf, nil, err) + + for { + time.Sleep(time.Duration(1) * time.Second) + qRes, err := DOC_CLIENT.QueryDocument(res.DocumentId, &api.QueryDocumentParam{Https: false}) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", qRes) + if qRes.Status == "PUBLISHED" { + break + } + } + rRes, err := DOC_CLIENT.GetImages(res.DocumentId) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", rRes) +} + +func TestListDocs(t *testing.T) { + listParam := &api.ListDocumentsParam{ + Status: api.DOC_STATUS_PUBLISHED, + MaxSize: 2, + } + res, err := DOC_CLIENT.ListDocuments(listParam) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 2, len(res.Docs)) + t.Logf("%+v", res) + + listParam.Marker = res.NextMarker + listParam.MaxSize = 3 + res, err = DOC_CLIENT.ListDocuments(listParam) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 3, len(res.Docs)) +} + +func TestDeleteDocs(t *testing.T) { + regParam := &api.RegDocumentParam{ + Title: "test.txt", + Format: "txt", + } + res, err := DOC_CLIENT.RegisterDocument(regParam) + ExpectEqual(t.Errorf, nil, err) + t.Logf("%+v", res) + + err = DOC_CLIENT.DeleteDocument(res.DocumentId) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/dts/client.go b/bce-sdk-go/services/dts/client.go new file mode 100644 index 0000000..883bc13 --- /dev/null +++ b/bce-sdk-go/services/dts/client.go @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for DTS service + +// Package dts defines the DTS services of BCE. The supported APIs are all defined in sub-package +package dts + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + DEFAULT_ENDPOINT = "dts.baidubce.com" + REQUEST_DTS_URL = "/task" +) + +// Client of DTS service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getDtsUri() string { + return URI_PREFIX + REQUEST_DTS_URL +} + +func getDtsUriWithTaskId(taskId string) string { + return URI_PREFIX + REQUEST_DTS_URL + "/" + taskId +} diff --git a/bce-sdk-go/services/dts/client_test.go b/bce-sdk-go/services/dts/client_test.go new file mode 100644 index 0000000..3e46fe2 --- /dev/null +++ b/bce-sdk-go/services/dts/client_test.go @@ -0,0 +1,260 @@ +package dts + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + DTS_CLIENT *Client + DTS_ID string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 1; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + DTS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateDts(t *testing.T) { + args := &CreateDtsArgs{ + ProductType: "postpay", + Type: "migration", + Standard: "Large", + SourceInstanceType: "public", + TargetInstanceType: "public", + CrossRegionTag: 0, + DirectionType: "single", + } + result, err := DTS_CLIENT.CreateDts(args) + ExpectEqual(t.Errorf, nil, err) + + DTS_ID = result.DtsTasks[0].DtsId +} + +func TestClient_GetDetail(t *testing.T) { + //result, err := DTS_CLIENT.GetDetail("dtsmris3cu2k0uw3fuo0") + result, err := DTS_CLIENT.GetDetail("dtsbukshhbsvd6yo7z96") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "unConfig", result.Status) +} + +func TestClient_ListDts(t *testing.T) { + var count = 0 + args := &ListDtsArgs{ + Type: "migration", + MaxKeys: 10, + } + for true { + result, err := DTS_CLIENT.ListDts(args) + ExpectEqual(t.Errorf, nil, err) + args.Marker = result.NextMarker + for _, e := range result.Task { + fmt.Println("dtsId: ", e.DtsId) + } + count += len(result.Task) + if !result.IsTruncated { + break + } + } + fmt.Println("count: ", count) +} + +func TestClient_ListDtsWithPage(t *testing.T) { + var count = 0 + args := &ListDtsWithPageArgs{ + Types: []string{"bidirect"}, + Filters: []ListFilter{ + { + Keyword: "he", + KeywordType: "taskName", + }, + }, + PageNo: 1, + PageSize: 10, + Order: "desc", + OrderBy: "createTime", + } + for true { + result, err := DTS_CLIENT.ListDtsWithPage(args) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Result { + fmt.Println("dtsId: ", e.DtsId) + } + count += len(result.Result) + if len(result.Result) < 10 { + break + } + } + fmt.Println("count: ", count) +} + +func TestClient_DeleteDts(t *testing.T) { + err := DTS_CLIENT.DeleteDts("dtsbbpvtjcb6ploqexvf") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ConfigDts(t *testing.T) { + args := &ConfigArgs{ + Type: "migration", + TaskName: "go-sdk-1", + DataType: []string{"increment"}, + SrcConnection: Connection{ + InstanceType: "bcerds", + DbType: "mysql", + InstanceId: "rdsm9744332", + Region: "bj", + FieldWhitelist: "", + FieldBlacklist: "", + }, + DstConnection: Connection{ + InstanceType: "bcerds", + DbType: "mysql", + InstanceId: "rdsmiu336698", + Region: "bj", + SqlType: "I,U", + }, + SchemaMapping: []Schema{ + { + Type: "table", + Src: "hello.user", + Dst: "hello.user", + Where: "", + }, + }, + Granularity: "dbtb", + InitPosition: InitPosition{ + Type: "binlog", + Position: "", + }, + } + result, err := DTS_CLIENT.ConfigDts("dtsmro61533558", args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println("result dtsId: ", result.DtsId) +} + +func TestClient_PreCheck(t *testing.T) { + result, err := DTS_CLIENT.PreCheck("dtsmro61533558") + ExpectEqual(t.Errorf, nil, err) + fmt.Println("result success: ", result.Success) + fmt.Println("result message: ", result.Message) +} + +func TestClient_GetPreCheck(t *testing.T) { + result, err := DTS_CLIENT.GetPreCheck("dtsmro61533558") + ExpectEqual(t.Errorf, nil, err) + fmt.Println("result success: ", result.Success) + for _, e := range result.Result { + fmt.Println("name: ", e.Name, "status: ", e.Status, "Message: ", e.Message, + "Subscription: ", e.Subscription) + } +} + +func TestClient_SkipPreCheck(t *testing.T) { + response, err := DTS_CLIENT.SkipPreCheck("dtsmro61533558") + ExpectEqual(t.Errorf, nil, err) + fmt.Println("response success: ", response.Success) + fmt.Println("response result: ", response.Result) +} + +func TestClient_StartDts(t *testing.T) { + err := DTS_CLIENT.StartDts("dtsmro61533558") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_PauseDts(t *testing.T) { + err := DTS_CLIENT.PauseDts("dtsmro61533558") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ShutdownDts(t *testing.T) { + err := DTS_CLIENT.ShutdownDts("dtsmro61533558") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSchema(t *testing.T) { + args := &GetSchemaArgs{ + Connection: Connection{ + InstanceType: "bcerds", + DbType: "mysql", + InstanceId: "rdsm9744332", + Region: "bj", + FieldWhitelist: "", + FieldBlacklist: "", + }, + } + response, err := DTS_CLIENT.GetSchema(args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println("response success: ", response.Success) + fmt.Println("response result: ", response.Result) +} + +func TestClient_UpdateTaskName(t *testing.T) { + args := &UpdateTaskNameArgs{ + TaskName: "go-sdkkk", + } + err := DTS_CLIENT.UpdateTaskName("dtsbe35xxxx8xzw365", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ResizeTaskStandard(t *testing.T) { + args := &ResizeTaskStandardArgs{ + Standard: "Xlarge", + } + response, err := DTS_CLIENT.ResizeTaskStandard("dtsbexxxxxzw365", args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println("response orderId: ", response.OrderId) +} diff --git a/bce-sdk-go/services/dts/dts.go b/bce-sdk-go/services/dts/dts.go new file mode 100644 index 0000000..c242786 --- /dev/null +++ b/bce-sdk-go/services/dts/dts.go @@ -0,0 +1,379 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// dts.go - the dts APIs definition supported by the DTS service +package dts + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateDts - create a dtsTask with the specific parameters +// +// PARAMS: +// - args: the arguments to create a dtsTask +// +// RETURNS: +// - *CreateDtsResult: the result of create dtsTask, contains new dtsTask's ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateDts(args *CreateDtsArgs) (*CreateDtsResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.ProductType == "" { + return nil, fmt.Errorf("unset ProductType") + } + + if args.Type == "" { + return nil, fmt.Errorf("unset Type") + } + + if args.Standard == "" { + return nil, fmt.Errorf("unset Standard") + } + + if args.SourceInstanceType == "" { + return nil, fmt.Errorf("unset SourceInstanceType") + } + + if args.TargetInstanceType == "" { + return nil, fmt.Errorf("unset TargetInstanceType") + } + + result := &CreateDtsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// DeleteDts - delete a dtsTask +// +// PARAMS: +// - taskId: the specific taskId +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDts(taskId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getDtsUriWithTaskId(taskId)). + Do() +} + +// GetDetail - get a specific dtsTask's detail +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - *DtsTaskMeta: the specific dtsTask's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetDetail(taskId string) (*DtsTaskMeta, error) { + result := &DtsTaskMeta{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDtsUriWithTaskId(taskId)). + WithResult(result). + Do() + + return result, err +} + +// ListDts - list all dtsTask with the specific type +// +// PARAMS: +// - args: the arguments to list all dtsTask with the specific type +// +// RETURNS: +// - *ListDtsResult: the result of list all dtsTask, contains all dtsTask' detail +// - error: nil if success otherwise the specific error +func (c *Client) ListDts(args *ListDtsArgs) (*ListDtsResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.Type == "" { + return nil, fmt.Errorf("unset type") + } + + if args.MaxKeys <= 0 { + args.MaxKeys = 10 + } + if args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListDtsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUri()+"/list"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListDtsWithPage - list all dtsTask with page +// +// PARAMS: +// - args: the arguments to list all dtsTask with page +// +// RETURNS: +// - *ListDtsResult: the result of list all dtsTask, contains all dtsTask' detail +// - error: nil if success otherwise the specific error +func (c *Client) ListDtsWithPage(args *ListDtsWithPageArgs) (*ListDtsWithPageResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.Types == nil || len(args.Types) == 0 { + return nil, fmt.Errorf("unset type") + } + + if args.PageNo <= 0 { + args.PageNo = 1 + } + if args.PageSize > 100 { + args.PageSize = 100 + } + + result := &ListDtsWithPageResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUri()+"/listWithPage"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// PreCheck - precheck a dtsTask +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PreCheck(taskId string) (*PreCheckResult, error) { + result := &PreCheckResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUriWithTaskId(taskId) + "/precheck"). + WithResult(result). + Do() + return result, err +} + +// GetPreCheck - get a precheck result +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - *GetPreCheckResult: the specific dtsTask's precheck result +// - error: nil if success otherwise the specific error +func (c *Client) GetPreCheck(taskId string) (*GetPreCheckResult, error) { + result := &GetPreCheckResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDtsUriWithTaskId(taskId) + "/precheck"). + WithResult(result). + Do() + + return result, err +} + +// SkipPreCheck - skip precheck of a dts task +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SkipPreCheck(taskId string) (*SkipPreCheckResponse, error) { + result := &SkipPreCheckResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDtsUriWithTaskId(taskId)). + WithQueryParam("skipPrecheck", ""). + WithResult(result). + Do() + return result, err +} + +// ConfigDts - config a dtsTask with the specific parameters +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// - args: the arguments to config a dtsTask +// +// RETURNS: +// - *ConfigDtsResult: the result of config dtsTask, contains the dtsTask's ID +// - error: nil if success otherwise the specific error +func (c *Client) ConfigDts(taskId string, args *ConfigArgs) (*ConfigDtsResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.TaskName == "" { + return nil, fmt.Errorf("unset TaskName") + } + + if args.DataType == nil { + return nil, fmt.Errorf("unset DataType") + } + + if args.SchemaMapping == nil { + return nil, fmt.Errorf("unset SchemaMapping") + } + + result := &ConfigDtsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUriWithTaskId(taskId)+"/config"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// StartDts - start a dtsTask +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StartDts(taskId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUriWithTaskId(taskId) + "/start"). + Do() +} + +// PauseDts - pause a dtsTask +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PauseDts(taskId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUriWithTaskId(taskId) + "/pause"). + Do() +} + +// ShutdownDts - shutdown a dtsTask +// +// PARAMS: +// - taskId: the specific dtsTask's ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ShutdownDts(taskId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUriWithTaskId(taskId) + "/shutdown"). + Do() +} + +// GetSchema - get schema +// +// PARAMS: +// - args: connection param +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetSchema(args *GetSchemaArgs) (*GetSchemaResponse, error) { + result := &GetSchemaResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getDtsUri()+"/schema"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpdateTaskName - update task name +// +// PARAMS: +// - args: update task name param +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateTaskName(taskId string, args *UpdateTaskNameArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDtsUriWithTaskId(taskId)). + WithQueryParam("name", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ResizeTaskStandard - resize task standard +// +// PARAMS: +// - args: resize task standard param +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeTaskStandard(taskId string, args *ResizeTaskStandardArgs) (*ResizeTaskStandardResponse, error) { + result := &ResizeTaskStandardResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getDtsUriWithTaskId(taskId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("standard", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) GetVpcs(region string) (*DtsVpcsResult, error) { + result := &DtsVpcsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getDtsUri()+"/vpc"). + WithQueryParam("region", region). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/dts/model.go b/bce-sdk-go/services/dts/model.go new file mode 100644 index 0000000..e0a4c8c --- /dev/null +++ b/bce-sdk-go/services/dts/model.go @@ -0,0 +1,278 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package dts + +type CreateDtsArgs struct { + ClientToken string `json:"-"` + ProductType string `json:"productType"` + Type string `json:"type"` + Standard string `json:"standard"` + SourceInstanceType string `json:"sourceInstanceType"` + TargetInstanceType string `json:"targetInstanceType"` + CrossRegionTag int `json:"crossRegionTag"` + DirectionType string `json:"directionType"` + OrderInfo OrderInfo `json:"orderInfo"` +} + +type CreateDtsResult struct { + DtsTasks []DtsId `json:"dtsTasks"` +} + +type DtsId struct { + DtsId string `json:"dtsId"` +} + +type ConfigDtsResult struct { + DtsId string `json:"dtsId"` +} + +type DtsTaskMeta struct { + DtsId string `json:"dtsId"` + TaskName string `json:"taskName"` + Status string `json:"status"` + DataType []string `json:"dataType"` + Region string `json:"region"` + CreateTime string `json:"createTime"` + SrcConnection Connection `json:"srcConnection"` + DstConnection Connection `json:"dstConnection"` + SchemaMapping []Schema `json:"schemaMapping,omitempty"` + RunningTime int `json:"runningTime"` + SubStatus []SubStatus `json:"subStatus,omitempty"` + DynamicInfo DynamicInfo `json:"dynamicInfo,omitempty"` + Errmsg string `json:"errmsg,omitempty"` + SdkRealtimeProgress string `json:"sdkRealtimeProgress,omitempty"` + Granularity string `json:"granularity,omitempty"` + SubDataScope SubDataScope `json:"subDataScope,omitempty"` + PayInfo PayInfo `json:"payInfo,omitempty"` + LockStatus string `json:"lockStatus,omitempty"` + DtsIdPos string `json:"dtsIdPos,omitempty"` + DtsIdNeg string `json:"dtsIdNeg,omitempty"` + DtsTaskPos *DtsTaskMeta `json:"dtsTaskPos"` + DtsTaskNeg *DtsTaskMeta `json:"dtsTaskNeg"` +} + +type Connection struct { + Region string `json:"region"` + DbType string `json:"dbType"` + DbUser string `json:"dbUser"` + DbPass string `json:"dbPass"` + DbPort int `json:"dbPort"` + DbHost string `json:"dbHost"` + InstanceId string `json:"instanceId"` + DbServer string `json:"dbServer,omitempty"` + InstanceType string `json:"instanceType"` + InstanceShortId string `json:"instanceShortId,omitempty"` + FieldWhitelist string `json:"field_whitelist,omitempty"` + FieldBlacklist string `json:"field_blacklist,omitempty"` + StartTime string `json:"startTime,omitempty"` + EndTime string `json:"endTime,omitempty"` + SqlType string `json:"sqlType,omitempty"` + VpcId string `json:"vpcId"` + VpcName string `json:"vpcName"` + VpcCidr string `json:"vpcCidr"` + VpcShortId string `json:"vpcShortId"` +} + +type Schema struct { + Type string `json:"type"` + Src string `json:"src"` + Dst string `json:"dst"` + Where string `json:"where"` +} + +type SubStatus struct { + S string `json:"s"` + B string `json:"b"` + I string `json:"i"` +} + +type DynamicInfo struct { + Schema []SchemaInfo `json:"schema"` + Base []SchemaInfo `json:"base"` + Increment Increment `json:"increment"` +} + +type Increment struct { + Delay int64 `json:"delay"` + Position string `json:"position"` + SyncStatus string `json:"syncStatus"` +} + +type SchemaInfo struct { + Current string `json:"current"` + Count string `json:"count"` + Speed string `json:"speed"` + ExpectFinishTime string `json:"expectFinishTime"` +} + +type SubDataScope struct { + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` +} + +type PayInfo struct { + ProductType string `json:"productType"` + SourceInstanceType string `json:"sourceInstanceType"` + TargetInstanceType string `json:"targetInstanceType"` + CrossRegionTag int `json:"crossRegionTag"` + CreateTime int `json:"createTime"` + Standard string `json:"standard"` + EndTime string `json:"endTime"` +} + +type ListDtsArgs struct { + Type string `json:"type"` + Status string `json:"status,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + Keyword string `json:"keyword,omitempty"` + KeywordType string `json:"keywordType,omitempty"` +} + +type ListDtsWithPageArgs struct { + Types []string `json:"types"` + Filters []ListFilter `json:"filters"` + Order string `json:"order"` + OrderBy string `json:"orderBy"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type ListFilter struct { + KeywordType string `json:"keywordType"` + Keyword string `json:"keyword"` +} + +type ListDtsResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Task []DtsTaskMeta `json:"task"` +} + +type ListDtsWithPageResult struct { + OrderBy string `json:"orderBy"` + Order string `json:"order"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` + Result []DtsTaskMeta `json:"result"` +} + +type CheckResult struct { + Name string `json:"name"` + Status string `json:"status"` + Message string `json:"message"` + Subscription string `json:"subscription"` +} + +type GetPreCheckResult struct { + Success bool `json:"success"` + Result []CheckResult `json:"result"` +} + +type ConfigArgs struct { + Type string `json:"type,omitempty"` + DtsId string `json:"dtsId,omitempty"` + TaskName string `json:"taskName"` + DataType []string `json:"dataType"` + SrcConnection Connection `json:"srcConnection"` + DstConnection Connection `json:"dstConnection"` + SchemaMapping []Schema `json:"schemaMapping"` + Granularity string `json:"granularity,omitempty"` + ProductType string `json:"productType,omitempty"` + QueueType string `json:"queueType,omitempty"` + InitPosition InitPosition `json:"initPosition,omitempty"` + NetType string `json:"netType,omitempty"` + Admin string `json:"admin,omitempty"` +} + +type InitPosition struct { + Type string `json:"type"` + Position string `json:"position"` +} + +type PreCheckResult struct { + Success bool `json:"success"` + Message string `json:"message"` +} + +type SkipPreCheckResponse struct { + Success bool `json:"success"` + Result string `json:"result"` +} + +type GetSchemaArgs struct { + Connection Connection `json:"connection"` +} + +type GetSchemaResponse struct { + Success bool `json:"success"` + Result GetSchemaResult `json:"result"` +} + +type GetSchemaResult struct { + SchemaAll map[string]ObjectInDb `json:"schemaAll"` +} + +type ObjectInDb struct { + Tables []string `json:"tables"` + Views []string `json:"views"` + Procedures []string `json:"procedures"` + Functions []string `json:"functions"` +} + +type UpdateTaskNameArgs struct { + TaskName string `json:"taskName"` +} + +type ResizeTaskStandardArgs struct { + ClientToken string `json:"-"` + Standard string `json:"standard"` +} + +type ResizeTaskStandardResponse struct { + OrderId string `json:"orderId"` +} + +type OrderInfo struct { + Src Src `json:"src"` + Dst Dst `json:"dst"` +} + +type Src struct { + InstanceType string `json:"instanceType"` + DbType string `json:"dbType"` + SliceNum string `json:"sliceNum"` +} + +type Dst struct { + InstanceType string `json:"instanceType"` + DbType string `json:"dbType"` +} + +type DtsVpcsResult struct { + Vpcs []VpcVo `json:"vpcs"` +} + +type VpcVo struct { + VpcId string `json:"vpcId"` + ShortId string `json:"shortId"` + Name string `json:"name"` + Cidr string `json:"cidr"` +} diff --git a/bce-sdk-go/services/eccr/api.go b/bce-sdk-go/services/eccr/api.go new file mode 100644 index 0000000..c6e21a0 --- /dev/null +++ b/bce-sdk-go/services/eccr/api.go @@ -0,0 +1,589 @@ +package eccr + +import ( + "encoding/base64" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +type Interface interface { + ListInstances(args *ListInstancesArgs) (*ListInstancesResponse, error) + GetInstanceDetail(instanceID string) (*GetInstanceDetailResponse, error) + CreateInstance(args *CreateInstanceArgs) (*CreateInstanceResponse, error) + RenewInstance(orderType string, args *RenewInstanceArgs) (*RenewInstanceResponse, error) + UpdateInstance(instanceID string, args *UpdateInstanceArgs) (*UpdateInstanceResponse, error) + UpgradeInstance(instanceID string, args *UpgradeInstanceArgs) (*UpgradeInstanceResponse, error) + ListPrivateNetworks(instanceID string) (*ListPrivateNetworksResponse, error) + CreatePrivateNetwork(instanceID string, args *CreatePrivateNetworkArgs) (map[string]string, error) + DeletePrivateNetwork(instanceID string, args *DeletePrivateNetworkArgs) error + ListPublicNetworks(instanceID string) (*ListPublicNetworksResponse, error) + UpdatePublicNetwork(instanceID string, args *UpdatePublicNetworkArgs) error + DeletePublicNetworkWhitelist(instanceID string, args *DeletePublicNetworkWhitelistArgs) error + AddPublicNetworkWhitelist(instanceID string, args *AddPublicNetworkWhitelistArgs) error + ResetPassword(instanceID string, args *ResetPasswordArgs) (map[string]string, error) + CreateTemporaryToken(instanceID string, args *CreateTemporaryTokenArgs) (*CreateTemporaryTokenResponse, error) + CreateRegistry(instanceID string, args *CreateRegistryArgs) (*CreateRegistryResponse, error) + GetRegistryDetail(instanceID, registryID string) (*RegistryResponse, error) + ListRegistries(instanceID string, args *ListRegistriesArgs) (*ListRegistriesResponse, error) + CheckHealthRegistry(instanceID string, args *RegistryRequestArgs) error + UpdateRegistry(instanceID, registryID string, args *RegistryRequestArgs) (*RegistryResponse, error) + DeleteRegistry(instanceID, registryID string) error + ListBuildRepositoryTask(instanceID, projectName, repositoryName string, args *ListBuildRepositoryTaskArgs) (*ListBuildRepositoryTaskResponse, error) + CreateBuildRepositoryTask(instanceID, projectName, repositoryName string, args *BuildRepositoryTaskArgs) (*BuildRepositoryTaskResponse, error) + GetBuildRepositoryTask(instanceID, projectName, repositoryName, imageBuildID string) (*BuildRepositoryTaskResult, error) + DeleteBuildRepositoryTask(instanceID, projectName, repositoryName, imageBuildID string) error + BatchDeleteBuildRepositoryTask(instanceID, projectName, repositoryName string, args *BatchDeleteBuildRepositoryTaskArgs) error +} + +// ListInstances - list all instance with the specific parameters +// +// PARAMS: +// - ListInstancesArgs: the arguments to list all instance +// +// RETURNS: +// - ListInstancesResponse: the result of list Instance +// - error: nil if success otherwise the specific error +func (c *Client) ListInstances(args *ListInstancesArgs) (*ListInstancesResponse, error) { + + result := &ListInstancesResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceListURI()). + WithQueryParamFilter("keywordType", args.KeywordType). + WithQueryParamFilter("keyword", args.Keyword). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithQueryParamFilter("acrossregion", args.Acrossregion). + WithResult(result). + Do() + + return result, err +} + +// GetInstanceDetail - get a specific instance detail info +// +// PARAMS: +// - instanceID: the specific instance ID +// +// RETURNS: +// - *GetInstanceDetailResponse: the result of get instance detail info +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceDetail(instanceID string) (*GetInstanceDetailResponse, error) { + + result := &GetInstanceDetailResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceURI(instanceID)). + WithResult(result). + Do() + + return result, err +} + +// CreateInstance - create instance with the specific parameters +// +// PARAMS: +// - CreateInstanceArgs: the arguments to crate Instance +// +// RETURNS: +// - CreateInstanceResponse: the result of create Instance +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstance(args *CreateInstanceArgs) (*CreateInstanceResponse, error) { + result := &CreateInstanceResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getInstanceCreateURI()). + WithResult(result). + WithBody(args). + Do() + + return result, err +} + +// RenewInstance - create instance with the specific parameters +// +// PARAMS: +// - orderType: the operation type, value requires renew +// - ConfirmOrderRequest: the arguments to crate Instance +// +// RETURNS: +// - CreateInstanceResponse: the result of create Instance +// - error: nil if success otherwise the specific error +func (c *Client) RenewInstance(orderType string, args *RenewInstanceArgs) (*RenewInstanceResponse, error) { + result := &RenewInstanceResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithQueryParamFilter("orderType", orderType). + WithURL(getInstanceRenewURI()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateInstance - update instance info +// +// PARAMS: +// - instanceId: the specific instance ID +// - UpdateInstanceArgs: parameters required to update instance info +// +// RETURNS: +// - *UpdateInstanceResponse: the result of updated instance info +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstance(instanceID string, args *UpdateInstanceArgs) (*UpdateInstanceResponse, error) { + result := &UpdateInstanceResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceURI(instanceID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpgradeInstance - upgrade instance by specific parameters +// +// PARAMS: +// - instanceId: the specific instance ID +// - UpgradeInstanceArgs: parameters required to upgrade instance information +// +// RETURNS: +// +// = UpgradeInstanceResponse: the result of upgrade instance +// - error: nil if success otherwise the specific error +func (c *Client) UpgradeInstance(instanceID string, args *UpgradeInstanceArgs) (*UpgradeInstanceResponse, error) { + result := &UpgradeInstanceResponse{} + + err := bce.NewRequestBuilder(c).WithMethod(http.PUT). + WithURL(getInstanceUpgradeURI(instanceID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListPrivateNetworks - list all Privatelinks in an instance with the specific parameters +// +// PARAMS: +// - instanceID: the specific instance ID +// +// RETURNS: +// - *ListPrivateNetworksResponse: the result of list Privatelinks +// - error: nil if success otherwise the specific error +func (c *Client) ListPrivateNetworks(instanceID string) (*ListPrivateNetworksResponse, error) { + result := &ListPrivateNetworksResponse{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getPrivateNetworkListResponseURI(instanceID)). + WithResult(result). + Do() + + return result, err +} + +// CreatePrivateNetwork - create private Network with the specific parameters +// +// PARAMS: +// - instanceID: the specific instance ID +// - CreateInstanceArgs: the arguments to crate private network +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreatePrivateNetwork(instanceID string, args *CreatePrivateNetworkArgs) (map[string]string, error) { + result := make(map[string]string) + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getPrivateNetworkResponseURI(instanceID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// DeletePrivateNetwork - delete private Network with the specific parameters +// +// PARAMS: +// - instanceID: the specific instance ID +// - DeletePrivateNetworkArgs: the arguments to delete private network +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeletePrivateNetwork(instanceID string, args *DeletePrivateNetworkArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getPrivateNetworkResponseURI(instanceID)). + WithBody(args). + Do() + + return err +} + +// ListPublicNetworks - list all Publiclinks in an instance with the specific parameters +// +// PARAMS: +// - instanceID: the specific instance ID +// +// RETURNS: +// - *ListPublicNetworksResponse: the result of list Publiclinks +// - error: nil if success otherwise the specific error +func (c *Client) ListPublicNetworks(instanceID string) (*ListPublicNetworksResponse, error) { + result := &ListPublicNetworksResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getPublicNetworkResponseURI(instanceID)). + WithResult(result).Do() + + return result, err +} + +// UpdatePublicNetwork - update Publiclink +// +// PARAMS: +// - instanceId: the specific instance ID +// - UpdatePublicNetworkArgs: parameters required to update publiclink info +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdatePublicNetwork(instanceID string, args *UpdatePublicNetworkArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getPublicNetworkResponseURI(instanceID)). + WithBody(args). + Do() + + return err +} + +// DeletePublicNetworkWhitelist - delete Publiclink white list +// +// PARAMS: +// - instanceId: the specific instance ID +// - DeletePublicNetworkWhiteListArgs: delete publiclinks list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeletePublicNetworkWhitelist(instanceID string, args *DeletePublicNetworkWhitelistArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getPublicNetworkWhitelistURI(instanceID)). + WithBody(args). + Do() + return err +} + +// AddPublicNetworkWhitelist - add Publiclink white list +// +// PARAMS: +// - instanceId: the specific instance ID +// - DeletePublicNetworkWhiteListArgs: the arguments to delete publiclinks withlist +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AddPublicNetworkWhitelist(instanceID string, args *AddPublicNetworkWhitelistArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getPublicNetworkWhitelistURI(instanceID)). + WithBody(args). + Do() + + return err +} + +// ResetPassword - reset login password +// +// PARAMS: +// - instanceId: the specific instance ID +// - ResetPasswordArgs: the arguments to reset password +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - map[string]string: the result of reset password +func (c *Client) ResetPassword(instanceID string, args *ResetPasswordArgs) (map[string]string, error) { + result := make(map[string]string) + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceCredentialURI(instanceID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateTemporaryToken - create temporary token +// +// PARAMS: +// - instanceID: the specific instance ID +// - CreateTemporaryTokenArgs: the arguments to crate temporary token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateTemporaryToken(instanceID string, args *CreateTemporaryTokenArgs) (*CreateTemporaryTokenResponse, error) { + result := &CreateTemporaryTokenResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getInstanceCredentialURI(instanceID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateRegistry - create registry +// +// PARAMS: +// - instanceID: the specific instance ID +// - CreateRegistryArgs: the arguments to crate registry +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - CreateRegistryResponse: the result od create registry +func (c *Client) CreateRegistry(instanceID string, args *CreateRegistryArgs) (*CreateRegistryResponse, error) { + result := &CreateRegistryResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getInstanceRegistryURI(instanceID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetRegistryDetail - get a specific registry detail info +// +// PARAMS: +// - instanceID: the specific instance ID +// - registryID: the specific registry ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - RegistryResponse: the result of create registry +func (c *Client) GetRegistryDetail(instanceID, registryID string) (*RegistryResponse, error) { + result := &RegistryResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceRegistryIDURI(instanceID, registryID)). + WithResult(result). + Do() + + return result, err +} + +// ListRegistries - get a registry list of instance +// +// PARAMS: +// - instanceID: the specific instance ID +// - ListRegistriesArgs: parameters required to list registry information +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - ListRegistriesResponse: the result of list registry +func (c *Client) ListRegistries(instanceID string, args *ListRegistriesArgs) (*ListRegistriesResponse, error) { + result := &ListRegistriesResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParamFilter("registryName", args.RegistryName). + WithQueryParamFilter("registryType", args.RegistryType). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithURL(getInstanceRegistryURI(instanceID)). + WithResult(result). + Do() + + return result, err +} + +// CheckHealthRegistry - check if the registry is healthy +// +// PARAMS: +// - instanceID: the specific instance ID +// - RegistryRequestArgs: parameters required to check registry +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CheckHealthRegistry(instanceID string, args *RegistryRequestArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getCheckHealthRegistryURI(instanceID)). + WithBody(args). + Do() + + return err +} + +// UpdateRegistry - update the registry info +// +// PARAMS: +// - instanceID: the specific instance ID +// - registryID: the specific registry ID +// - RegistryRequestArgs: parameters required to update registry +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - RegistryResponse: the result of update registry +func (c *Client) UpdateRegistry(instanceID, registryID string, args *RegistryRequestArgs) (*RegistryResponse, error) { + result := &RegistryResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceRegistryIDURI(instanceID, registryID)). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) DeleteRegistry(instanceID, registryID string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getInstanceRegistryIDURI(instanceID, registryID)). + Do() + + return err +} + +// ListBuildRepositoryTask - list the build task info +// +// PARAMS: +// - instanceID: the specific instance ID +// - projectName: the specific project Name +// - repositoryName: the specific registry Name +// - ListBuildRepositoryTaskArgs: parameters required to get task list +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - ListBuildRepositoryTaskResponse: the result of build task list + +func (c *Client) ListBuildRepositoryTask(instanceID, projectName, repositoryName string, args *ListBuildRepositoryTaskArgs) ( + *ListBuildRepositoryTaskResponse, error) { + result := &ListBuildRepositoryTaskResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParamFilter("keywordType", args.KeywordType). + WithQueryParamFilter("keyword", args.Keyword). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithURL(getImageBuildURI(instanceID, projectName, base64.RawURLEncoding.EncodeToString([]byte(repositoryName)))). + WithResult(result). + Do() + + return result, err +} + +// CreateBuildRepositoryTask - create the build task +// +// PARAMS: +// - instanceID: the specific instance ID +// - projectName: the specific project Name +// - repositoryName: the specific registry Name +// - BuildRepositoryTaskArgs: parameters required to create build task +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - BuildRepositoryTaskResponse: the result of build task + +func (c *Client) CreateBuildRepositoryTask(instanceID, projectName, repositoryName string, args *BuildRepositoryTaskArgs) ( + *BuildRepositoryTaskResponse, error) { + result := &BuildRepositoryTaskResponse{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getImageBuildURI(instanceID, projectName, base64.RawURLEncoding.EncodeToString([]byte(repositoryName)))). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetBuildRepositoryTask - get the build task +// +// PARAMS: +// - instanceID: the specific instance ID +// - projectName: the specific project Name +// - repositoryName: the specific registry Name +// - imageBuildID: the specific image build ID +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - BuildRepositoryTaskResult: the result of build task + +func (c *Client) GetBuildRepositoryTask(instanceID, projectName, repositoryName, imageBuildID string) (*BuildRepositoryTaskResult, error) { + result := &BuildRepositoryTaskResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getImageBuildInfoURI(instanceID, projectName, base64.RawURLEncoding.EncodeToString([]byte(repositoryName)), imageBuildID)). + WithResult(result). + Do() + + return result, err +} + +// DeleteBuildRepositoryTask - batch delete the build task +// +// PARAMS: +// - instanceID: the specific instance ID +// - projectName: the specific project Name +// - repositoryName: the specific registry Name +// +// RETURNS: +// - error: nil if success otherwise the specific error + +func (c *Client) DeleteBuildRepositoryTask(instanceID, projectName, repositoryName, imageBuildID string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getImageBuildInfoURI(instanceID, projectName, base64.RawURLEncoding.EncodeToString([]byte(repositoryName)), imageBuildID)). + Do() + + return err +} + +// BatchDeleteBuildRepositoryTask - batch delete the build task +// +// PARAMS: +// - instanceID: the specific instance ID +// - projectName: the specific project Name +// - repositoryName: the specific registry Name +// - BatchDeleteBuildRepositoryTaskArgs: parameters required to batch delete build task +// +// RETURNS: +// - error: nil if success otherwise the specific error + +func (c *Client) BatchDeleteBuildRepositoryTask(instanceID, projectName, repositoryName string, args *BatchDeleteBuildRepositoryTaskArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithBody(args). + WithURL(getImageBuildURI(instanceID, projectName, base64.RawURLEncoding.EncodeToString([]byte(repositoryName)))). + Do() + + return err +} diff --git a/bce-sdk-go/services/eccr/client.go b/bce-sdk-go/services/eccr/client.go new file mode 100644 index 0000000..dcba6ed --- /dev/null +++ b/bce-sdk-go/services/eccr/client.go @@ -0,0 +1,107 @@ +package eccr + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + DEFAULT_ENDPOINT = "ccr." + bce.DEFAULT_REGION + ".baidubce.com" + + URI_PREFIX = bce.URI_PREFIX + "v1" + + REQUEST_INSTANCE_URL = "/instances" + + REQUEST_PRIVATELINK_URL = "/privatelinks" + + REQUEST_PUBLICLINK_URL = "/publiclinks" + + REQUEST_PUBLICLINK_WITHLIST_URL = "/whitelist" + + REQUEST_CREDENTIAL_URL = "/credential" + + REQUEST_REGISTRY_URL = "/registries" + + REQUEST_REPOSITORIES_URL = "/repositories" + + REQUEST_PROJECT_URL = "/projects" + + REQUEST_IMAGEBUILD_URL = "/imagebuilds" +) + +// Client ccr enterprise interface.Interface +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getInstanceListURI() string { + return URI_PREFIX + REQUEST_INSTANCE_URL +} + +func getInstanceURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID +} + +func getInstanceCreateURI() string { + return URI_PREFIX + REQUEST_INSTANCE_URL +} + +func getInstanceRenewURI() string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/renew" +} + +func getInstanceUpgradeURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + "/upgrade" +} + +func getPrivateNetworkListResponseURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_PRIVATELINK_URL +} + +func getPrivateNetworkResponseURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_PRIVATELINK_URL +} + +func getPublicNetworkResponseURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_PUBLICLINK_URL +} + +func getPublicNetworkWhitelistURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_PUBLICLINK_URL + REQUEST_PUBLICLINK_WITHLIST_URL +} + +func getInstanceCredentialURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_CREDENTIAL_URL +} + +func getInstanceRegistryURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_REGISTRY_URL +} + +func getInstanceRegistryIDURI(instanceID, registryID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_REGISTRY_URL + "/" + registryID +} + +func getCheckHealthRegistryURI(instanceID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_REGISTRY_URL + "/ping" +} + +func getImageBuildURI(instanceID, projectName, repositoryName string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_PROJECT_URL + "/" + projectName + + REQUEST_REPOSITORIES_URL + "/" + repositoryName + REQUEST_IMAGEBUILD_URL +} + +func getImageBuildInfoURI(instanceID, projectName, repositoryName, imageBuildID string) string { + return URI_PREFIX + REQUEST_INSTANCE_URL + "/" + instanceID + REQUEST_PROJECT_URL + "/" + projectName + + REQUEST_REPOSITORIES_URL + "/" + repositoryName + REQUEST_IMAGEBUILD_URL + "/" + imageBuildID +} diff --git a/bce-sdk-go/services/eccr/client_test.go b/bce-sdk-go/services/eccr/client_test.go new file mode 100644 index 0000000..3809e0e --- /dev/null +++ b/bce-sdk-go/services/eccr/client_test.go @@ -0,0 +1,475 @@ +package eccr + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + CCR_CLIENT *Client + CCR_INSTANCE_ID string + CCR_REGISTRY_ID string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func TestMain(m *testing.M) { + setup() + code := m.Run() + os.Exit(code) +} + +func setup() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fmt.Println(conf) + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + if err := decoder.Decode(confObj); err != nil { + log.Fatal("decode config obj err:", err) + os.Exit(1) + } + + log.SetLogLevel(log.WARN) + + CCR_CLIENT, err = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + if err != nil { + log.Fatal(err) + } + + log.Info("Setup Complete") +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_ListInstances(t *testing.T) { + args := &ListInstancesArgs{ + KeywordType: "clusterName", + Keyword: "", + PageNo: 1, + PageSize: 10, + } + resp, err := CCR_CLIENT.ListInstances(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_GetInstanceDetail(t *testing.T) { + + resp, err := CCR_CLIENT.GetInstanceDetail(CCR_INSTANCE_ID) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_CreateInstance(t *testing.T) { + + billing := Billing{ + ReservationTimeUnit: "MONTH", + ReservationTime: 1, + AutoRenew: false, + AutoRenewTimeUnit: "MONTH", + AutoRenewTime: 1, + } + + args := &CreateInstanceArgs{ + Type: "BASIC", + Name: "instanceName", + Bucket: "", + PaymentTiming: "prepay", + Billing: billing, + PaymentMethod: []PaymentMethod{}, + } + + resp, err := CCR_CLIENT.CreateInstance(args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_RenewInstance(t *testing.T) { + + orderType := "RENEW" + args := &RenewInstanceArgs{ + Items: []Item{}, + PaymentMethod: []PaymentMethod{}, + } + + resp, err := CCR_CLIENT.RenewInstance(orderType, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_UpdateInstance(t *testing.T) { + + args := &UpdateInstanceArgs{ + Name: "InstanceName", + } + + resp, err := CCR_CLIENT.UpdateInstance(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + + fmt.Println("Response:", string(s)) +} + +func TestClient_UpgradeInstance(t *testing.T) { + + args := &UpgradeInstanceArgs{ + Type: "STANDARD", + PaymentMethod: []PaymentMethod{}, + } + + resp, err := CCR_CLIENT.UpgradeInstance(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_ListPrivateNetworks(t *testing.T) { + + resp, err := CCR_CLIENT.ListPrivateNetworks(CCR_INSTANCE_ID) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_CreatePrivateNetwork(t *testing.T) { + + args := &CreatePrivateNetworkArgs{ + VpcID: "VpcID", + SubnetID: "SubnetID", + IPAddress: "", + IPType: "", + AutoDNSResolve: false, + } + + resp, err := CCR_CLIENT.CreatePrivateNetwork(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_DeletePrivateNetwork(t *testing.T) { + + args := &DeletePrivateNetworkArgs{ + VpcID: "VpcID", + SubnetID: "SubnetID", + } + + err := CCR_CLIENT.DeletePrivateNetwork(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + fmt.Println("Delete Private Network Test Passed") +} + +func TestClient_ListPublicNetworks(t *testing.T) { + + resp, err := CCR_CLIENT.ListPublicNetworks(CCR_INSTANCE_ID) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_UpdatePublicNetwork(t *testing.T) { + args := &UpdatePublicNetworkArgs{ + Action: "open", + } + + err := CCR_CLIENT.UpdatePublicNetwork(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + fmt.Println("Update Public Network Test Passed") + +} + +func TestClient_DeletePublicNetworkWhitelist(t *testing.T) { + args := &DeletePublicNetworkWhitelistArgs{ + Items: []string{"PublicNetworkWhiteListArgs"}, + } + + err := CCR_CLIENT.DeletePublicNetworkWhitelist(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + fmt.Println("Delete Public Network Whitelist Test Passed") +} + +func TestClient_AddPublicNetworkWhitelist(t *testing.T) { + args := &AddPublicNetworkWhitelistArgs{ + IPAddr: "cidrv4", + Description: "", + } + + err := CCR_CLIENT.AddPublicNetworkWhitelist(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + fmt.Println("Add Public Network Whitelist Test Passed") +} + +func TestClient_ResetPassword(t *testing.T) { + args := &ResetPasswordArgs{ + Password: "Password", + } + + resp, err := CCR_CLIENT.ResetPassword(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_CreateTemporaryToken(t *testing.T) { + args := &CreateTemporaryTokenArgs{ + Duration: 10, + } + + resp, err := CCR_CLIENT.CreateTemporaryToken(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_CreateRegistry(t *testing.T) { + args := &CreateRegistryArgs{ + Credential: &RegistryCredential{}, + Description: "", + Insecure: false, + Name: "", + Type: "harbor", + URL: "https://baidu.com", + } + + resp, err := CCR_CLIENT.CreateRegistry(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_GetRegistryDetail(t *testing.T) { + + resp, err := CCR_CLIENT.GetRegistryDetail(CCR_INSTANCE_ID, CCR_REGISTRY_ID) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:" + string(s)) +} + +func TestClient_ListRegistries(t *testing.T) { + args := &ListRegistriesArgs{ + RegistryName: "", + RegistryType: "", + PageNo: 1, + PageSize: 10, + } + + resp, err := CCR_CLIENT.ListRegistries(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.Marshal(resp) + fmt.Println("Response:" + string(s)) +} + +func TestClient_CheckHealthRegistry(t *testing.T) { + args := &RegistryRequestArgs{ + Credential: &RegistryCredential{}, + Description: "", + Insecure: false, + Name: "", + Type: "harbor", + URL: "https://registry.baidubce.com", + } + + err := CCR_CLIENT.CheckHealthRegistry(CCR_INSTANCE_ID, args) + + ExpectEqual(t.Errorf, nil, err) + fmt.Println("Check Health Registry Test Passed") +} + +func TestClient_UpdateRegistry(t *testing.T) { + args := &RegistryRequestArgs{ + Credential: &RegistryCredential{}, + Description: "", + Insecure: true, + Name: "", + Type: "harbor", + URL: "https://registry.baidubce.com", + } + + resp, err := CCR_CLIENT.UpdateRegistry(CCR_INSTANCE_ID, CCR_REGISTRY_ID, args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_DeleteRegistry(t *testing.T) { + + err := CCR_CLIENT.DeleteRegistry(CCR_INSTANCE_ID, CCR_REGISTRY_ID) + + ExpectEqual(t.Errorf, nil, err) + + fmt.Println("Delete Registry Test Passed") +} + +func TestClient_CreateBuildRepositoryTask(t *testing.T) { + args := &BuildRepositoryTaskArgs{ + TagName: "v1.0", + IsLatest: false, + Dockerfile: "from busybox \n yum install pip", + FromType: "dcokerfile", + } + + resp, err := CCR_CLIENT.CreateBuildRepositoryTask(CCR_INSTANCE_ID, "test", "pip", args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_ListBuildRepositoryTaskArgs(t *testing.T) { + args := &ListBuildRepositoryTaskArgs{ + KeywordType: "tag", + Keyword: "v1.0", + PageNo: 1, + PageSize: 10, + } + + resp, err := CCR_CLIENT.ListBuildRepositoryTask(CCR_INSTANCE_ID, "test", "pip", args) + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_GetBuildRepositoryTask(t *testing.T) { + resp, err := CCR_CLIENT.GetBuildRepositoryTask(CCR_INSTANCE_ID, "test", "pip", "1") + + ExpectEqual(t.Errorf, nil, err) + + s, _ := json.MarshalIndent(resp, "", "\t") + fmt.Println("Response:", string(s)) +} + +func TestClient_BatchDeleteBuildRepositoryTask(t *testing.T) { + args := &BatchDeleteBuildRepositoryTaskArgs{ + Items: []string{"1", "2"}, + } + err := CCR_CLIENT.BatchDeleteBuildRepositoryTask(CCR_INSTANCE_ID, "test", "pip", args) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteBuildRepositoryTask(t *testing.T) { + err := CCR_CLIENT.DeleteBuildRepositoryTask(CCR_INSTANCE_ID, "test", "pip", "1") + + ExpectEqual(t.Errorf, nil, err) +} + +func Test_getImageBuildURI(t *testing.T) { + type args struct { + instanceID string + projectName string + repositoryName string + } + tests := []struct { + name string + args args + want string + }{ + { + name: "image build uri", + args: args{ + instanceID: "test_instance", + projectName: "test_project", + repositoryName: "test_repository", + }, + want: fmt.Sprintf(`/v1/projects/%s/repositories/%s/imageBuilds/%s`, "test_instance", "test_project", "test_repository"), + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + if got := getImageBuildURI(tt.args.instanceID, tt.args.projectName, tt.args.repositoryName); got != tt.want { + t.Errorf("getImageBuildURI() = %v, want %v", got, tt.want) + } + }) + } +} diff --git a/bce-sdk-go/services/eccr/model.go b/bce-sdk-go/services/eccr/model.go new file mode 100644 index 0000000..a00c705 --- /dev/null +++ b/bce-sdk-go/services/eccr/model.go @@ -0,0 +1,381 @@ +package eccr + +import ( + "time" +) + +type PagedListOption struct { + PageNo int + PageSize int + KeywordType string + Keyword string +} + +type PageInfo struct { + Total int `json:"total"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type ListInstancesArgs struct { + PageNo int + PageSize int + KeywordType string + Keyword string + Acrossregion string +} + +type ListInstancesResponse struct { + PageInfo `json:",inline"` + Instances []*InstanceInfo `json:"instances"` +} + +type InstanceInfo struct { + ID string `json:"id"` + InstanceType string `json:"instanceType"` + Name string `json:"name"` + Status string `json:"status"` + CreateTime time.Time `json:"createTime"` + Region string `json:"region"` + PublicURL string `json:"publicURL"` + ExpireTime time.Time `json:"expireTime"` +} + +type InstanceStatistic struct { + Repo int64 `json:"repo"` + Chart int64 `json:"chart"` + Namespace int64 `json:"namespace"` + Storage int64 `json:"storage"` +} + +type UserQuota struct { + Repo int64 `json:"repo"` + Chart int64 `json:"chart"` + Namespace int64 `json:"namespace"` +} + +type GetInstanceDetailResponse struct { + Info *InstanceInfo `json:"info,omitempty"` + Statistic InstanceStatistic `json:"statistic,omitempty"` + Quota UserQuota `json:"quota,omitempty"` + Bucket string `json:"bucket,omitempty"` + Region string `json:"region,omitempty"` +} + +type CreateInstanceArgs struct { + Type string `json:"type" binding:"required,oneof=BASIC STANDARD ADVANCED"` + Name string `json:"name" binding:"required,max=256,min=1"` + Bucket string `json:"bucket"` + + PaymentTiming string `json:"paymentTiming" binding:"required,oneof=prepay"` + Billing Billing `json:"billing"` + + PaymentMethod []PaymentMethod `json:"paymentMethod"` +} + +type PaymentMethod struct { + Type string `json:"type"` + Values []string `json:"values"` +} + +type Billing struct { + ReservationTimeUnit string `json:"reservationTimeUnit" binding:"required,oneof=MONTH YEAR"` + ReservationTime int `json:"reservationTime" binding:"required,oneof=1 2 3 4 5 6 7 8 9"` + AutoRenew bool `json:"autoRenew"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit" binding:"oneof=MONTH YEAR"` + AutoRenewTime int `json:"autoRenewTime" binding:"required,oneof=1 2 3 4 5 6 7 8 9"` +} + +type CreateInstanceResponse struct { + InstanceID string `json:"instanceID"` + OrderID string `json:"orderID"` +} + +type RenewInstanceArgs struct { + Items []Item `json:"items"` + // Payment information + PaymentMethod []PaymentMethod `json:"paymentMethod"` +} + +type RenewInstanceResponse struct { + OrderId string `json:"orderId"` +} + +type Item struct { + Config Config `json:"config"` + // Payment information + PaymentMethod []PaymentMethod `json:"paymentMethod"` +} +type Config struct { + // renewal time + Duration int `json:"duration"` + InstanceId string `json:"instanceId"` + // Product name + ServiceType string `json:"serviceType"` + // renew time unit 'year' | 'month' | 'day'; default `month` + TimeUnit string `json:"timeUnit"` + // Whether it is an order that expires uniformly. default(no): no parameter, yes: 1 + UnionExpireOrderFlag string `json:"unionExpireOrderFlag"` + // UUID + UUID string `json:"uuid"` +} + +type UpdateInstanceArgs struct { + Name string `json:"name,omitempty" binding:"required,max=256,min=1"` +} + +type UpdateInstanceResponse struct { + ID string `json:"id"` + InstanceType string `json:"instanceType"` + Name string `json:"name"` + Status string `json:"status"` + CreateTime time.Time `json:"createTime"` + Region string `json:"region"` + PublicURL string `json:"publicURL"` + ExpireTime time.Time `json:"expireTime"` +} + +type UpgradeInstanceArgs struct { + Type string `json:"type" binding:"required,oneof=BASIC STANDARD ADVANCED"` + + PaymentMethod []PaymentMethod `json:"paymentMethod"` +} + +type UpgradeInstanceResponse struct { + OrderID string `json:"orderID"` +} + +type ListPrivateNetworksResponse struct { + Domain string `json:"domain"` + Items []PrivateNetworksItems `json:"items"` +} + +type PrivateNetworksItems struct { + VpcID string `json:"vpcID,omitempty"` + SubnetID string `json:"subnetID,omitempty"` + ServiceNetID string `json:"serviceNetID,omitempty"` + Status string `json:"status,omitempty"` + IPAddress string `json:"ipAddress,omitempty"` + ResourceSource string `json:"resourceSource,omitempty"` +} + +type CreatePrivateNetworkArgs struct { + VpcID string `json:"vpcID,omitempty" binding:"required"` + SubnetID string `json:"subnetID,omitempty" binding:"required"` + IPAddress string `json:"ipAddress,omitempty"` + IPType string `json:"ipType,omitempty"` + AutoDNSResolve bool `json:"autoDnsResolve,omitempty"` +} + +type DeletePrivateNetworkArgs struct { + VpcID string `json:"vpcID,omitempty"` + SubnetID string `json:"subnetID,omitempty"` +} + +type PublicNetworkInfoWhitelist struct { + IPAddr string `json:"ipAddr,omitempty" binding:"required,cidrv4|ipv4"` + Description string `json:"description"` +} + +type ListPublicNetworksResponse struct { + Domain string `json:"domain"` + Status string `json:"status"` + Whitelist []PublicNetworkInfoWhitelist `json:"whitelist"` +} + +type UpdatePublicNetworkArgs struct { + Action string `json:"action,omitempty" enums:"open,close" binding:"required,oneof=open close"` +} + +type DeletePublicNetworkWhitelistArgs struct { + Items []string `json:"items,omitempty" binding:"required"` +} + +type AddPublicNetworkWhitelistArgs struct { + IPAddr string `json:"ipAddr,omitempty" binding:"required,cidrv4|ipv4"` + Description string `json:"description"` +} + +type ResetPasswordArgs struct { + Password string `json:"password,omitempty" binding:"required,password"` +} + +type CreateTemporaryTokenArgs struct { + Duration int `json:"duration,omitempty" binding:"required,min=1,max=24"` +} + +type CreateTemporaryTokenResponse struct { + Password string `json:"password,omitempty"` +} + +type RegistryCredential struct { + + // Access key, e.g. user name when credential type is 'basic'. + AccessKey string `json:"accessKey"` + + // Access secret, e.g. password when credential type is 'basic'. + AccessSecret string `json:"accessSecret,omitempty"` + + // Credential type, such as 'basic', 'oauth'. + Type string `json:"type"` +} + +type CreateRegistryArgs struct { + // credential + Credential *RegistryCredential `json:"credential"` + + // Description of the registry. + Description string `json:"description"` + + // Whether or not the certificate will be verified when Harbor tries to access the server. + Insecure bool `json:"insecure"` + + // The registry name. + Name string `json:"name"` + + // Type of the registry, e.g. 'harbor'. + Type string `json:"type" binding:"required,oneof=harbor docker-hub docker-registry baidu-ccr"` + + // The registry URL string. + URL string `json:"url"` +} + +type CreateRegistryResponse struct { + // The create time of the policy. + CreationTime string `json:"creation_time,omitempty"` + + // credential + Credential *RegistryCredential `json:"credential,omitempty"` + + // Description of the registry. + Description string `json:"description,omitempty"` + + // The registry ID. + ID int64 `json:"id,omitempty"` + + // Whether or not the certificate will be verified when Harbor tries to access the server. + Insecure bool `json:"insecure,omitempty"` + + // The registry name. + Name string `json:"name,omitempty"` + + // Health status of the registry. + Status string `json:"status,omitempty"` + + // Type of the registry, e.g. 'harbor'. + Type string `json:"type,omitempty"` + + // The update time of the policy. + UpdateTime string `json:"update_time,omitempty"` + + // The registry URL string. + URL string `json:"url,omitempty"` +} + +type RegistryResponse struct { + // id + ID int64 `json:"id"` + + // creation time + CreationTime string `json:"creationTime"` + + // credential + Credential *RegistryCredential `json:"credential"` + + // description + Description string `json:"description"` + + // insecure + Insecure bool `json:"insecure"` + + // name + Name string `json:"name"` + + // status + Status string `json:"status"` + + // type + Type string `json:"type"` + + // update time + UpdateTime string `json:"updateTime"` + + // url + URL string `json:"url"` +} + +type ListRegistriesArgs struct { + RegistryName string `json:"registryName"` + RegistryType string `json:"registryType"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type ListRegistriesResponse struct { + PageInfo `json:",inline"` + Items []*RegistryResponse `json:"items"` +} + +type RegistryRequestArgs struct { + // credential + Credential *RegistryCredential `json:"credential"` + + // Description of the registry. + Description string `json:"description"` + + // Whether or not the certificate will be verified when Harbor tries to access the server. + Insecure bool `json:"insecure"` + + // The registry name. + Name string `json:"name"` + + // Type of the registry, e.g. 'harbor'. + Type string `json:"type" binding:"required,oneof=harbor docker-hub docker-registry baidu-ccr"` + + // The registry URL string. + URL string `json:"url"` +} + +type ListBuildRepositoryTaskArgs struct { + KeywordType string `json:"keywordType"` + Keyword string `json:"keyword"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +// ListBuildRepositoryTaskResponse list repository task response +type ListBuildRepositoryTaskResponse struct { + PageInfo `json:",inline"` + Items []*BuildRepositoryTaskResult `json:"items"` +} + +// BuildRepositoryTaskResult build repository task result +type BuildRepositoryTaskResult struct { + ID string `json:"id"` + TagName string `json:"tagName"` + IsLatest bool `json:"isLatest"` + Status string `json:"status"` + FromType string `json:"fromType"` + Dockerfile string `json:"dockerfile"` + CreateBy string `json:"createBy"` + CreateAt time.Time `json:"createAt"` + Image string `json:"image"` +} + +// BuildRepositoryTaskArgs build repository task request +type BuildRepositoryTaskArgs struct { + TagName string `json:"tagName"` + IsLatest bool `json:"isLatest"` + FromType string `json:"fromType"` + Dockerfile string `json:"dockerfile"` +} + +// BuildRepositoryTaskResponse build repository task response +type BuildRepositoryTaskResponse struct { + ID string `json:"id"` +} + +// BatchDeleteBuildRepositoryTaskArgs delete task request +type BatchDeleteBuildRepositoryTaskArgs struct { + Items []string `json:"items"` +} diff --git a/bce-sdk-go/services/eip/client.go b/bce-sdk-go/services/eip/client.go new file mode 100644 index 0000000..8bead1c --- /dev/null +++ b/bce-sdk-go/services/eip/client.go @@ -0,0 +1,102 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for EIP service + +// Package eip defines the EIP services of BCE. The supported APIs are all defined in sub-package +package eip + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "eip." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_EIP_URL = "/eip" + + REQUEST_RECYCLE_EIP_URL = "/eip/recycle" + + REQUEST_EIP_CLUSTER_URL = "/eipcluster" + + REQUEST_EIP_TP_URL = "/eiptp" + + REQUEST_EIP_GROUP_URL = "/eipgroup" + + REQUEST_EIP_BP_URL = "/eipbp" +) + +// Client of EIP service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getEipUri() string { + return URI_PREFIX + REQUEST_EIP_URL +} + +func getEipUriWithEip(eip string) string { + return URI_PREFIX + REQUEST_EIP_URL + "/" + eip +} + +func getRecycleEipUri() string { + return URI_PREFIX + REQUEST_RECYCLE_EIP_URL +} + +func getRecycleEipUriWithEip(eip string) string { + return URI_PREFIX + REQUEST_RECYCLE_EIP_URL + "/" + eip +} + +func getEipClusterUri() string { + return URI_PREFIX + REQUEST_EIP_CLUSTER_URL +} + +func getEipClusterUriWithId(clusterId string) string { + return URI_PREFIX + REQUEST_EIP_CLUSTER_URL + "/" + clusterId +} + +func getEipTpUri() string { + return URI_PREFIX + REQUEST_EIP_TP_URL +} + +func getEipTpUriWithId(id string) string { + return URI_PREFIX + REQUEST_EIP_TP_URL + "/" + id +} + +func getEipGroupUri() string { + return URI_PREFIX + REQUEST_EIP_GROUP_URL +} + +func getEipGroupUriWithId(id string) string { + return URI_PREFIX + REQUEST_EIP_GROUP_URL + "/" + id +} + +func getEipBpUrl() string { + return URI_PREFIX + REQUEST_EIP_BP_URL +} + +func getEipBpUrlWithId(id string) string { + return URI_PREFIX + REQUEST_EIP_BP_URL + "/" + id +} diff --git a/bce-sdk-go/services/eip/client_test.go b/bce-sdk-go/services/eip/client_test.go new file mode 100644 index 0000000..83238f2 --- /dev/null +++ b/bce-sdk-go/services/eip/client_test.go @@ -0,0 +1,434 @@ +package eip + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + EIP_CLIENT *Client + EIP_ADDRESS string + CLUSTER_ID string + // set this value before start test + BCC_TEST_ID = "" + EIP_TP_ID = "" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + EIP_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateEip(t *testing.T) { + args := &CreateEipArgs{ + Name: "sdk-eip", + BandWidthInMbps: 1, + Billing: &Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByTraffic", + }, + ClientToken: getClientToken(), + } + result, err := EIP_CLIENT.CreateEip(args) + ExpectEqual(t.Errorf, nil, err) + + EIP_ADDRESS = result.Eip +} + +func TestClient_BatchCreateEip(t *testing.T) { + args := &BatchCreateEipArgs{ + Name: "sdk-eip", + BandWidthInMbps: 1, + Billing: &Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByBandwidth", + }, + Count: 254, + RouteType: "BGP", + //Idc: "bjdd_cu", + Continuous: true, + ClientToken: getClientToken(), + } + result, err := EIP_CLIENT.BatchCreateEip(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_ResizeEip(t *testing.T) { + args := &ResizeEipArgs{ + NewBandWidthInMbps: 2, + ClientToken: getClientToken(), + } + err := EIP_CLIENT.ResizeEip(EIP_ADDRESS, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindEip(t *testing.T) { + args := &BindEipArgs{ + InstanceType: "BCC", + InstanceId: BCC_TEST_ID, + ClientToken: getClientToken(), + } + err := EIP_CLIENT.BindEip(EIP_ADDRESS, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnBindEip(t *testing.T) { + err := EIP_CLIENT.UnBindEip(EIP_ADDRESS, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_PurchaseReservedEip(t *testing.T) { + args := &PurchaseReservedEipArgs{ + Billing: &Billing{ + Reservation: &Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + } + err := EIP_CLIENT.PurchaseReservedEip(EIP_ADDRESS, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListEip(t *testing.T) { + args := &ListEipArgs{} + EIP_CLIENT.ListEip(args) +} + +func TestClient_DeleteEip(t *testing.T) { + err := EIP_CLIENT.DeleteEip(EIP_ADDRESS, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_OptionalDeleteEip(t *testing.T) { + err := EIP_CLIENT.OptionalDeleteEip(EIP_ADDRESS, getClientToken(), false) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListEipCluster(t *testing.T) { + args := &ListEipArgs{} + result, err := EIP_CLIENT.ListEipCluster(args) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.ClusterList { + ExpectEqual(t.Errorf, "zone-A|zone-C", e.ClusterAz) + ExpectEqual(t.Errorf, "c-76a34e7b", e.ClusterId) + ExpectEqual(t.Errorf, "su-eip-pdd", e.ClusterName) + ExpectEqual(t.Errorf, "su", e.ClusterRegion) + } +} + +func TestClient_GetEipCluster(t *testing.T) { + result, err := EIP_CLIENT.GetEipCluster(CLUSTER_ID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "zone-A|zone-C", result.ClusterAz) + ExpectEqual(t.Errorf, "c-76a34e7b", result.ClusterId) + ExpectEqual(t.Errorf, "su-eip-pdd", result.ClusterName) + ExpectEqual(t.Errorf, "su", result.ClusterRegion) + ExpectEqual(t.Errorf, 240000000000, result.NetworkInBps) + ExpectEqual(t.Errorf, 240000000000, result.NetworkOutBps) + ExpectEqual(t.Errorf, 48000000, result.NetworkInPps) + ExpectEqual(t.Errorf, 48000000, result.NetworkOutPps) +} + +func TestClient_DirectEip(t *testing.T) { + EIP_CLIENT.DirectEip(EIP_ADDRESS, getClientToken()) +} + +func TestClient_UnDirectEip(t *testing.T) { + EIP_CLIENT.UnDirectEip(EIP_ADDRESS, getClientToken()) +} + +func TestClient_ListRecycleEip(t *testing.T) { + args := &ListRecycleEipArgs{ + Marker: "", + MaxKeys: 1, + } + result, err := EIP_CLIENT.ListRecycleEip(args) + ExpectEqual(t.Errorf, nil, err) + fmt.Println(result) +} + +func TestClient_RestoreRecycleEip(t *testing.T) { + err := EIP_CLIENT.RestoreRecycleEip(EIP_ADDRESS, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteRecycleEip(t *testing.T) { + err := EIP_CLIENT.DeleteRecycleEip(EIP_ADDRESS, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateEipTp(t *testing.T) { + args := &CreateEipTpArgs{ + ReservationLength: 1, + Capacity: "10G", + DeductPolicy: "TimeDurationPackage", + PackageType: "WebOutBytes", + ClientToken: getClientToken(), + } + result, err := EIP_CLIENT.CreateEipTp(args) + ExpectEqual(t.Errorf, nil, err) + EIP_TP_ID = result.Id +} + +func TestClient_ListEipTp(t *testing.T) { + args := &ListEipTpArgs{ + Id: "tp-R4E8cWijbf", + DeductPolicy: "FullTimeDurationPackage", + Status: "RUNNING", + } + _, err := EIP_CLIENT.ListEipTp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetEipTp(t *testing.T) { + _, err := EIP_CLIENT.GetEipTp(EIP_TP_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateEipGroup(t *testing.T) { + args := &CreateEipGroupArgs{ + Name: "sdk-eipGroup", + BandWidthInMbps: 500, + Billing: &Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByBandwidth", + }, + EipCount: 254, + RouteType: "BGP", + Continuous: true, + ClientToken: getClientToken(), + } + result, err := EIP_CLIENT.CreateEipGroup(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_ResizeEipGroupBandWidth(t *testing.T) { + args := &ResizeEipGroupArgs{ + BandWidthInMbps: 22, + ClientToken: getClientToken(), + } + EIP_CLIENT.ResizeEipGroupBandWidth("eg-2b1ef0db", args) +} + +func TestClient_EipGroupAddEipCount(t *testing.T) { + args := &GroupAddEipCountArgs{ + EipAddCount: 1, + ClientToken: getClientToken(), + } + EIP_CLIENT.EipGroupAddEipCount("eg-2b1ef0db", args) +} + +func TestClient_ReleaseEipGroupIps(t *testing.T) { + Eips := []string{"100.88.3.216"} + args := &ReleaseEipGroupIpsArgs{ + ReleaseIps: Eips, + ClientToken: getClientToken(), + } + EIP_CLIENT.ReleaseEipGroupIps("eg-2b1ef0db", args) +} + +func TestClient_RenameEipGroup(t *testing.T) { + args := &RenameEipGroupArgs{ + Name: "new_SDK_111", + ClientToken: getClientToken(), + } + EIP_CLIENT.RenameEipGroup("eg-2b1ef0db", args) +} + +func TestClient_ListEipGroup(t *testing.T) { + result, err := EIP_CLIENT.ListEipGroup(nil) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_EipGroupDetail(t *testing.T) { + result, err := EIP_CLIENT.EipGroupDetail("eg-2b1ef0db") + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_EipGroupMoveIn(t *testing.T) { + Ips := []string{"100.88.1.231"} + args := &EipGroupMoveInArgs{ + Eips: Ips, + ClientToken: getClientToken(), + } + err := EIP_CLIENT.EipGroupMoveIn("eg-2b1ef0db", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EipGroupMoveOut(t *testing.T) { + args := &EipGroupMoveOutArgs{ + MoveOutEips: []MoveOutEip{ + { + Eip: "100.88.11.128", + BandWidthInMbps: 11, + Billing: &Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByBandwidth", + }, + }, + }, + ClientToken: getClientToken(), + } + err := EIP_CLIENT.EipGroupMoveOut("eg-2b1ef0db", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EipGroupPurchaseReserved(t *testing.T) { + args := &EipGroupPurchaseReservedArgs{ + Billing: &Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByBandwidth", + }, + ClientToken: getClientToken(), + } + err := EIP_CLIENT.EipGroupPurchaseReserved("eg-2b1ef0db", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateEipBp(t *testing.T) { + args := &CreateEipBpArgs{ + Name: "sdk-eipBp", + Eip: "100.88.3.216", + BandwidthInMbps: 10, + Type: "BandwidthPackage", + AutoReleaseTime: "2023-12-13T20:38:43Z", + ClientToken: getClientToken(), + } + _, err := EIP_CLIENT.CreateEipBp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteEipBp(t *testing.T) { + id := "bw-7fP4jhXO" + clientToken := getClientToken() + err := EIP_CLIENT.DeleteEipBp(id, clientToken) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetEipBp(t *testing.T) { + id := "bw-7fP4jhXO" + clientToken := getClientToken() + _, err := EIP_CLIENT.GetEipBp(id, clientToken) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListEipBp(t *testing.T) { + args := &ListEipBpArgs{ + Id: "bw-7fP4jhXO", + Name: "sdk-eipBp", + Type: "BandwidthPackage", + Marker: "", + MaxKeys: 1000, + BindType: "eip", + } + _, err := EIP_CLIENT.ListEipBp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ResizeEipBp(t *testing.T) { + args := &ResizeEipBpArgs{ + BandwidthInMbps: 10, + ClientToken: getClientToken(), + } + id := "bw-7fP4jhXO" + err := EIP_CLIENT.ResizeEipBp(id, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateEipBp(t *testing.T) { + args := &UpdateEipBpNameArgs{ + Name: "sdk-eipBp", + ClientToken: getClientToken(), + } + id := "bw-7fP4jhXO" + err := EIP_CLIENT.UpdateEipBpName(id, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateEipBpAutoReleaseTime(t *testing.T) { + args := &UpdateEipBpAutoReleaseTimeArgs{ + AutoReleaseTime: "2023-12-13T20:38:43Z", + ClientToken: getClientToken(), + } + id := "bw-7fP4jhXO" + err := EIP_CLIENT.UpdateEipBpAutoReleaseTime(id, args) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/eip/config.json b/bce-sdk-go/services/eip/config.json new file mode 100644 index 0000000..b666209 --- /dev/null +++ b/bce-sdk-go/services/eip/config.json @@ -0,0 +1,5 @@ +{ + "AK":"ak", + "SK":"sk", + "Endpoint":"endpoint" +} diff --git a/bce-sdk-go/services/eip/eip.go b/bce-sdk-go/services/eip/eip.go new file mode 100644 index 0000000..64a4cc4 --- /dev/null +++ b/bce-sdk-go/services/eip/eip.go @@ -0,0 +1,500 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// eip.go - the eip APIs definition supported by the EIP service +package eip + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateEip - create an EIP with the specific parameters +// +// PARAMS: +// - args: the arguments to create an eip +// +// RETURNS: +// - *CreateEipResult: the result of create EIP, contains new EIP's address +// - error: nil if success otherwise the specific error +func (c *Client) CreateEip(args *CreateEipArgs) (*CreateEipResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create eip argments") + } + + if args.Billing == nil { + return nil, fmt.Errorf("please set billing") + } + + result := &CreateEipResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getEipUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// BatchCreateEip - create EIPs with the specific parameters +// +// PARAMS: +// - args: the arguments to create eips +// +// RETURNS: +// - *BatchCreateEipResult: the result of create EIP, contains new EIP's address +// - error: nil if success otherwise the specific error +func (c *Client) BatchCreateEip(args *BatchCreateEipArgs) (*BatchCreateEipResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create eip argments") + } + + if args.Billing == nil { + return nil, fmt.Errorf("please set billing") + } + + result := &BatchCreateEipResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getEipUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("action", "batch"). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ResizeEip - resize an EIP with the specific parameters +// +// PARAMS: +// - eip: the specific EIP +// - args: the arguments to resize an EIP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeEip(eip string, args *ResizeEipArgs) error { + if args == nil { + return fmt.Errorf("please set resize eip argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("resize", ""). + WithBody(args). + Do() +} + +// BindEip - bind an EIP to an instance with the specific parameters +// +// PARAMS: +// - eip: the specific EIP +// - args: the arguments to bind an EIP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindEip(eip string, args *BindEipArgs) error { + if args == nil { + return fmt.Errorf("please set bind eip argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("bind", ""). + WithBody(args). + Do() +} + +// UnBindEip - unbind an EIP +// +// PARAMS: +// - eip: the specific EIP +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindEip(eip, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParam("unbind", ""). + Do() +} + +// DeleteEip - delete an EIP +// +// PARAMS: +// - eip: the specific EIP +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEip(eip, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// OptionalDeleteEip - optionally delete an EIP +// +// PARAMS: +// - eip: the specific EIP +// - clientToken: optional parameter, an Idempotent Token +// - releaseToRecycle: the parameter confirms whether to put the specific EIP in the recycle bin (true) or directly delete it (false) +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) OptionalDeleteEip(eip string, clientToken string, releaseToRecycle bool) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("releaseToRecycle", strconv.FormatBool(releaseToRecycle)). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// ListEip - list all EIP with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eip +// +// RETURNS: +// - *ListEipResult: the result of list all eip, contains new EIP's ID +// - error: nil if success otherwise the specific error +func (c *Client) ListEip(args *ListEipArgs) (*ListEipResult, error) { + if args == nil { + args = &ListEipArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListEipResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipUri()). + WithQueryParamFilter("eip", args.Eip). + WithQueryParamFilter("instanceType", args.InstanceType). + WithQueryParamFilter("instanceId", args.InstanceId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParamFilter("status", args.Status). + WithResult(result). + Do() + + return result, err +} + +// ListRecycleEip - list all EIP in the recycle bin with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eip in the recycle bin +// +// RETURNS: +// - *ListRecycleEipResult: the result of list all eip in the recycle bin +// - error: nil if success otherwise the specific error +func (c *Client) ListRecycleEip(args *ListRecycleEipArgs) (*ListRecycleEipResult, error) { + if args == nil { + args = &ListRecycleEipArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListRecycleEipResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRecycleEipUri()). + WithQueryParamFilter("eip", args.Eip). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// RestoreRecycleEip - restore the specific EIP in the recycle bin +// +// PARAMS: +// - eip: the specific EIP +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RestoreRecycleEip(eip string, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRecycleEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParam("restore", ""). + Do() +} + +// DeleteRecycleEip - delete the specific EIP in the recycle bin +// +// PARAMS: +// - eip: the specific EIP +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecycleEip(eip string, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRecycleEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// PurchaseReservedEip - purchase reserve an eip with the specific parameters +// +// PARAMS: +// - eip: the specific EIP +// - args: the arguments to purchase reserve an eip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) PurchaseReservedEip(eip string, args *PurchaseReservedEipArgs) error { + if args == nil { + return fmt.Errorf("please set purchase reserved eip argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("purchaseReserved", ""). + WithBody(args). + Do() +} + +// StartAutoRenew - start auto renew an eip +// +// PARAMS: +// - eip: the specific EIP +// - args: the arguments to start auto renew an eip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StartAutoRenew(eip string, args *StartAutoRenewArgs) error { + if args == nil { + return fmt.Errorf("please set eip auto renew argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParam("startAutoRenew", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// StopAutoRenew - stop eip auto renew +// +// PARAMS: +// - eip: the specific EIP +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StopAutoRenew(eip string, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParam("stopAutoRenew", ""). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// ListEipCluster - list all EIP Cluster with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eip cluster +// RETURNS: +// - *ListClusterResult: the result of list all eip cluster +// - error: nil if success otherwise the specific error + +func (c *Client) ListEipCluster(args *ListEipArgs) (*ListClusterResult, error) { + if args == nil { + args = &ListEipArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + result := &ListClusterResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipClusterUri()). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetEipCluster - get the eip cluster detail with the clusterId +// +// PARAMS: +// - clusterId: the specific clusterId +// RETURNS: +// - *ClusterDetail: the result of eip cluster detail +// - error: nil if success otherwise the specific error + +func (c *Client) GetEipCluster(clusterId string) (*ClusterDetail, error) { + if len(clusterId) == 0 { + return nil, fmt.Errorf("please set clusterId argment") + } + result := &ClusterDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipClusterUriWithId(clusterId)). + WithResult(result). + Do() + + return result, err +} + +// DirectEip - turn on EIP pass through with the specific parameters +// +// PARAMS: +// - eip: the specific EIP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DirectEip(eip, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParam("direct", ""). + Do() +} + +// UnDirectEip - turn off EIP pass through with the specific parameters +// +// PARAMS: +// - eip: the specific EIP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnDirectEip(eip, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipUriWithEip(eip)). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParam("unDirect", ""). + Do() +} + +// CreateEipTp - create an EIP TP with the specific parameters +// +// PARAMS: +// - args: the arguments to create an eiptp +// +// RETURNS: +// - *CreateEipTpResult: the created eiptp id. +// - error: nil if success otherwise the specific error +func (c *Client) CreateEipTp(args *CreateEipTpArgs) (*CreateEipTpResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create eip tp argments") + } + if len(args.Capacity) == 0 { + return nil, fmt.Errorf("please set capacity argment") + } + result := &CreateEipTpResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getEipTpUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListEipTp - list all EIP TPs with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eiptps +// +// RETURNS: +// - *ListEipTpResult: the result of listing all eiptps +// - error: nil if success otherwise the specific error +func (c *Client) ListEipTp(args *ListEipTpArgs) (*ListEipTpResult, error) { + if args == nil { + args = &ListEipTpArgs{} + } + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + result := &ListEipTpResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipTpUri()). + WithQueryParamFilter("id", args.Id). + WithQueryParamFilter("deductPolicy", args.DeductPolicy). + WithQueryParamFilter("status", args.Status). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetEipTp - get the EIP TP detail with the id +// +// PARAMS: +// - id: the specific eiptp id +// RETURNS: +// - *EipTpDetail: the result of eiptp detail +// - error: nil if success otherwise the specific error + +func (c *Client) GetEipTp(id string) (*EipTpDetail, error) { + if len(id) == 0 { + return nil, fmt.Errorf("please set eiptp id argment") + } + result := &EipTpDetail{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipTpUriWithId(id)). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/eip/eipbp.go b/bce-sdk-go/services/eip/eipbp.go new file mode 100644 index 0000000..4c0bc25 --- /dev/null +++ b/bce-sdk-go/services/eip/eipbp.go @@ -0,0 +1,188 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eip + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateEipBp - create an EIP BP with the specific parameters +// +// PARAMS: +// - args: the arguments to create an eipbp +// +// RETURNS: +// - *CreateEipBpResult: the result of create EIP BP, contains new EIP BP's id +// - error: nil if success otherwise the specific error +func (c *Client) CreateEipBp(args *CreateEipBpArgs) (*CreateEipBpResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create eipbp argments") + } + + result := &CreateEipBpResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getEipBpUrl()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ResizeEIpBp - resize an EIP BP with the specific parameters +// +// PARAMS: +// - id: the id of EIP BP +// - args: the arguments to resize an EIP BP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeEipBp(id string, args *ResizeEipBpArgs) error { + if args == nil { + return fmt.Errorf("please set resize eipbp argments") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipBpUrlWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("resize", ""). + WithBody(args). + Do() + + return err +} + +// GetEipBp - get the EIP BP detail with the id +// +// PARAMS: +// - id: the specific eipbp id +// - clientToken: the specific client token +// +// RETURNS: +// - *EipBpDetail: the result of eipbp detail +// - error: nil if success otherwise the specific error +func (c *Client) GetEipBp(id, clientToken string) (*EipBpDetail, error) { + + result := &EipBpDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipBpUrlWithId(id)). + WithQueryParamFilter("clientToken", clientToken). + WithResult(result). + Do() + + return result, err +} + +// ListEipBp - list all EIP BP with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eipBp +// +// RETURNS: +// - *EipBpListResult: the result of list all eipBp +// - error: nil if success otherwise the specific error +func (c *Client) ListEipBp(args *ListEipBpArgs) (*ListEipBpResult, error) { + if args == nil { + return nil, fmt.Errorf("please set list eipbp argments") + } + + result := &ListEipBpResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipBpUrl()). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParamFilter("id", args.Id). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("bindType", args.BindType). + WithResult(result). + Do() + + return result, err +} + +// UpdateEipBpAutoReleaseTime - update the auto release time of an EIP BP +// +// PARAMS: +// - id: the specific eipbp id +// - args: the arguments to update eipbp auto release time +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEipBpAutoReleaseTime(id string, args *UpdateEipBpAutoReleaseTimeArgs) error { + if args == nil { + return fmt.Errorf("please set update eipbp autoReleaseTime argments") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipBpUrlWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("retime", ""). + WithBody(args). + Do() + + return err +} + +// UpdateEipBpName - update the Name of an EIP BP +// +// PARAMS: +// - id: the specific eipbp id +// - args: the arguments to update eipbp name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEipBpName(id string, args *UpdateEipBpNameArgs) error { + if args == nil { + return fmt.Errorf("please set update eipbp name argments") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipBpUrlWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("rename", ""). + WithBody(args). + Do() + + return err +} + +// DeleteEipBp - delete an EIP BP with the specific id +// +// PARAMS: +// - id: the specific eipbp id +// - clientToken: the specific client token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEipBp(id, clientToken string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getEipBpUrlWithId(id)). + WithQueryParamFilter("clientToken", clientToken). + Do() + + return err +} diff --git a/bce-sdk-go/services/eip/eipgroup.go b/bce-sdk-go/services/eip/eipgroup.go new file mode 100644 index 0000000..643c451 --- /dev/null +++ b/bce-sdk-go/services/eip/eipgroup.go @@ -0,0 +1,273 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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 eip + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateEipGroup - create an EIP_GROUP with the specific parameters +// +// PARAMS: +// - args: the arguments to create an eipGroup +// +// RETURNS: +// - *CreateEipGroupResult: the result of create EIP_GROUP, contains new EIP_GROUP's id +// - error: nil if success otherwise the specific error +func (c *Client) CreateEipGroup(args *CreateEipGroupArgs) (*CreateEipGroupResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create eip argments") + } + + if args.Billing == nil { + return nil, fmt.Errorf("please set billing") + } + + result := &CreateEipGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getEipGroupUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ResizeEipGroupBandWidth - resize an EIP_GROUP with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to resize an EIP_GROUP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeEipGroupBandWidth(id string, args *ResizeEipGroupArgs) error { + if args == nil { + return fmt.Errorf("please set resize argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("resize", ""). + WithBody(args). + Do() +} + +// EipGroupAddEipCount - increase EIP_GROUP's ip count with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to increase EIP_GROUP's ip count +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EipGroupAddEipCount(id string, args *GroupAddEipCountArgs) error { + if args == nil { + return fmt.Errorf("please set resize argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("resize", ""). + WithBody(args). + Do() +} + +// ReleaseEipGroupIps - release EIP_GROUP's ips with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to release EIP_GROUP's ips +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ReleaseEipGroupIps(id string, args *ReleaseEipGroupIpsArgs) error { + if args == nil { + return fmt.Errorf("please set resize argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("resize", ""). + WithBody(args). + Do() +} + +// RenameEipGroup - rename EIP_GROUP's name with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to rename EIP_GROUP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenameEipGroup(id string, args *RenameEipGroupArgs) error { + if args == nil { + return fmt.Errorf("please set rename argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("update", ""). + WithBody(args). + Do() +} + +// DeleteEipGroup - delete an EIP_GROUP +// +// PARAMS: +// - id: the specific EIP_GROUP's id +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEipGroup(id, clientToken string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// ListEipGroup - list all EIP_GROUP with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eipGroup +// +// RETURNS: +// - *ListEipGroupResult: the result of list all eipGroup +// - error: nil if success otherwise the specific error +func (c *Client) ListEipGroup(args *ListEipGroupArgs) (*ListEipGroupResult, error) { + if args == nil { + args = &ListEipGroupArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListEipGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipGroupUri()). + WithQueryParamFilter("id", args.Id). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("status", args.Status). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// EipGroupDetail - get EIP_GROUP detail +// +// PARAMS: +// - id: the eipGroup's id +// +// RETURNS: +// - *EipGroupModel: the result of list all eip in the recycle bin +// - error: nil if success otherwise the specific error +func (c *Client) EipGroupDetail(id string) (*EipGroupModel, error) { + result := &EipGroupModel{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getEipGroupUriWithId(id)). + WithResult(result). + Do() + + return result, err +} + +// EipGroupMoveOut - move eips out of EIP_GROUP with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to move out EIP_GROUP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EipGroupMoveOut(id string, args *EipGroupMoveOutArgs) error { + if args == nil { + return fmt.Errorf("please set argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("move_out", ""). + WithBody(args). + Do() +} + +// EipGroupMoveIn - move eips into to EIP_GROUP with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to move in EIP_GROUP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EipGroupMoveIn(id string, args *EipGroupMoveInArgs) error { + if args == nil { + return fmt.Errorf("please set argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("move_in", ""). + WithBody(args). + Do() +} + +// EipGroupPurchaseReserved - purchase reserved EIP_GROUP with the specific parameters +// +// PARAMS: +// - id: the eipGroup's id +// - args: the arguments to purchase reserved EIP_GROUP +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EipGroupPurchaseReserved(id string, args *EipGroupPurchaseReservedArgs) error { + if args == nil { + return fmt.Errorf("please set argments") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getEipGroupUriWithId(id)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("purchaseReserved", ""). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/eip/model.go b/bce-sdk-go/services/eip/model.go new file mode 100644 index 0000000..952019a --- /dev/null +++ b/bce-sdk-go/services/eip/model.go @@ -0,0 +1,393 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model +package eip + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type Reservation struct { + ReservationLength int `json:"reservationLength,omitempty"` + ReservationTimeUnit string `json:"reservationTimeUnit,omitempty"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming,omitempty"` + BillingMethod string `json:"billingMethod,omitempty"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +type CreateEipArgs struct { + Name string `json:"name,omitempty"` + BandWidthInMbps int `json:"bandwidthInMbps"` + Billing *Billing `json:"billing"` + Tags []model.TagModel `json:"tags"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + RouteType string `json:"routeType,omitempty"` + Idc string `json:"idc,omitempty"` + ClientToken string `json:"-"` +} + +type BatchCreateEipArgs struct { + Name string `json:"name,omitempty"` + BandWidthInMbps int `json:"bandwidthInMbps"` + Billing *Billing `json:"billing"` + Tags []model.TagModel `json:"tags"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + RouteType string `json:"routeType,omitempty"` + Idc string `json:"idc,omitempty"` + Continuous bool `json:"continuous,omitempty"` + Count int `json:"count,omitempty"` + ClientToken string `json:"-"` +} + +type CreateEipResult struct { + Eip string `json:"eip"` +} + +type BatchCreateEipResult struct { + Eips []string `json:"eips"` +} + +type ResizeEipArgs struct { + NewBandWidthInMbps int `json:"newBandwidthInMbps"` + ClientToken string `json:"-"` +} + +type BindEipArgs struct { + InstanceType string `json:"instanceType"` + InstanceId string `json:"instanceId"` + ClientToken string `json:"-"` +} + +type ListEipArgs struct { + Eip string + InstanceType string + InstanceId string + Marker string + MaxKeys int + Status string +} + +type ListEipResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + EipList []EipModel `json:"eipList"` +} + +type EipModel struct { + Name string `json:"name"` + Eip string `json:"eip"` + EipId string `json:"eipId"` + Status string `json:"status"` + EipInstanceType string `json:"eipInstanceType"` + InstanceType string `json:"instanceType"` + InstanceId string `json:"instanceId"` + ShareGroupId string `json:"shareGroupId"` + ClusterId string `json:"clusterId"` + BandWidthInMbps int `json:"bandwidthInMbps"` + PaymentTiming string `json:"paymentTiming"` + BillingMethod string `json:"billingMethod"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + Tags []model.TagModel `json:"tags"` +} + +type ListRecycleEipArgs struct { + Eip string + Name string + Marker string + MaxKeys int +} + +type ListRecycleEipResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + EipList []RecycleEipModel `json:"eipList"` +} + +type RecycleEipModel struct { + Name string `json:"name"` + Eip string `json:"eip"` + EipId string `json:"eipId"` + Status string `json:"status"` + RouteType string `json:"routeType"` + BandWidthInMbps int `json:"bandwidthInMbps"` + PaymentTiming string `json:"paymentTiming"` + BillingMethod string `json:"billingMethod"` + RecycleTime string `json:"recycleTime"` + ScheduledDeleteTime string `json:"scheduledDeleteTime"` +} + +type PurchaseReservedEipArgs struct { + Billing *Billing `json:"billing"` + ClientToken string `json:"clientToken"` +} + +type StartAutoRenewArgs struct { + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + ClientToken string `json:"-"` +} + +type ListClusterResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + ClusterList []ClusterModel `json:"clusterList"` +} + +type ClusterModel struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + ClusterRegion string `json:"clusterRegion"` + ClusterAz string `json:"clusterAz"` +} + +type ClusterDetail struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + ClusterRegion string `json:"clusterRegion"` + ClusterAz string `json:"clusterAz"` + NetworkInBps int64 `json:"networkInBps"` + NetworkOutBps int64 `json:"networkOutBps"` + NetworkInPps int64 `json:"networkInPps"` + NetworkOutPps int64 `json:"networkOutPps"` +} + +type Package struct { + Id string `json:"id,omitempty"` + DeductPolicy string `json:"deductPolicy,omitempty"` + PackageType string `json:"packageType,omitempty"` + Status string `json:"status,omitempty"` + Capacity string `json:"capacity,omitempty"` + UsedCapacity string `json:"usedCapacity,omitempty"` + ActiveTime string `json:"activeTime"` + ExpireTime string `json:"expireTime"` + CreateTime string `json:"createTime"` +} + +type CreateEipTpArgs struct { + ReservationLength int `json:"reservationLength,omitempty"` + Capacity string `json:"capacity,omitempty"` + DeductPolicy string `json:"deductPolicy,omitempty"` + PackageType string `json:"packageType,omitempty"` + ClientToken string `json:"-"` +} + +type CreateEipTpResult struct { + Id string `json:"id,omitempty"` +} + +type ListEipTpArgs struct { + Id string `json:"id,omitempty"` + DeductPolicy string `json:"deductPolicy,omitempty"` + Status string `json:"status,omitempty"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListEipTpResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + PackageList []Package `json:"packageList"` +} + +type EipTpDetail struct { + Id string `json:"id,omitempty"` + DeductPolicy string `json:"deductPolicy,omitempty"` + PackageType string `json:"packageType,omitempty"` + Status string `json:"status,omitempty"` + Capacity string `json:"capacity,omitempty"` + UsedCapacity string `json:"usedCapacity,omitempty"` + ActiveTime string `json:"activeTime,omitempty"` + ExpireTime string `json:"expireTime,omitempty"` + CreateTime string `json:"createTime,omitempty"` +} + +type CreateEipGroupArgs struct { + Name string `json:"name,omitempty"` + EipCount int `json:"eipCount"` + BandWidthInMbps int `json:"bandwidthInMbps"` + Billing *Billing `json:"billing"` + Tags []model.TagModel `json:"tags"` + RouteType string `json:"routeType,omitempty"` + Idc string `json:"idc,omitempty"` + Continuous bool `json:"continuous,omitempty"` + ClientToken string `json:"-"` +} + +type CreateEipGroupResult struct { + Id string `json:"id"` +} + +type ResizeEipGroupArgs struct { + BandWidthInMbps int `json:"bandwidthInMbps"` + ClientToken string `json:"-"` +} + +type GroupAddEipCountArgs struct { + EipAddCount int `json:"eipAddCount"` + ClientToken string `json:"-"` +} + +type ReleaseEipGroupIpsArgs struct { + ReleaseIps []string `json:"releaseIps"` + ClientToken string `json:"-"` +} + +type RenameEipGroupArgs struct { + Name string `json:"name"` + ClientToken string `json:"-"` +} + +type ListEipGroupArgs struct { + Id string + Name string + Marker string + MaxKeys int + Status string +} + +type ListEipGroupResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + EipGroup []EipGroupModel `json:"eipgroups"` +} + +type EipGroupModel struct { + Name string `json:"name"` + Status string `json:"status"` + Id string `json:"id"` + BandWidthInMbps int `json:"bandwidthInMbps"` + DefaultDomesticBandwidth int `json:"defaultDomesticBandwidth"` + BwShortId string `json:"bwShortId"` + BwBandwidthInMbps int `json:"bwBandwidthInMbps"` + DomesticBwShortId string `json:"domesticBwShortId"` + DomesticBwBandwidthInMbps int `json:"domesticBwBandwidthInMbps"` + PaymentTiming string `json:"paymentTiming"` + BillingMethod string `json:"billingMethod"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + Region string `json:"region"` + RouteType string `json:"routeType"` + Eips []EipModel `json:"eips"` +} + +type EipGroupMoveOutArgs struct { + MoveOutEips []MoveOutEip `json:"moveOutEips"` + ClientToken string `json:"-"` +} + +type MoveOutEip struct { + Eip string `json:"eip"` + BandWidthInMbps int `json:"bandwidthInMbps"` + Billing *Billing `json:"billing"` +} + +type EipGroupMoveInArgs struct { + Eips []string `json:"eips"` + ClientToken string `json:"-"` +} + +type EipGroupPurchaseReservedArgs struct { + Billing *Billing `json:"billing"` + ClientToken string `json:"-"` +} + +type CreateEipBpArgs struct { + Name string `json:"name"` + Eip string `json:"eip"` + EipGroupId string `json:"eipGroupId"` + BandwidthInMbps int `json:"bandwidthInMbps"` + Type string `json:"type"` + AutoReleaseTime string `json:"autoReleaseTime"` + ClientToken string `json:"-"` +} + +type CreateEipBpResult struct { + Id string `json:"id"` +} + +type ResizeEipBpArgs struct { + BandwidthInMbps int `json:"bandwidthInMbps"` + ClientToken string `json:"-"` +} + +type EipBpDetail struct { + Name string `json:"name"` + Id string `json:"id"` + BindType string `json:"bindType"` + BandwidthInMbps int `json:"bandwidthInMbps"` + InstanceId string `json:"instanceId"` + Eips []string `json:"eips"` + InstanceBandwidthInMbps int `json:"instanceBandwidthInMbps"` + CreateTime string `json:"createTime"` + AutoReleaseTime string `json:"autoReleaseTime"` + Type string `json:"type"` + Region string `json:"region"` +} + +type ListEipBpArgs struct { + Id string `json:"id"` + Name string `json:"name"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + BindType string `json:"bindType"` + Type string `json:"type"` +} + +type ListEipBpResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + EipGroup []EipBpList `json:"bpList"` +} + +type EipBpList struct { + Name string `json:"name"` + Id string `json:"id"` + BindType string `json:"bindType"` + BandwidthInMbps int `json:"bandwidthInMbps"` + InstanceId string `json:"instanceId"` + Eips []string `json:"eips"` + CreateTime string `json:"createTime"` + AutoReleaseTime string `json:"autoReleaseTime"` + Type string `json:"type"` + Region string `json:"region"` +} + +type UpdateEipBpAutoReleaseTimeArgs struct { + AutoReleaseTime string `json:"autoReleaseTime"` + ClientToken string `json:"-"` +} + +type UpdateEipBpNameArgs struct { + Name string `json:"name"` + ClientToken string `json:"-"` +} diff --git a/bce-sdk-go/services/endpoint/client.go b/bce-sdk-go/services/endpoint/client.go new file mode 100644 index 0000000..c928435 --- /dev/null +++ b/bce-sdk-go/services/endpoint/client.go @@ -0,0 +1,51 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 endpoint + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_ENDPOINT_URL = "/endpoint" +) + +// Client of VPC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForEndpoint() string { + return URI_PREFIX + REQUEST_ENDPOINT_URL +} + +func getURLForEndpointId(endpointId string) string { + return getURLForEndpoint() + "/" + endpointId +} diff --git a/bce-sdk-go/services/endpoint/client_test.go b/bce-sdk-go/services/endpoint/client_test.go new file mode 100644 index 0000000..483f645 --- /dev/null +++ b/bce-sdk-go/services/endpoint/client_test.go @@ -0,0 +1,175 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 endpoint + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + ENDPOINT_CLIENT *Client + + region string + + EndpointId string +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + VPCEndpoint string `json:"Endpoint"` +} + +const ( + PAYMENT_TIMING_POSTPAID PaymentTimingType = "Postpaid" + + VPC_ID string = "vpc-q1hcnhf7nmve" + SUBNET_ID string = "sbn-crqu2vxzj049" + SERVICE string = "77.uservice-a7f5795b.beijing.baidubce.com" +) + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + ENDPOINT_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.VPCEndpoint) + + region = confObj.VPCEndpoint[4:6] + +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_GetService(t *testing.T) { + result, err := ENDPOINT_CLIENT.GetServices() + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_CreateEndpoint(t *testing.T) { + args := &CreateEndpointArgs{ + VpcId: VPC_ID, + Name: "go-sdk-create-1", + SubnetId: SUBNET_ID, + Service: "77.uservice-a7f5795b.beijing.baidubce.com", + Description: "go sdk test", + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + ClientToken: getClientToken(), + } + result, err := ENDPOINT_CLIENT.CreateEndpoint(args) + ExpectEqual(t.Errorf, nil, err) + EndpointId := result.Id + log.Debug(EndpointId) +} + +func TestClient_DeleteEndpoint(t *testing.T) { + err := ENDPOINT_CLIENT.DeleteEndpoint("endpoint-f0f191f0", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateEndpoint(t *testing.T) { + args := &UpdateEndpointArgs{ + ClientToken: getClientToken(), + Name: "go-sdk-2", + Description: "go sdk 2", + } + err := ENDPOINT_CLIENT.UpdateEndpoint("endpoint-3c7e02cb", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListEndpoints(t *testing.T) { + args := &ListEndpointArgs{ + VpcId: VPC_ID, + SubnetId: SUBNET_ID, + } + res, err := ENDPOINT_CLIENT.ListEndpoints(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) +} + +func TestClient_GetEndpointDetail(t *testing.T) { + result, err := ENDPOINT_CLIENT.GetEndpointDetail("endpoint-3c7e02cb") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} +func TestClient_UpdateEndpointNSG(t *testing.T) { + args := &UpdateEndpointNSGArgs{ + SecurityGroupIds: []string{"g-wmxijt06y5um"}, + } + err := ENDPOINT_CLIENT.UpdateEndpointNormalSecurityGroup("endpoint-3c7e02cb", args) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_UpdateEndpointESG(t *testing.T) { + args := &UpdateEndpointESGArgs{ + EnterpriseSecurityGroupIds: []string{"esg-nhwrebdqi4q2"}, + } + err := ENDPOINT_CLIENT.UpdateEndpointEnterpriseSecurityGroup("endpoint-3c7e02cb", args) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/endpoint/endpoint.go b/bce-sdk-go/services/endpoint/endpoint.go new file mode 100644 index 0000000..3e772f3 --- /dev/null +++ b/bce-sdk-go/services/endpoint/endpoint.go @@ -0,0 +1,198 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// endpoint.go - the endpoint APIs definition supported by the endpoint service +package endpoint + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// GetServices - get the public services +// RETURNS: +// - *ListServiceResult: the result of public service +// - error: nil if success otherwise the specific error +func (c *Client) GetServices() (*ListServiceResult, error) { + result := &ListServiceResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEndpoint() + "/publicService"). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// CreateEndpoint - create an endpoint with the specific parameters +// +// PARAMS: +// - args: the arguments to create an endpoint +// +// RETURNS: +// - *CreateEndpointResult: the result of create endpoint +// - error: nil if success otherwise the specific error +func (c *Client) CreateEndpoint(args *CreateEndpointArgs) (*CreateEndpointResult, error) { + if args == nil { + return nil, fmt.Errorf("The createEndpointArgs cannot be nil.") + } + + result := &CreateEndpointResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEndpoint()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// DeleteEndpoint - delete an endpoint +// +// PARAMS: +// - endpointId: the specific endpointId +// - clientToken: optional parameter, an Idempotent Token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEndpoint(endpointId string, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEndpointId(endpointId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// UpdateEndpoint - update an endpoint +// +// PARAMS: +// - endpointId: the specific endpointId +// - UpdateEndpointArgs: the arguments to update an endpoint +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEndpoint(endpointId string, args *UpdateEndpointArgs) error { + if args == nil { + return fmt.Errorf("The updateEndpointArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEndpointId(endpointId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// ListEndpoints - list all endpoint with the specific parameters +// +// PARAMS: +// - args: the arguments to list all endpoint +// +// RETURNS: +// - *ListEndpointResult: the result of list all endpoint +// - error: nil if success otherwise the specific error +func (c *Client) ListEndpoints(args *ListEndpointArgs) (*ListEndpointResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListEndpointArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListEndpointResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEndpoint()). + WithMethod(http.GET). + WithQueryParam("vpcId", args.VpcId). + WithQueryParam("name", args.Name). + WithQueryParam("ipAddress", args.IpAddress). + WithQueryParam("status", args.Status). + WithQueryParam("subnetId", args.SubnetId). + WithQueryParam("service", args.Service). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetEndpointDetail - get the endpoint detail +// +// PARAMS: +// - endpointId: the specific endpointId +// +// RETURNS: +// - *Endpoint: the endpoint +// - error: nil if success otherwise the specific error +func (c *Client) GetEndpointDetail(endpointId string) (*Endpoint, error) { + result := &Endpoint{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEndpointId(endpointId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// UpdateEndpointNormalSecurityGroup - update normal security group bound to the endpoint +// +// PARAMS: +// - endpointId: the specific endpointId +// - args: the arguments to update a normal security group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEndpointNormalSecurityGroup(endpointId string, args *UpdateEndpointNSGArgs) error { + if args == nil { + return fmt.Errorf("The UpdateEndpointNSGArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEndpointId(endpointId)). + WithMethod(http.PUT). + WithQueryParam("bindSg", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// UpdateEndpointEnterpriseSecurityGroup - update enterprise security group bound to the endpoint +// +// PARAMS: +// - endpointId: the specific endpointId +// - args: the arguments to update an enterprise security group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEndpointEnterpriseSecurityGroup(endpointId string, args *UpdateEndpointESGArgs) error { + if args == nil { + return fmt.Errorf("The UpdateEndpointESGArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEndpointId(endpointId)). + WithMethod(http.PUT). + WithQueryParam("bindEsg", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/endpoint/model.go b/bce-sdk-go/services/endpoint/model.go new file mode 100644 index 0000000..7b26f88 --- /dev/null +++ b/bce-sdk-go/services/endpoint/model.go @@ -0,0 +1,96 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 endpoint + +type Endpoint struct { + EndpointId string `json:"endpointId"` + Name string `json:"name"` + IpAddress string `json:"ipAddress"` + Status string `json:"status"` + Service string `json:"service"` + SubnetId string `json:"subnetId"` + Description string `json:"description"` + CreateTime string `json:"createTime"` + VpcId string `json:"vpcId"` + ProductType string `json:"productType"` +} + +type ListEndpointArgs struct { + VpcId string + Name string + IpAddress string + Status string + SubnetId string + Service string + Marker string + MaxKeys int +} + +type ListEndpointResult struct { + Endpoints []Endpoint `json:"endpoints"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type ListServiceResult struct { + Services []string `json:"services"` +} + +type UpdateEndpointArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description"` +} + +type UpdateEndpointNSGArgs struct { + SecurityGroupIds []string `json:"securityGroupIds"` + ClientToken string `json:"-"` +} +type UpdateEndpointESGArgs struct { + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` + ClientToken string `json:"-"` +} + +type CreateEndpointArgs struct { + ClientToken string `json:"-"` + VpcId string `json:"vpcId"` + Name string `json:"name"` + SubnetId string `json:"subnetId"` + Service string `json:"service"` + Description string `json:"description,omitempty"` + IpAddress string `json:"ipAddress,omitempty"` + Billing *Billing `json:"billing"` +} + +type CreateEndpointResult struct { + Id string `json:"id"` + IpAddress string `json:"ipAddress"` +} + +type Billing struct { + PaymentTiming PaymentTimingType `json:"paymentTiming,omitempty"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +type ( + PaymentTimingType string +) + +type Reservation struct { + ReservationLength int `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} diff --git a/bce-sdk-go/services/eni/client.go b/bce-sdk-go/services/eni/client.go new file mode 100644 index 0000000..cb801eb --- /dev/null +++ b/bce-sdk-go/services/eni/client.go @@ -0,0 +1,51 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 eni + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENI = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_ENI_URL = "/eni" +) + +// Client of ENI service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENI + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForEni() string { + return URI_PREFIX + REQUEST_ENI_URL +} + +func getURLForEniId(eniId string) string { + return getURLForEni() + "/" + eniId +} diff --git a/bce-sdk-go/services/eni/client_test.go b/bce-sdk-go/services/eni/client_test.go new file mode 100644 index 0000000..8fb4532 --- /dev/null +++ b/bce-sdk-go/services/eni/client_test.go @@ -0,0 +1,310 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 eni + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + ENI_CLIENT *Client + region string +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +const ( + VPC_ID string = "vpc-q1hcnhf7nmve" + SUBNET_ID string = "sbn-cxwi5hmf8ugx" +) + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + ENI_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + + region = confObj.Endpoint[4:6] + +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateEni(t *testing.T) { + args := &CreateEniArgs{ + Name: "GO_SDK_TEST_CREATE", + SubnetId: "sbn-56s25qecigix", + EnterpriseSecurityGroupIds: []string{ + "esg-rn49gxbin4x7", + }, + PrivateIpSet: []PrivateIp{ + { + Primary: true, + PrivateIpAddress: "", + }, + }, + Ipv6PrivateIpSet: []PrivateIp{ + { + Primary: false, + PrivateIpAddress: "2400:da00:e003:0:1d2:100:0:15", + }, + }, + Description: "go sdk test", + ClientToken: getClientToken(), + } + result, err := ENI_CLIENT.CreateEni(args) + ExpectEqual(t.Errorf, nil, err) + EniId := result.EniId + log.Debug(EniId) +} + +func TestClient_UpdateEni(t *testing.T) { + args := &UpdateEniArgs{ + EniId: "eni-mmwvvbvfjch3", + ClientToken: getClientToken(), + Name: "hzb_3_1", + Description: "go sdk 2", + } + err := ENI_CLIENT.UpdateEni(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteEni(t *testing.T) { + args := &DeleteEniArgs{ + EniId: "eni-darynwwu5xk0", + ClientToken: getClientToken(), + } + err := ENI_CLIENT.DeleteEni(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListEnis(t *testing.T) { + args := &ListEniArgs{ + VpcId: VPC_ID, + //InstanceId: "i-FodWXDUY", + Name: "eni", + } + res, err := ENI_CLIENT.ListEni(args) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) +} + +func TestClient_GetEniDetail(t *testing.T) { + result, err := ENI_CLIENT.GetEniDetail("eni-wbi6thg2p6vj") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_AddPrivateIp(t *testing.T) { + args := &EniPrivateIpArgs{ + EniId: "eni-6c6b8dt4m8rt", + ClientToken: getClientToken(), + PrivateIpAddress: "192.168.0.32", + } + result, err := ENI_CLIENT.AddPrivateIp(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_BatchAddPrivateIp(t *testing.T) { + args := &EniBatchPrivateIpArgs{ + EniId: "eni-gay686fr93e3", + ClientToken: getClientToken(), + PrivateIpAddresses: []string{ + "192.168.0.28", + "192.168.0.29", + }, + } + result, err := ENI_CLIENT.BatchAddPrivateIp(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_BatchAddPrivateIpCrossSubnet(t *testing.T) { + args := &EniBatchAddPrivateIpCrossSubnetArgs{ + EniId: "eni-gay686fr93e3", + ClientToken: getClientToken(), + SubnetId: "sbn-5vhut3bxmumi", + PrivateIpAddressCount: 2, + } + result, err := ENI_CLIENT.BatchAddPrivateIpCrossSubnet(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_DeletePrivateIp(t *testing.T) { + args := &EniPrivateIpArgs{ + EniId: "eni-6c6b8dt4m8rt", + ClientToken: getClientToken(), + PrivateIpAddress: "192.168.0.32", + } + err := ENI_CLIENT.DeletePrivateIp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BatchDeletePrivateIp(t *testing.T) { + args := &EniBatchPrivateIpArgs{ + EniId: "eni-6c6b8dt4m8rt", + ClientToken: getClientToken(), + PrivateIpAddresses: []string{ + "192.168.0.34", + "192.168.0.35", + }, + } + err := ENI_CLIENT.BatchDeletePrivateIp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_AttachEniInstance(t *testing.T) { + args := &EniInstance{ + EniId: "eni-pw4tqi2f9gvq", + ClientToken: getClientToken(), + InstanceId: "i-KdT8ptiu", + } + err := ENI_CLIENT.AttachEniInstance(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DetachEniInstance(t *testing.T) { + args := &EniInstance{ + EniId: "eni-pw4tqi2f9gvq", + ClientToken: getClientToken(), + InstanceId: "i-KdT8ptiu", + } + err := ENI_CLIENT.DetachEniInstance(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindEniPublicIp(t *testing.T) { + args := &BindEniPublicIpArgs{ + EniId: "eni-mmwvvbvfjch3", + ClientToken: getClientToken(), + PrivateIpAddress: "192.168.0.54", + PublicIpAddress: "100.88.8.55", + } + err := ENI_CLIENT.BindEniPublicIp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnBindEniPublicIp(t *testing.T) { + args := &UnBindEniPublicIpArgs{ + EniId: "eni-mmwvvbvfjch3", + ClientToken: getClientToken(), + PublicIpAddress: "100.88.8.55", + } + err := ENI_CLIENT.UnBindEniPublicIp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateEniSecurityGroup(t *testing.T) { + args := &UpdateEniSecurityGroupArgs{ + EniId: "eni-mmwvvbvfjch3", + ClientToken: getClientToken(), + SecurityGroupIds: []string{ + "g-eqhqsbs84yww", + "g-8bfifey0s4h3", + }, + } + err := ENI_CLIENT.UpdateEniSecurityGroup(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateEniEnterpriseSecurityGroup(t *testing.T) { + args := &UpdateEniEnterpriseSecurityGroupArgs{ + EniId: "eni-7c9yzhkfn9c2", + ClientToken: getClientToken(), + EnterpriseSecurityGroupIds: []string{ + "esg-e28mnj5vbrv5", + }, + } + err := ENI_CLIENT.UpdateEniEnterpriseSecurityGroup(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetEniIPQuota(t *testing.T) { + args := &EniQuoteArgs{EniId: "eni-bd1ivf6ui4di"} + result, err := ENI_CLIENT.GetEniQuota(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_GetEniBindQuota(t *testing.T) { + args := &EniQuoteArgs{InstanceId: "i-0v5XVO8M"} + result, err := ENI_CLIENT.GetEniQuota(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} diff --git a/bce-sdk-go/services/eni/config.json b/bce-sdk-go/services/eni/config.json new file mode 100644 index 0000000..5a6634f --- /dev/null +++ b/bce-sdk-go/services/eni/config.json @@ -0,0 +1,5 @@ +{ + "AK":"", + "SK":"", + "Endpoint":"" +} diff --git a/bce-sdk-go/services/eni/eni.go b/bce-sdk-go/services/eni/eni.go new file mode 100644 index 0000000..030b5ee --- /dev/null +++ b/bce-sdk-go/services/eni/eni.go @@ -0,0 +1,440 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// eni.go - the eni APIs definition supported by the eni service +package eni + +import ( + "fmt" + "strconv" + "strings" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateEni - create an eni with the specific parameters +// +// PARAMS: +// - args: the arguments to create an eni +// +// RETURNS: +// - *CreateEniResult: the result of create eni +// - error: nil if success otherwise the specific error +func (c *Client) CreateEni(args *CreateEniArgs) (*CreateEniResult, error) { + if args == nil { + return nil, fmt.Errorf("The createEniArgs cannot be nil.") + } + + result := &CreateEniResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEni()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// UpdateEni - update an eni +// +// PARAMS: +// - UpdateEniArgs: the arguments to update an eni +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEni(args *UpdateEniArgs) error { + if args == nil { + return fmt.Errorf("The updateEniArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("modifyAttribute", ""). + Do() +} + +// DeleteEni - delete an eni +// +// PARAMS: +// - DeleteEniArgs: the arguments to delete an eni +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEni(args *DeleteEniArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// ListEnis - list all eni with the specific parameters +// +// PARAMS: +// - args: the arguments to list all eni +// +// RETURNS: +// - *ListEniResult: the result of list all eni +// - error: nil if success otherwise the specific error +func (c *Client) ListEni(args *ListEniArgs) (*ListEniResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListEniArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListEniResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForEni()). + WithMethod(http.GET). + WithQueryParam("vpcId", args.VpcId). + WithQueryParamFilter("instanceId", args.InstanceId). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)) + + if len(args.PrivateIpAddress) != 0 { + builder.WithQueryParam("privateIpAddress", + strings.Replace(strings.Trim(fmt.Sprint(args.PrivateIpAddress), "[]"), " ", ",", -1)) + } + + err := builder.WithResult(result).Do() + + return result, err +} + +// GetEniDetail - get the eni detail +// +// PARAMS: +// - eniId: the specific eniId +// +// RETURNS: +// - *Eni: the eni +// - error: nil if success otherwise the specific error +func (c *Client) GetEniDetail(eniId string) (*Eni, error) { + if eniId == "" { + return nil, fmt.Errorf("The eniId cannot be empty.") + } + + result := &Eni{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(eniId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// AddPrivateIp - add private ip +// +// PARAMS: +// - args: the arguments to add private ip +// +// RETURNS: +// - *AddPrivateIpResult: the private ip +// - error: nil if success otherwise the specific error +func (c *Client) AddPrivateIp(args *EniPrivateIpArgs) (*AddPrivateIpResult, error) { + if args == nil { + return nil, fmt.Errorf("The EniPrivateIpArgs cannot be nil.") + } + + result := &AddPrivateIpResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)+"/privateIp"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// BatchAddPrivateIp - batch add private ips +// +// PARAMS: +// - args: the arguments to batch add private ips, property PrivateIpAddresses or PrivateIpAddressCount is required; +// when PrivateIpAddressCount is set, private ips will be auto allocated, +// and if you want assign private ips, please just set PrivateIpAddresses; +// +// RETURNS: +// - *BatchAddPrivateIpResult: the private ips +// - error: nil if success otherwise the specific error +func (c *Client) BatchAddPrivateIp(args *EniBatchPrivateIpArgs) (*BatchAddPrivateIpResult, error) { + if args == nil { + return nil, fmt.Errorf("The EniBatchPrivateIpArgs cannot be nil.") + } + + result := &BatchAddPrivateIpResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)+"/privateIp/batchAdd"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// BatchAddPrivateIpCrossSubnet - batch add private ips that support cross subnet, white list function +// +// PARAMS: +// - args: the arguments to batch add private ips, property PrivateIps or PrivateIpAddressCount is required; +// when PrivateIpAddressCount is set, private ips in subnet assigned by 'SubnetId' property will be auto allocated; +// if you want assign private ips, please just set PrivateIps, and you can also assgin subnet with property 'PrivateIpArgs.SubnetId'; +// +// RETURNS: +// - *BatchAddPrivateIpResult: the private ips +// - error: nil if success otherwise the specific error +func (c *Client) BatchAddPrivateIpCrossSubnet(args *EniBatchAddPrivateIpCrossSubnetArgs) (*BatchAddPrivateIpResult, error) { + if args == nil { + return nil, fmt.Errorf("The EniBatchAddPrivateIpCrossSubnetArgs cannot be nil.") + } + + result := &BatchAddPrivateIpResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)+"/privateIp/batchAddCrossSubnet"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// DeletePrivateIp - delete private ip +// +// PARAMS: +// - args: the arguments to delete private ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeletePrivateIp(args *EniPrivateIpArgs) error { + if args == nil { + return fmt.Errorf("The EniPrivateIpArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)+"/privateIp/"+args.PrivateIpAddress). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// BatchDeletePrivateIp - batch delete private ip +// +// PARAMS: +// - args: the arguments to batch delete private ipa +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchDeletePrivateIp(args *EniBatchPrivateIpArgs) error { + if args == nil { + return fmt.Errorf("The EniBatchPrivateIpArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)+"/privateIp/batchDel"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// AttachEniInstance - eni attach instance +// +// PARAMS: +// - args: the arguments to attach instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AttachEniInstance(args *EniInstance) error { + if args == nil { + return fmt.Errorf("The EniInstance cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithQueryParam("attach", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// DetachEniInstance - eni detach instance +// +// PARAMS: +// - args: the arguments to detach instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DetachEniInstance(args *EniInstance) error { + if args == nil { + return fmt.Errorf("The EniInstance cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithQueryParam("detach", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// BindEniPublicIp - eni bind public ip +// +// PARAMS: +// - args: the arguments to bind public ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindEniPublicIp(args *BindEniPublicIpArgs) error { + if args == nil { + return fmt.Errorf("The BindEniPublicIpArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithQueryParam("bind", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// UnBindEniPublicIp - eni unbind public ip +// +// PARAMS: +// - args: the arguments to unbind public ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindEniPublicIp(args *UnBindEniPublicIpArgs) error { + if args == nil { + return fmt.Errorf("The UnBindEniPublicIpArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithQueryParam("unBind", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// UpdateEniSecurityGroup - update eni sg +// +// PARAMS: +// - args: the arguments to update eni sg +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEniSecurityGroup(args *UpdateEniSecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("The UpdateEniSecurityGroupArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithQueryParam("bindSg", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// UpdateEniEnterpriseSecurityGroup - update eni enterprise security group +// +// PARAMS: +// - args: the arguments to update eni enterprise security group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEniEnterpriseSecurityGroup(args *UpdateEniEnterpriseSecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("The UpdateEniEnterpriseSecurityGroupArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(args.EniId)). + WithMethod(http.PUT). + WithQueryParam("bindEsg", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +func (c *Client) GetEniQuota(args *EniQuoteArgs) (*EniQuoteInfo, error) { + + result := &EniQuoteInfo{} + request := bce.NewRequestBuilder(c). + WithURL(getURLForEni() + "/quota"). + WithMethod(http.GET) + if args.EniId != "" { + request.WithQueryParam("eniId", args.EniId) + } + if args.InstanceId != "" { + request.WithQueryParam("instanceId", args.InstanceId) + } + err := request.WithResult(result).Do() + + return result, err +} + +// GetEniStatus - get an eni status +// +// PARAMS: +// - eniId: the arguments to get an eni status +// +// RETURNS: +// - *EniStatusInfo: the result of get an eni status +// - error: nil if success otherwise the specific error +func (c *Client) GetEniStatus(eniId string) (*EniStatusInfo, error) { + result := &EniStatusInfo{} + request := bce.NewRequestBuilder(c). + WithURL(getURLForEniId(eniId) + "/status"). + WithMethod(http.GET) + err := request.WithResult(result).Do() + + return result, err +} diff --git a/bce-sdk-go/services/eni/model.go b/bce-sdk-go/services/eni/model.go new file mode 100644 index 0000000..b4dc353 --- /dev/null +++ b/bce-sdk-go/services/eni/model.go @@ -0,0 +1,165 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 eni + +type CreateEniArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + SubnetId string `json:"subnetId"` + InstanceId string `json:"instanceId,omitempty"` + SecurityGroupIds []string `json:"securityGroupIds"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` + PrivateIpSet []PrivateIp `json:"privateIpSet"` + Ipv6PrivateIpSet []PrivateIp `json:"ipv6PrivateIpSet,omitempty"` + Description string `json:"description,omitempty"` +} + +type CreateEniResult struct { + EniId string `json:"eniId"` +} + +type UpdateEniArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description"` +} + +type DeleteEniArgs struct { + EniId string + ClientToken string +} + +type ListEniArgs struct { + VpcId string + InstanceId string + Name string + Marker string + MaxKeys int + PrivateIpAddress []string `json:"privateIpAddress,omitempty"` +} + +type ListEniResult struct { + Eni []Eni `json:"enis"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type Eni struct { + EniId string `json:"eniId"` + Name string `json:"name"` + ZoneName string `json:"zoneName"` + Description string `json:"description"` + InstanceId string `json:"instanceId"` + MacAddress string `json:"macAddress"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Status string `json:"status"` + PrivateIpSet []PrivateIp `json:"privateIpSet"` + Ipv6PrivateIpSet []PrivateIp `json:"ipv6PrivateIpSet"` + SecurityGroupIds []string `json:"securityGroupIds"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` + CreatedTime string `json:"createdTime"` +} + +type PrivateIp struct { + PublicIpAddress string `json:"publicIpAddress"` + Primary bool `json:"primary"` + PrivateIpAddress string `json:"privateIpAddress"` +} + +type EniPrivateIpArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + IsIpv6 bool `json:"isIpv6,omitempty"` + PrivateIpAddress string `json:"privateIpAddress"` +} + +type EniBatchPrivateIpArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + IsIpv6 bool `json:"isIpv6,omitempty"` + PrivateIpAddresses []string `json:"privateIpAddresses"` + PrivateIpAddressCount int `json:"privateIpAddressCount,omitempty"` +} + +type EniBatchAddPrivateIpCrossSubnetArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + SubnetId string `json:"subnetId"` + IsIpv6 bool `json:"isIpv6,omitempty"` + PrivateIps []PrivateIpArgs `json:"privateIps"` + PrivateIpAddressCount int `json:"privateIpAddressCount,omitempty"` +} + +type PrivateIpArgs struct { + PrivateIpAddress string `json:"privateIpAddress"` + SubnetId string `json:"subnetId"` +} + +type AddPrivateIpResult struct { + PrivateIpAddress string `json:"privateIpAddress"` +} + +type BatchAddPrivateIpResult struct { + PrivateIpAddresses []string `json:"privateIpAddresses"` +} + +type EniInstance struct { + EniId string `json:"-"` + InstanceId string `json:"instanceId"` + ClientToken string `json:"-"` +} + +type BindEniPublicIpArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + PrivateIpAddress string `json:"privateIpAddress"` + PublicIpAddress string `json:"publicIpAddress"` +} + +type UnBindEniPublicIpArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + PublicIpAddress string `json:"publicIpAddress"` +} + +type UpdateEniSecurityGroupArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type UpdateEniEnterpriseSecurityGroupArgs struct { + EniId string `json:"-"` + ClientToken string `json:"-"` + EnterpriseSecurityGroupIds []string `json:"enterpriseSecurityGroupIds"` +} + +type EniQuoteArgs struct { + EniId string `json:"-"` + InstanceId string `json:"-"` +} + +type EniQuoteInfo struct { + TotalQuantity int `json:"totalQuantity"` + AvailableQuantity int `json:"availableQuantity"` +} + +type EniStatusInfo struct { + Status string `json:"status"` +} diff --git a/bce-sdk-go/services/esg/client.go b/bce-sdk-go/services/esg/client.go new file mode 100644 index 0000000..3ff48f3 --- /dev/null +++ b/bce-sdk-go/services/esg/client.go @@ -0,0 +1,55 @@ +/* + * Copyright Baidu, Inc. + * + * 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 esg + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENI = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_ENI_URL = "/enterprise/security" +) + +// Client of ESG service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENI + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForEsg() string { + return URI_PREFIX + REQUEST_ENI_URL +} + +func getURLForEsgId(esgId string) string { + return getURLForEsg() + "/" + esgId +} + +func getURLForEsgRuleId(esgRuleId string) string { + return getURLForEsg() + "/rule/" + esgRuleId +} diff --git a/bce-sdk-go/services/esg/client_test.go b/bce-sdk-go/services/esg/client_test.go new file mode 100644 index 0000000..dadb92b --- /dev/null +++ b/bce-sdk-go/services/esg/client_test.go @@ -0,0 +1,191 @@ +/* + * Copyright Baidu, Inc. + * + * 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 esg + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + ESG_CLIENT *Client + + region string +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + ESG_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + + region = confObj.Endpoint[4:6] +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateEsg(t *testing.T) { + args := &CreateEsgArgs{ + Name: "esgGoSdkTest", + Rules: []EnterpriseSecurityGroupRule{ + { + Action: "deny", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "udp", + Remark: "go sdk test", + SourceIp: "all", + }, + { + Action: "allow", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "icmp", + Remark: "go sdk test", + SourceIp: "all", + }, + }, + Desc: "go sdk test", + ClientToken: getClientToken(), + Tags: []model.TagModel{ + { + TagKey: "test", + TagValue: "", + }, + }, + } + result, err := ESG_CLIENT.CreateEsg(args) + ExpectEqual(t.Errorf, nil, err) + EnterpriseSecurityGroupId := result.EnterpriseSecurityGroupId + log.Debug(EnterpriseSecurityGroupId) +} + +func TestClient_ListEsgs(t *testing.T) { + args := &ListEsgArgs{} + res, err := ESG_CLIENT.ListEsg(args) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) +} + +func TestClient_DeleteEsg(t *testing.T) { + args := &DeleteEsgArgs{ + EnterpriseSecurityGroupId: "esg-s91awqpw73un", + ClientToken: getClientToken(), + } + err := ESG_CLIENT.DeleteEsg(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateEsgRules(t *testing.T) { + args := &CreateEsgRuleArgs{ + Rules: []EnterpriseSecurityGroupRule{ + { + Action: "deny", + Direction: "ingress", + Ethertype: "IPv4", + PortRange: "1-65535", + Priority: 1000, + Protocol: "udp", + Remark: "go sdk test", + SourceIp: "all", + }, + }, + EnterpriseSecurityGroupId: "esg-v99qnxx7uh83", + ClientToken: getClientToken(), + } + err := ESG_CLIENT.CreateEsgRules(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteEsgRule(t *testing.T) { + args := &DeleteEsgRuleArgs{ + EnterpriseSecurityGroupRuleId: "esgr-ak7b51zzgptc", + } + err := ESG_CLIENT.DeleteEsgRule(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateEsgRule(t *testing.T) { + args := &UpdateEsgRuleArgs{ + Priority: 900, + Remark: "go sdk test update", + ClientToken: getClientToken(), + EnterpriseSecurityGroupRuleId: "esgr-ahm3xxi11s20", + } + err := ESG_CLIENT.UpdateEsgRule(args) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/esg/config.json b/bce-sdk-go/services/esg/config.json new file mode 100644 index 0000000..5a6634f --- /dev/null +++ b/bce-sdk-go/services/esg/config.json @@ -0,0 +1,5 @@ +{ + "AK":"", + "SK":"", + "Endpoint":"" +} diff --git a/bce-sdk-go/services/esg/esg.go b/bce-sdk-go/services/esg/esg.go new file mode 100644 index 0000000..0563a5e --- /dev/null +++ b/bce-sdk-go/services/esg/esg.go @@ -0,0 +1,154 @@ +/* + * Copyright Baidu, Inc. + * + * 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 esg + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateEsg - create an esg with the specific parameters +// +// PARAMS: +// - args: the arguments to create an esg +// +// RETURNS: +// - *CreateEsgResult: the result of create esg +// - error: nil if success otherwise the specific error +func (c *Client) CreateEsg(args *CreateEsgArgs) (*CreateEsgResult, error) { + if args == nil { + return nil, fmt.Errorf("The createEsgArgs cannot be nil.") + } + + result := &CreateEsgResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEsg()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListEsg - list all esg with the specific parameters +// +// PARAMS: +// - args: the arguments to list all esg +// +// RETURNS: +// - *ListEsgResult: the result of list all esg +// - error: nil if success otherwise the specific error +func (c *Client) ListEsg(args *ListEsgArgs) (*ListEsgResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListEsgArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListEsgResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForEsg()). + WithMethod(http.GET). + WithQueryParamFilter("instanceId", args.InstanceId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)) + + err := builder.WithResult(result).Do() + + return result, err +} + +// DeleteEsg - delete an esg +// +// PARAMS: +// - DeleteEsgArgs: the arguments to delete an esg +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEsg(args *DeleteEsgArgs) error { + if args == nil { + return fmt.Errorf("The deleteEsgArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEsgId(args.EnterpriseSecurityGroupId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// CreateEsgRules - create esg rules +// +// PARAMS: +// - CreateEsgRuleArgs: the arguments to create esg rules +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateEsgRules(args *CreateEsgRuleArgs) error { + if args == nil { + return fmt.Errorf("The createEsgRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEsgId(args.EnterpriseSecurityGroupId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("authorizeRule", ""). + Do() +} + +// DeleteEsgRule - delete an esg rule +// +// PARAMS: +// - DeleteEsgArgs: the arguments to delete an esg rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEsgRule(args *DeleteEsgRuleArgs) error { + if args == nil { + return fmt.Errorf("The deleteEsgRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEsgRuleId(args.EnterpriseSecurityGroupRuleId)). + WithMethod(http.DELETE). + Do() +} + +// UpdateEsgRule - update esg rule +// +// PARAMS: +// - CreateEsgRuleArgs: the arguments to update esg rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEsgRule(args *UpdateEsgRuleArgs) error { + if args == nil { + return fmt.Errorf("The updateEsgRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForEsgRuleId(args.EnterpriseSecurityGroupRuleId)). + WithMethod(http.PUT). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/esg/model.go b/bce-sdk-go/services/esg/model.go new file mode 100644 index 0000000..f792856 --- /dev/null +++ b/bce-sdk-go/services/esg/model.go @@ -0,0 +1,94 @@ +/* + * Copyright Baidu, Inc. + * + * 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 esg + +import "github.com/baidubce/bce-sdk-go/model" + +type CreateEsgArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Desc string `json:"desc"` + Rules []EnterpriseSecurityGroupRule `json:"rules"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +type CreateEsgResult struct { + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId"` +} + +type EnterpriseSecurityGroup struct { + Id string `json:"id"` + Name string `json:"name"` + Desc string `json:"desc"` + Rules []EnterpriseSecurityGroupRule `json:"rules"` + Tags []model.TagModel `json:"tags"` + CreatedTime string `json:"createdTime"` +} + +type EnterpriseSecurityGroupRule struct { + EnterpriseSecurityGroupRuleId string `json:"enterpriseSecurityGroupRuleId"` + Remark string `json:"remark"` + Direction string `json:"direction"` + Ethertype string `json:"ethertype"` + PortRange string `json:"portRange"` + Protocol string `json:"protocol"` + SourceIp string `json:"sourceIp"` + DestIp string `json:"destIp"` + Action string `json:"action"` + Priority int `json:"priority"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` +} + +type ListEsgArgs struct { + InstanceId string + Marker string + MaxKeys int +} + +type ListEsgResult struct { + EnterpriseSecurityGroups []EnterpriseSecurityGroup `json:"enterpriseSecurityGroups"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type DeleteEsgArgs struct { + EnterpriseSecurityGroupId string + ClientToken string +} + +type CreateEsgRuleArgs struct { + ClientToken string `json:"-"` + EnterpriseSecurityGroupId string `json:"enterpriseSecurityGroupId"` + Rules []EnterpriseSecurityGroupRule `json:"rules"` +} + +type DeleteEsgRuleArgs struct { + EnterpriseSecurityGroupRuleId string +} + +type UpdateEsgRuleArgs struct { + ClientToken string + EnterpriseSecurityGroupRuleId string `json:"-"` + Remark string `json:"remark"` + PortRange string `json:"portRange"` + Protocol string `json:"protocol"` + SourceIp string `json:"sourceIp"` + DestIp string `json:"destIp"` + Action string `json:"action"` + Priority int `json:"priority"` +} diff --git a/bce-sdk-go/services/et/client.go b/bce-sdk-go/services/et/client.go new file mode 100644 index 0000000..c9bb0ed --- /dev/null +++ b/bce-sdk-go/services/et/client.go @@ -0,0 +1,78 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for ET service + +// Package et defines the et services of BCE. +// The supported APIs are all defined in different files. +package et + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_ET_URL = "/et" + REQUEST_ET_CHANNEL_URL = "/channel" + REQUEST_ET_CHANNEL_ROUTE_URL = "/route" + REQUEST_ET_CHANNEL_ROUTE_RULE_URL = "/rule" +) + +// Client of ET service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForEt() string { + return URI_PREFIX + REQUEST_ET_URL +} + +func getURLForEtId(etId string) string { + return getURLForEt() + "/" + etId +} + +func getURLForEtChannel(etId string) string { + return getURLForEtId(etId) + REQUEST_ET_CHANNEL_URL +} + +func getURLForEtChannelId(etId string, etChannelId string) string { + return getURLForEtChannel(etId) + "/" + etChannelId +} + +func getURLForEtChannelRoute(etId string, etChannelId string) string { + return getURLForEtChannelId(etId, etChannelId) + REQUEST_ET_CHANNEL_ROUTE_URL +} + +func getURLForEtChannelRouteRule(etId string, etChannelId string) string { + return getURLForEtChannelRoute(etId, etChannelId) + REQUEST_ET_CHANNEL_ROUTE_RULE_URL +} + +func getURLForEtChannelRouteRuleId(etId string, etChannelId string, routeRuleId string) string { + return getURLForEtChannelRouteRule(etId, etChannelId) + "/" + routeRuleId +} diff --git a/bce-sdk-go/services/et/client_test.go b/bce-sdk-go/services/et/client_test.go new file mode 100644 index 0000000..0c689dc --- /dev/null +++ b/bce-sdk-go/services/et/client_test.go @@ -0,0 +1,298 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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 et + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + EtClient *Client +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + f = filepath.Dir(f) + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + EtClient, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) +} + +// TestClient_GetEtChannel tests GetEtChannel method of EtClient +func TestClient_GetEtChannel(t *testing.T) { + args := &GetEtChannelArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-xxxxxxxxxxxx", + } + result, err := EtClient.GetEtChannel(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + log.Debug(string(r)) +} + +// TestClient_RecommitEtChannel 测试客户端的RecommitEtChannel方法 +func TestClient_RecommitEtChannel(t *testing.T) { + args := &RecommitEtChannelArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-xxxxxxxxxxxx", + EtChannelId: "dedicatedconn-xxxxxxxxxxxx", + Result: RecommitEtChannelResult{ // recommit et channel result + AuthorizedUsers: []string{"xxxxxxxxxxxxxxxxxx"}, // authorized users + Description: "test Description", // description + BaiduAddress: "Your BaiduAddress", // baidu address + Name: "test Name", // name + Networks: []string{"Your Networks"}, // networks + CustomerAddress: "Your CustomerAddress", // customer address + RouteType: "Your RouteType", // route type + VlanId: "1", // vlan id + Status: "Your Status", // status + EnableIpv6: 0, // enable ipv6 + BaiduIpv6Address: "Your BaiduIpv6Address", // baidu ipv6 address + Ipv6Networks: []string{"Your Ipv6Networks"}, // ipv6 networks + CustomerIpv6Address: "Your CustomerIpv6Address", // customer ipv6 address + }, + } + err := EtClient.RecommitEtChannel(args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_UpdateEtChannel 测试客户端的更新ET通道函数 +func TestClient_UpdateEtChannel(t *testing.T) { + args := &UpdateEtChannelArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-xxxxxxxxxxxx", + EtChannelId: "dedicatedconn-xxxxxxxxxxxx", + Result: UpdateEtChannelResult{ // update et channel result + Name: "testname", // name + Description: "testdecription", // description + }, + } + err := EtClient.UpdateEtChannel(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteEtChannel(t *testing.T) { + args := &DeleteEtChannelArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-xxxxxxxxxxxx", + EtChannelId: "dedicatedconn-xxxxxxxxxxxx", + } + err := EtClient.DeleteEtChannel(args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_EnableEtChannelIPv6 测试函数 +func TestClient_EnableEtChannelIPv6(t *testing.T) { + args := &EnableEtChannelIPv6Args{ + ClientToken: getClientToken(), + EtId: "dcphy-xxxxxxxxxxxx", + EtChannelId: "dedicatedconn-xxxxxxxxxxxx", + Result: EnableEtChannelIPv6Result{ // enable et channel ipv6 result + BaiduIpv6Address: "2001:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:0001", // baidu ipv6 address + Ipv6Networks: []string{"2001:xxxx:xxxx:xxxx::/64"}, // ipv6 networks + CustomerIpv6Address: "2001:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:0002", // customer ipv6 address + }, + } + err := EtClient.EnableEtChannelIPv6(args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_DisableEtChannelIPv6 测试函数 +func TestClient_DisableEtChannelIPv6(t *testing.T) { + args := &DisableEtChannelIPv6Args{ + ClientToken: getClientToken(), + EtId: "dcphy-tm25m1reihvw", + EtChannelId: "dedicatedconn-ybffmxnpygcx", + } + err := EtClient.DisableEtChannelIPv6(args) + ExpectEqual(t.Errorf, nil, err) +} + +// getClientToken 函数返回一个长度为32的字符串作为客户端令牌。 +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateEtDcphy(t *testing.T) { + args := &CreateEtDcphyArgs{ + ClientToken: getClientToken(), + Name: "test_InitEt", + Isp: "ISP_CMCC", + IntfType: "1G", + ApType: "SINGLE", + ApAddr: "BJYZ", + UserName: "test", + UserPhone: "18266666666", + UserEmail: "18266666666@baidu.com", + UserIdc: "北京|市辖区|东城区|百度科技园K2", + } + + r, err := EtClient.CreateEtDcphy(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(r.Id) != 0) +} + +func TestClient_UpdateEtDcphy(t *testing.T) { + args := &UpdateEtDcphyArgs{ + Name: "test_Update", + Description: "new", + UserName: "testUpdate", + UserPhone: "18266666667", + UserEmail: "18266666667@baidu.com", + } + + err := EtClient.UpdateEtDcphy("dcphy-23451", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListEtDcphy(t *testing.T) { + args := &ListEtDcphyArgs{ + Marker: "your marker", + MaxKeys: 10000, + Status: "established", + } + + r, err := EtClient.ListEtDcphy(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(r.Ets) != 0) +} + +func TestClient_ListEtDcphyDetail(t *testing.T) { + r, err := EtClient.ListEtDcphyDetail("dcphy-23451") + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(r.Name) != 0) +} + +func TestClient_CreateEtChannel(t *testing.T) { + args := &CreateEtChannelArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-234r5", + Description: "test", + BaiduAddress: "172.1.1.1/24", + Name: "testChannel", + Networks: []string{"192.168.0.0/16"}, + CustomerAddress: "172.1.1.2/24", + RouteType: "static-route", + VlanId: 100, + EnableIpv6: 1, + BaiduIpv6Address: "2400:da00:e003:0:1eb:200::1/88", + CustomerIpv6Address: "2400:da00:e003:0:0:200::1/88", + Ipv6Networks: []string{"2400:da00:e003:0:15f::/87"}, + } + + r, err := EtClient.CreateEtChannel(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, true, len(r.Id) != 0) +} + +func TestCreateEtGatewayRouteRule(t *testing.T) { + req := &CreateEtChannelRouteRuleArgs{ + EtId: "dcphy-tm25m1reihvw", + EtChannelId: "dedicatedconn-ybffmxnpygcx", + ClientToken: getClientToken(), + DestAddress: "11.11.12.14/32", + NextHopType: "etChannel", + NextHopId: "dedicatedconn-ybffmxnpygcx", + } + response, err := EtClient.CreateEtChannelRouteRule(req) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(response) + fmt.Println(string(r)) +} + +func TestListEtChannelRouteRule(t *testing.T) { + req := &ListEtChannelRouteRuleArgs{ + EtId: "dcphy-tm25m1reihvw", + EtChannelId: "dedicatedconn-ybffmxnpygcx", + } + response, err := EtClient.ListEtChannelRouteRule(req) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(response) + fmt.Println(string(r)) +} + +func TestUpdateEtChannelRouteRule(t *testing.T) { + req := &UpdateEtChannelRouteRuleArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-tm25m1reihvw", // 专线ID + EtChannelId: "dedicatedconn-ybffmxnpygcx", + RouteRuleId: "dcrr-07a5967b-84a", + Description: "test", + } + err := EtClient.UpdateEtChannelRouteRule(req) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeleteEtChannelRouteRule(t *testing.T) { + req := &DeleteEtChannelRouteRuleArgs{ + ClientToken: getClientToken(), + EtId: "dcphy-tm25m1reihvw", + EtChannelId: "dedicatedconn-ybffmxnpygcx", + RouteRuleId: "dcrr-6378ed8b-a2d", + } + err := EtClient.DeleteEtChannelRouteRule(req) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/et/et.go b/bce-sdk-go/services/et/et.go new file mode 100644 index 0000000..2738889 --- /dev/null +++ b/bce-sdk-go/services/et/et.go @@ -0,0 +1,372 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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. + */ + +// et.go - the et APIs definition supported by the et service + +package et + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// GetEtChannel - get an et channel +// +// PARAMS: +// - args: the arguments to get et channel +// +// RETURNS: +// - *GetEtChannelResult: the info of the et channel +// - error: nil if success otherwise the specific error +func (c *Client) GetEtChannel(args *GetEtChannelArgs) (*GetEtChannelsResult, error) { + if args == nil { + return nil, fmt.Errorf("The GetEtChannelArgs cannot be nil.") + } + + result := &GetEtChannelsResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannel(args.EtId)). + WithMethod(http.GET). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// RecommitEtChannel - recommit et channel +// +// PARAMS: +// - args: the arguments to recommit et channel +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecommitEtChannel(args *RecommitEtChannelArgs) error { + if args == nil { + return fmt.Errorf("The RecommitEtChannelArgs cannot be nil.") + } + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelId(args.EtId, args.EtChannelId)). + WithMethod(http.PUT). + WithBody(args.Result). + WithQueryParam("reCreate", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + return err +} + +// UpdateEtChannel - update et channel +// +// PARAMS: +// - args: the arguments to update et channel +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEtChannel(args *UpdateEtChannelArgs) error { + if args == nil { + return fmt.Errorf("The UpdateEtChannelArgs cannot be nil.") + } + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelId(args.EtId, args.EtChannelId)). + WithMethod(http.PUT). + WithBody(args.Result). + WithQueryParam("modifyAttribute", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + return err +} + +// DeleteEtChannel - delete et channel +// +// PARAMS: +// - args: the arguments to delete et channel +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEtChannel(args *DeleteEtChannelArgs) error { + if args == nil { + return fmt.Errorf("The DeleteEtChannelArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelId(args.EtId, args.EtChannelId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + return err +} + +// EnableEtChannelIPv6 - enable et channel ipv6 +// +// PARAMS: +// - args: the arguments to enable et channel ipv6 +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EnableEtChannelIPv6(args *EnableEtChannelIPv6Args) error { + if args == nil { + return fmt.Errorf("The EnableEtChannelIPv6Args cannot be nil.") + } + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelId(args.EtId, args.EtChannelId)). + WithMethod(http.PUT). + WithBody(args.Result). + WithQueryParam("enableIpv6", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + return err +} + +// DisableEtChannelIPv6 - disable EtChannelIPv6 with the specified parameters +// +// PARAMS: +// - args: the arguments to disable EtChannelIPv6 +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DisableEtChannelIPv6(args *DisableEtChannelIPv6Args) error { + if args == nil { + return fmt.Errorf("the createEtChannelRouteRuleArgs cannot be nil") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelId(args.EtId, args.EtChannelId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParam("disableIpv6", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// CreateEtDcphy - init a new Et +// +// PARAMS: +// - args: the arguments to init et dcphy +// +// RETURNS: +// - CreateEtDcphyResult: the id of et dcphy newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateEtDcphy(args *CreateEtDcphyArgs) (*CreateEtDcphyResult, error) { + if args == nil { + return nil, fmt.Errorf("The CreateEtDcphyArgs can not be nil") + } + + result := &CreateEtDcphyResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEt()+"/init"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// UpdateEtDcphy - update an existed Et +// +// PARAMS: +// - edId: the id of et dcphy +// - args: the arguments to update et dcphy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEtDcphy(dcphyId string, args *UpdateEtDcphyArgs) error { + if len(dcphyId) == 0 { + return fmt.Errorf("please set et dcphy id") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtId(dcphyId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// ListEtDcphy - List ets +// +// PARAMS: +// - args: the arguments to list et +// +// RETURNS: +// - ListEtDcphyResult: list result +// - error: nil if success otherwise the specific error +func (c *Client) ListEtDcphy(args *ListEtDcphyArgs) (*ListEtDcphyResult, error) { + if args == nil { + args = &ListEtDcphyArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListEtDcphyResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getURLForEt()). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParamFilter("status", args.Status). + WithResult(result). + Do() + + return result, err +} + +// ListEtDcphyDetail - List specific et detail +// +// PARAMS: +// - dcphyId: the id of etDcphy +// +// RETURNS: +// - EtDcphyDetail: etDcphy detail +// - error: nil if success otherwise the specific error +func (c *Client) ListEtDcphyDetail(dcphyId string) (*EtDcphyDetail, error) { + if len(dcphyId) == 0 { + return nil, fmt.Errorf("please set et dcphy id") + } + + result := &EtDcphyDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getURLForEtId(dcphyId)). + WithResult(result). + Do() + + return result, err +} + +// CreateEtChannel - create an Et channel with the specific parameters +// +// PARAMS: +// - args: the arguments to create an eip +// +// RETURNS: +// - CreateEipResult: the result of create EIP, contains new EIP's address +// - error: nil if success otherwise the specific error +func (c *Client) CreateEtChannel(args *CreateEtChannelArgs) (*CreateEtChannelResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create etChannel argments") + } + + if len(args.EtId) == 0 { + return nil, fmt.Errorf("please set et id") + } + + result := &CreateEtChannelResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getURLForEtChannel(args.EtId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateEtChannelRouteRule - create a new EtChannelRouteRule with the specified parameters +// +// PARAMS: +// - args: the arguments to create EtChannelRouteRule +// +// RETURNS: +// - *CreateEtChannelRouteRuleResult: the id of the EtChannelRouteRule newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateEtChannelRouteRule(args *CreateEtChannelRouteRuleArgs) (*CreateEtChannelRouteRuleResult, error) { + if args == nil { + return nil, fmt.Errorf("the createEtChannelRouteRuleArgs cannot be nil") + } + result := &CreateEtChannelRouteRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelRouteRule(args.EtId, args.EtChannelId)). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + return result, err +} + +// ListEtChannelRouteRule - list all EtChannelRouteRules with the specified parameters +// +// PARAMS: +// - args: the arguments to list EtChannelRouteRules +// +// RETURNS: +// - *EtChannelRouteRuleResult: the result of all EtChannelRouteRules +// - error: nil if success otherwise the specific error +func (c *Client) ListEtChannelRouteRule(args *ListEtChannelRouteRuleArgs) (*ListEtChannelRouteRuleResult, error) { + if args == nil { + return nil, fmt.Errorf("the listEtChannelRouteRuleArgs cannot be nil") + } + if args.MaxKeys < 0 || args.MaxKeys > 1000 { + return nil, fmt.Errorf("the field maxKeys is out of range [0, 1000]") + } + result := &ListEtChannelRouteRuleResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelRouteRule(args.EtId, args.EtChannelId)). + WithMethod(http.GET). + WithResult(result). + WithQueryParamFilter("marker", args.Marker) + if args.MaxKeys != 0 { + builder.WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)) + } + err := builder.Do() + return result, err +} + +// UpdateEtChannelRouteRule - update a specified EtChannelRouteRule +// +// PARAMS: +// - args: the arguments to update EtChannelRouteRule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEtChannelRouteRule(args *UpdateEtChannelRouteRuleArgs) error { + if args == nil { + return fmt.Errorf("the updateEtChannelRouteRuleArgs cannot be nil") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelRouteRuleId(args.EtId, args.EtChannelId, args.RouteRuleId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// DeleteEtChannelRouteRule - delete a specified EtChannelRouteRule +// +// PARAMS: +// - params: the arguments to delete EtChannelRouteRule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEtChannelRouteRule(args *DeleteEtChannelRouteRuleArgs) error { + if args == nil { + return fmt.Errorf("the deleteEtChannelRouteRuleArgs cannot be nil") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForEtChannelRouteRuleId(args.EtId, args.EtChannelId, args.RouteRuleId)). + WithMethod(http.DELETE). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + +} diff --git a/bce-sdk-go/services/et/model.go b/bce-sdk-go/services/et/model.go new file mode 100644 index 0000000..3355a37 --- /dev/null +++ b/bce-sdk-go/services/et/model.go @@ -0,0 +1,262 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package et + +type GetEtChannelArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` +} + +type RecommitEtChannelArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + Result RecommitEtChannelResult `json:"etChannelResult"` +} + +type UpdateEtChannelArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + Result UpdateEtChannelResult `json:"UpdateEtChannelResult"` +} + +type DeleteEtChannelArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` +} + +type EnableEtChannelIPv6Args struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + Result EnableEtChannelIPv6Result `json:"enableEtChannelIpv6Result"` +} + +type GetEtChannelsResult struct { + EtChannels []EtChannelResult `json:"etChannels"` +} + +type RecommitEtChannelResult struct { + AuthorizedUsers []string `json:"authorizedUsers"` + Description string `json:"description"` + BaiduAddress string `json:"baiduAddress"` + Name string `json:"name"` + Networks []string `json:"networks"` + CustomerAddress string `json:"customerAddress"` + RouteType string `json:"routeType"` + VlanId string `json:"vlanId"` + Id string `json:"id"` + Status string `json:"status"` + EnableIpv6 uint32 `json:"enableIpv6"` + BaiduIpv6Address string `json:"baiduIpv6Address"` + Ipv6Networks []string `json:"ipv6Networks"` + CustomerIpv6Address string `json:"CustomerIpv6Address"` +} + +type UpdateEtChannelResult struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type EnableEtChannelIPv6Result struct { + BaiduIpv6Address string `json:"baiduIpv6Address"` + CustomerIpv6Address string `json:"CustomerIpv6Address"` + Ipv6Networks []string `json:"ipv6Networks"` +} + +type EtChannelResult struct { + AuthorizedUsers []string `json:"authorizedUsers"` + Description string `json:"description"` + BaiduAddress string `json:"baiduAddress"` + Name string `json:"name"` + Networks []string `json:"networks"` + BGPAsn string `json:"bgpAsn"` + BGPKey string `json:"bgpKey"` + CustomerAddress string `json:"customerAddress"` + RouteType string `json:"routeType"` + VlanId string `json:"vlanId"` + Id string `json:"id"` + Status string `json:"status"` + EnableIpv6 uint32 `json:"enableIpv6"` + BaiduIpv6Address string `json:"baiduIpv6Address"` + Ipv6Networks []string `json:"ipv6Networks"` + CustomerIpv6Address string `json:"CustomerIpv6Address"` +} + +type CreateEtDcphyArgs struct { + ClientToken string `json:"clientToken,omitempty"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Isp string `json:"isp"` + IntfType string `json:"intfType"` + ApType string `json:"apType"` + ApAddr string `json:"apAddr"` + UserName string `json:"userName"` + UserPhone string `json:"userPhone"` + UserEmail string `json:"userEmail"` + UserIdc string `json:"userIdc"` +} + +type CreateEtDcphyResult struct { + Id string `json:"id"` +} + +type UpdateEtDcphyArgs struct { + ClientToken string `json:"clientToken,omitempty"` + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` + UserName string `json:"userName,omitempty"` + UserPhone string `json:"userPhone,omitempty"` + UserEmail string `json:"userEmail,omitempty"` +} + +type ListEtDcphyArgs struct { + Marker string + MaxKeys int + Status string +} + +type ListEtDcphyResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Ets []Et `json:"ets"` +} + +type Et struct { + Id string `json:"Id"` + Name string `json:"name"` + Description string `json:"description"` + Status string `json:"status"` + ExpireTime string `json:"expireTime"` + Isp string `json:"isp"` + IntfType string `json:"intfType"` + ApType string `json:"apType"` + ApAddr string `json:"apAddr"` + UserName string `json:"userName"` + UserPhone string `json:"userPhone"` + UserEmail string `json:"userEmail"` + UserIdc string `json:"userIdc"` +} + +type EtDcphyDetail struct { + Id string `json:"clientToken,omitempty"` + Name string `json:"name"` + Description string `json:"description"` + Status string `json:"status"` + ExpireTime string `json:"expireTime"` + Isp string `json:"isp"` + IntfType string `json:"intfType"` + ApType string `json:"apType"` + ApAddr string `json:"apAddr"` + UserName string `json:"userName"` + UserPhone string `json:"userPhone"` + UserEmail string `json:"userEmail"` + UserIdc string `json:"userIdc"` +} + +type CreateEtChannelArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + AuthorizedUsers []string `json:"authorizedUsers,omitempty"` + Description string `json:"description,omitempty"` + BaiduAddress string `json:"baiduAddress"` + Name string `json:"name"` + Networks []string `json:"networks,omitempty"` + CustomerAddress string `json:"customerAddress"` + RouteType string `json:"routeType"` + VlanId int `json:"vlanId"` + BgpAsn string `json:"bgpAsn,omitempty"` + BgpKey string `json:"bgpKey,omitempty"` + EnableIpv6 int `json:"enableIpv6,omitempty"` + BaiduIpv6Address string `json:"baiduIpv6Address,omitempty"` + CustomerIpv6Address string `json:"customerIpv6Address,omitempty"` + Ipv6Networks []string `json:"ipv6Networks,omitempty"` +} + +type CreateEtChannelResult struct { + Id string `json:"id"` +} + +type DisableEtChannelIPv6Args struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` +} + +type CreateEtChannelRouteRuleArgs struct { + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + ClientToken string `json:"clientToken,omitempty"` + IpVersion int `json:"ipVersion,omitempty"` + DestAddress string `json:"destAddress"` + NextHopType string `json:"nexthopType"` + NextHopId string `json:"nexthopId"` + Description string `json:"description,omitempty"` +} + +type CreateEtChannelRouteRuleResult struct { + RouteRuleId string `json:"routeRuleId"` +} + +type ListEtChannelRouteRuleArgs struct { + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` + DestAddress string `json:"destAddress,omitempty"` +} + +type ListEtChannelRouteRuleResult struct { + Marker string `json:"marker"` + IsTrucated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RouteRules []EtChannelRouteRule `json:"routeRules"` +} + +type EtChannelRouteRule struct { + RouteRuleId string `json:"routeRuleId"` + IpVersion int `json:"ipVersion"` + DestAddress string `json:"destAddress"` + NextHopType string `json:"nexthopType"` + NextHopId string `json:"nexthopId"` + Description string `json:"description"` + RouteProto string `json:"routeProto"` + AsPaths string `json:"asPaths"` + LocalPreference int `json:"localPreference"` + Med int `json:"med"` + Origin string `json:"origin"` +} + +type UpdateEtChannelRouteRuleArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + RouteRuleId string `json:"routeRuleId"` + Description string `json:"description"` +} + +type DeleteEtChannelRouteRuleArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtId string `json:"etId"` + EtChannelId string `json:"etChannelId"` + RouteRuleId string `json:"routeRuleId"` +} diff --git a/bce-sdk-go/services/etGateway/client.go b/bce-sdk-go/services/etGateway/client.go new file mode 100644 index 0000000..ed5247e --- /dev/null +++ b/bce-sdk-go/services/etGateway/client.go @@ -0,0 +1,55 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for EtGateway service + +// Package vpn defines the vpn services of BCE. +// The supported APIs are all defined in different files. +package etGateway + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_VPN_URL = "/etGateway" +) + +// Client of EtGateway service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForEtGateway() string { + return URI_PREFIX + REQUEST_VPN_URL +} + +func getURLForEtGatewayId(etGatewayId string) string { + return getURLForEtGateway() + "/" + etGatewayId +} diff --git a/bce-sdk-go/services/etGateway/client_test.go b/bce-sdk-go/services/etGateway/client_test.go new file mode 100644 index 0000000..48ea948 --- /dev/null +++ b/bce-sdk-go/services/etGateway/client_test.go @@ -0,0 +1,163 @@ +package etGateway + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + EtGateway_CLIENT *Client + region string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + VPCEndpoint string `json:"VPC"` + EIPEndpoint string `json:"EIP"` +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + EtGateway_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.VPCEndpoint) + + region = confObj.VPCEndpoint[4:6] + +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateEtGateway(t *testing.T) { + args := &CreateEtGatewayArgs{ + Name: "TestSDK-VPN", + Description: "vpn test", + VpcId: "vpc-2pa2x0bjt26i", + Speed: 100, + ClientToken: getClientToken(), + } + result, err := EtGateway_CLIENT.CreateEtGateway(args) + ExpectEqual(t.Errorf, nil, err) + EtGatewayId := result.EtGatewayId + log.Debug(EtGatewayId) +} + +func TestClient_ListEtGateway(t *testing.T) { + args := &ListEtGatewayArgs{ + VpcId: "vpc-xsd65rcsp5ue", + } + result := &ListEtGatewayResult{} + result, err := EtGateway_CLIENT.ListEtGateway(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_GetEtGatewayDetail(t *testing.T) { + res := &EtGatewayDetail{} + res, err := EtGateway_CLIENT.GetEtGatewayDetail("dcgw-vs1rvp9qy79f") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) +} + +func TestClient_UpdateEtGateway(t *testing.T) { + args := &UpdateEtGatewayArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-mx3annmentbu", + Name: "aaa", + Description: "test", + } + err := EtGateway_CLIENT.UpdateEtGateway(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteEtGateway(t *testing.T) { + err := EtGateway_CLIENT.DeleteEtGateway("dcgw-iiyc0ers2qx4", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_BindEt(t *testing.T) { + args := &BindEtArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-iiyc0ers2qx4", + EtId: "et-aaccd", + ChannelId: "sdxs", + LocalCidrs: []string{"192.168.0.1"}, + } + err := EtGateway_CLIENT.BindEt(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnBindEt(t *testing.T) { + err := EtGateway_CLIENT.UnBindEt("dcgw-iiyc0ers2qx4", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateHealthCheck(t *testing.T) { + auto := true + args := &CreateHealthCheckArgs{ + ClientToken: getClientToken(), + EtGatewayId: "dcgw-iiyc0ers2qx4", + HealthCheckSourceIp: "1.2.3.4", + HealthCheckType: HEALTH_CHECK_ICMP, + HealthCheckPort: 80, + HealthCheckInterval: 60, + HealthThreshold: 3, + UnhealthThreshold: 4, + AutoGenerateRouteRule: &auto, + } + err := EtGateway_CLIENT.CreateHealthCheck(args) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/etGateway/etGateway.go b/bce-sdk-go/services/etGateway/etGateway.go new file mode 100644 index 0000000..e2dc7aa --- /dev/null +++ b/bce-sdk-go/services/etGateway/etGateway.go @@ -0,0 +1,155 @@ +package etGateway + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +// CreateEtGateway - create a new Et gateway +// +// PARAMS: +// - args: the arguments to create Et gateway +// RETURNS: +// - *CreateVpnGatewayResult: the id of the et gateway newly created +// - error: nil if success otherwise the specific error + +func (c *Client) CreateEtGateway(args *CreateEtGatewayArgs) (*CreateEtGatewayResult, error) { + if args == nil { + return nil, fmt.Errorf("The CreateEtGatewayArgs cannot be nil.") + } + + result := &CreateEtGatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtGateway()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListEtGateway - list all Et gateways with the specific parameters +// PARAMS: +// - args: the arguments to list et gateways +// +// RETURNS: +// - *ListEtGatewayResult: the result of Et gateway list +// - error: nil if success otherwise the specific error +func (c *Client) ListEtGateway(args *ListEtGatewayArgs) (*ListEtGatewayResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListEtGatewayArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + result := &ListEtGatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtGateway()). + WithMethod(http.GET). + WithQueryParam("vpcId", args.VpcId). + WithQueryParamFilter("etGatewayId", args.EtGatewayId). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("status", args.Status). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + return result, err +} + +// GetEtGatewayDetail - Get the Et gateways with the specific parameters +// PARAMS: +// - etGatewayId: the id of the EtGateway's +// +// RETURNS: +// - *EtGatewayDetail: the result of EtGgateway detail +// - error: nil if success otherwise the specific error +func (c *Client) GetEtGatewayDetail(etGatewayId string) (*EtGatewayDetail, error) { + result := &EtGatewayDetail{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForEtGatewayId(etGatewayId)). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} + +// UpdateEtGateway - update the Et gateways with the specific parameters +// PARAMS: +// - args: the arguments to update the EtGateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateEtGateway(updateEtGatewayArgs *UpdateEtGatewayArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEtGatewayId(updateEtGatewayArgs.EtGatewayId)). + WithQueryParamFilter("clientToken", updateEtGatewayArgs.ClientToken). + WithMethod(http.PUT). + WithBody(updateEtGatewayArgs). + Do() +} + +// DeleteEtGateway - delete the Et gateways with the specific parameters +// PARAMS: +// - etGatewayId: the id to delete the EtGateway +// - clientToken: the idempotent string +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteEtGateway(etGatewayId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEtGatewayId(etGatewayId)). + WithQueryParam("clientToken", clientToken). + WithMethod(http.DELETE). + Do() +} + +// UnBindEt - bind the Et +// PARAMS: +// - args: the arguments to bind the Et +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindEt(args *BindEtArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEtGatewayId(args.EtGatewayId)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("bind", ""). + WithBody(args). + WithMethod(http.PUT). + Do() +} + +// UnBindEt - unbind the Et +// PARAMS: +// - args: the arguments to unbind the Et +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindEt(EtGatewayId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEtGatewayId(EtGatewayId)). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParam("unbind", ""). + WithMethod(http.PUT). + Do() +} + +// CreateHealthCheck - create the Et gateway's healthcheck with the specific parameters +// PARAMS: +// - args: the arguments to create the EtGateway's healthcheck +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateHealthCheck(args *CreateHealthCheckArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForEtGatewayId(args.EtGatewayId)+"/healthCheck"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithMethod(http.POST). + Do() +} diff --git a/bce-sdk-go/services/etGateway/model.go b/bce-sdk-go/services/etGateway/model.go new file mode 100644 index 0000000..a014ada --- /dev/null +++ b/bce-sdk-go/services/etGateway/model.go @@ -0,0 +1,101 @@ +package etGateway + +type ( + HealthCheckType string +) + +const ( + HEALTH_CHECK_ICMP HealthCheckType = "ICMP" +) + +type CreateEtGatewayArgs struct { + Name string `json:"name"` + VpcId string `json:"vpcId"` + Speed int `json:"speed"` + Description string `json:"description"` + EtId string `json:"etId"` + ChannelId string `json:"channelId"` + LocalCidrs []string `json:"localCidrs"` + ClientToken string `json:"clientToken,omitempty"` +} + +type CreateEtGatewayResult struct { + EtGatewayId string `json:"etGatewayId"` +} + +type ListEtGatewayArgs struct { + VpcId string + EtGatewayId string + Name string + Status string + Marker string + MaxKeys int +} + +type ListEtGatewayResult struct { + EtGateways []EtGateway `json:"etGateways"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} +type EtGateway struct { + EtGatewayId string `json:"etGatewayId"` + Name string `json:"name"` + Status string `json:"status"` + Speed int `json:"speed"` + CreateTime string `json:"createTime"` + Description string `json:"description"` + VpcId string `json:"vpcId"` + EtId string `json:"etId"` + ChannelId string `json:"channelId"` + LocalCidrs []string `json:"localCidrs"` +} + +type EtGatewayDetail struct { + EtGatewayId string `json:"etGatewayId"` + Name string `json:"name"` + Status string `json:"status"` + Speed int `json:"speed"` + CreateTime string `json:"createTime"` + Description string `json:"description"` + VpcId string `json:"vpcId"` + EtId string `json:"etId"` + ChannelId string `json:"channelId"` + LocalCidrs []string `json:"localCidrs"` + HealthCheckSourceIp string `json:"healthCheckSourceIp"` + HealthCheckDestIp string `json:"healthCheckDestIp"` + HealthCheckType string `json:"healthCheckType"` + HealthCheckInterval int `json:"healthCheckInterval"` + HealthThreshold int `json:"healthThreshold"` + UnhealthThreshold int `json:"unhealthThreshold"` +} + +// 参数localCidrs只有在专线网关处于running状态时允许更新。 +type UpdateEtGatewayArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtGatewayId string `json:"etGatewayId"` + Name string `json:"name,omitempty"` + Speed int `json:"speed,omitempty"` + Description string `json:"description,omitempty"` + LocalCidrs []string `json:"localCidrs,omitempty"` +} +type BindEtArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtGatewayId string `json:"etGatewayId"` + EtId string `json:"etId"` + ChannelId string `json:"channelId"` + LocalCidrs []string `json:"localCidrs,omitempty"` +} + +type CreateHealthCheckArgs struct { + ClientToken string `json:"clientToken,omitempty"` + EtGatewayId string `json:"etGatewayId"` + HealthCheckSourceIp string `json:"healthCheckSourceIp,omitempty"` + HealthCheckType HealthCheckType `json:"healthCheckType,omitempty"` + HealthCheckPort int `json:"healthCheckPort,omitempty"` + HealthCheckInterval int `json:"healthCheckInterval"` + HealthThreshold int `json:"healthThreshold"` + UnhealthThreshold int `json:"unhealthThreshold"` + AutoGenerateRouteRule *bool `json:"autoGenerateRouteRule,omitempty"` +} diff --git a/bce-sdk-go/services/gaiadb/client.go b/bce-sdk-go/services/gaiadb/client.go new file mode 100644 index 0000000..6f00e1d --- /dev/null +++ b/bce-sdk-go/services/gaiadb/client.go @@ -0,0 +1,41 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for Gaiadb service + +// Package gaiadb defines the GAIADB services of BCE. The supported APIs are all defined in sub-package +package gaiadb + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + DEFAULT_ENDPOINT = "gaiadb.bj.baidubce.com" +) + +// Client of GAIADB service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} diff --git a/bce-sdk-go/services/gaiadb/client_test.go b/bce-sdk-go/services/gaiadb/client_test.go new file mode 100644 index 0000000..0fdf9a1 --- /dev/null +++ b/bce-sdk-go/services/gaiadb/client_test.go @@ -0,0 +1,700 @@ +package gaiadb + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + GAIADB_CLIENT *Client + GAIADB_ID = "gaiadbwjeq27" + ORDERID string + // set this value before start test + ACCOUNT_NAME = "baidu" + PASSWORD = "baidu@123" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +const ( + SDK_NAME_PREFIX = "sdk_gaiadb_" +) + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 1; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + GAIADB_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func getClientToken() string { + return util.NewUUID() +} +func TestClient_CreateGaiadb(t *testing.T) { + + args := &CreateClusterArgs{ + ClientToken: getClientToken(), + Number: 1, + ProductType: "postpay", + InstanceParam: InstanceParam{ + ReleaseVersion: "8.0", + SubnetId: "sbn-na4tmg4v11hs", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, + AllocatedStorageInGB: 5120, + VpcId: "vpc-it3v6qt3jhvj", + InstanceAmount: 2, + ProxyAmount: 2, + }, + } + result, err := GAIADB_CLIENT.CreateCluster(args) + + ExpectEqual(t.Errorf, nil, err) + + GAIADB_ID = result.ClusterIds[0] + ORDERID = result.OrderId + fmt.Println("GAIADB: ", GAIADB_ID) + fmt.Println("ORDERID: ", ORDERID) +} + +func TestClient_DeleteCluster(t *testing.T) { + err := GAIADB_CLIENT.DeleteCluster(GAIADB_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RenameCluster(t *testing.T) { + args := &ClusterName{ + ClusterName: "cluster_test", + } + err := GAIADB_CLIENT.RenameCluster(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ResizeCluster(t *testing.T) { + args := &ResizeClusterArgs{ + ResizeType: "resizeSlave", + AllocatedCpuInCore: 4, + AllocatedMemoryInMB: 8192, + } + result, err := GAIADB_CLIENT.ResizeCluster(GAIADB_ID, args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetClusterList(t *testing.T) { + args := &Marker{ + Marker: "-1", + MaxKeys: 1000, + } + result, err := GAIADB_CLIENT.GetClusterList(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetClusterDetail(t *testing.T) { + result, err := GAIADB_CLIENT.GetClusterDetail(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetClusterCapacity(t *testing.T) { + result, err := GAIADB_CLIENT.GetClusterCapacity(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_QueryClusterPrice(t *testing.T) { + args := &QueryPriceArgs{ + Number: 1, + InstanceParam: InstanceInfo{ + ReleaseVersion: "8.0", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, + AllocatedStorageInGB: 5120, + InstanceAmount: 2, + ProxyAmount: 2, + }, + ProductType: "postpay", + } + result, err := GAIADB_CLIENT.QueryClusterPrice(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_QueryResizeClusterPrice(t *testing.T) { + args := &QueryResizePriceArgs{ + ClusterId: GAIADB_ID, + ResizeType: "resizeSlave", + AllocatedCpuInCore: 2, + AllocatedMemoryInMB: 8192, + } + result, err := GAIADB_CLIENT.QueryResizeClusterPrice(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RebootInstance(t *testing.T) { + args := &RebootInstanceArgs{ + ExecuteAction: "executeNow", + } + err := GAIADB_CLIENT.RebootInstance(GAIADB_ID, "gaiadbm5h6ys-secondary-129aafc0", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindTags(t *testing.T) { + args := &BindTagsArgs{ + Resources: []Resource{ + { + ResourceId: GAIADB_ID, + Tags: []Tag{ + { + TagKey: "testTagKey", + TagValue: "testTagValue", + }, + }, + }, + }, + } + err := GAIADB_CLIENT.BindTags(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ClusterSwitch(t *testing.T) { + args := &ClusterSwitchArgs{ + ExecuteAction: "executeNow", + SecondaryInstanceId: GAIADB_ID, + } + result, err := GAIADB_CLIENT.ClusterSwitch(GAIADB_ID, args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetInterfaceList(t *testing.T) { + result, err := GAIADB_CLIENT.GetInterfaceList(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateDnsName(t *testing.T) { + args := &UpdateDnsNameArgs{ + InterfaceId: "gaiadbm5h6ys_interface0000", + DnsName: "my.gaiadb.bj.baidubce.com", + } + err := GAIADB_CLIENT.UpdateDnsName(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateInterface(t *testing.T) { + args := &UpdateInterfaceArgs{ + InterfaceId: "gaiadbm5h6ys_interface0000", + Interface: InterfaceInfo{ + MasterReadable: 1, + AddressName: "addressname", + InstanceBinding: []string{ + "gaiadbymbrc8-primary-6f1cc3a2", + "gaiadbymbrc8-secondary-ec909467", + }, + }, + } + err := GAIADB_CLIENT.UpdateInterface(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_NewInstanceAutoJoin(t *testing.T) { + args := &NewInstanceAutoJoinArgs{ + AutoJoinRequestItems: []AutoJoinRequestItem{ + { + NewInstanceAutoJoin: "off", + InterfaceId: "gaiadbymbrc8-primary-6f1cc3a2", + }, + }, + } + err := GAIADB_CLIENT.NewInstanceAutoJoin(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateAccount(t *testing.T) { + args := &CreateAccountArgs{ + AccountName: "testaccount", + Password: "baidu@123", + AccountType: "common", + Remark: "testRemark", + } + err := GAIADB_CLIENT.CreateAccount(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAccount(t *testing.T) { + err := GAIADB_CLIENT.DeleteAccount(GAIADB_ID, "testaccount") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetAccountDetail(t *testing.T) { + result, err := GAIADB_CLIENT.GetAccountDetail(GAIADB_ID, "testaccount") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_GetAccountList(t *testing.T) { + result, err := GAIADB_CLIENT.GetAccountList(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountRemark(t *testing.T) { + args := &RemarkArgs{ + Remark: "remark", + Etag: "v0", + } + err := GAIADB_CLIENT.UpdateAccountRemark(GAIADB_ID, "testaccount", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountAuthIp(t *testing.T) { + args := &AuthIpArgs{ + Action: "ipAdd", + Value: AuthIp{ + Authip: []string{"10.10.10.10"}, + Authbns: []string{}, + }, + } + err := GAIADB_CLIENT.UpdateAccountAuthIp(GAIADB_ID, "testaccount", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountPrivileges(t *testing.T) { + args := &PrivilegesArgs{ + DatabasePrivileges: []DatabasePrivilege{ + { + DbName: "testdb", + AuthType: "definePrivilege", + Privileges: []string{"UPDATE"}, + }, + }, + Etag: "v0", + } + err := GAIADB_CLIENT.UpdateAccountPrivileges(GAIADB_ID, "testaccount", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountPassword(t *testing.T) { + args := &PasswordArgs{ + Password: "testpassword", + Etag: "v0", + } + err := GAIADB_CLIENT.UpdateAccountPassword(GAIADB_ID, "testaccount", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateDatabase(t *testing.T) { + args := &CreateDatabaseArgs{ + DbName: "test_db", + CharacterSetName: "utf8", + Remark: "sdk test", + } + err := GAIADB_CLIENT.CreateDatabase(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteDatabase(t *testing.T) { + err := GAIADB_CLIENT.DeleteDatabase(GAIADB_ID, "test_db") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListDatabase(t *testing.T) { + result, err := GAIADB_CLIENT.ListDatabase(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_CreateSnapshot(t *testing.T) { + err := GAIADB_CLIENT.CreateSnapshot(GAIADB_ID) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_ListSnapshot(t *testing.T) { + result, err := GAIADB_CLIENT.ListSnapshot(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateSnapshotPolicy(t *testing.T) { + args := &UpdateSnapshotPolicyArgs{ + DataBackupWeekDay: []string{"Monday"}, + DataBackupRetainStrategys: []DataBackupRetainStrategy{{ + StartSeconds: 0, + RetainCount: "8", + Precision: 86400, + EndSeconds: -691200, + }}, + DataBackupTime: "02:00:00Z", + } + err := GAIADB_CLIENT.UpdateSnapshotPolicy(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_GetSnapshotPolicy(t *testing.T) { + result, err := GAIADB_CLIENT.GetSnapshotPolicy(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateWhiteList(t *testing.T) { + args := &WhiteList{ + AuthIps: []string{"192.168.1.2"}, + Etag: "v0", + } + err := GAIADB_CLIENT.UpdateWhiteList(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetWhiteList(t *testing.T) { + result, err := GAIADB_CLIENT.GetWhiteList(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateMultiactiveGroup(t *testing.T) { + args := &CreateMultiactiveGroupArgs{ + LeaderClusterId: GAIADB_ID, + MultiActiveGroupName: "test_multiactive_group", + } + result, err := GAIADB_CLIENT.CreateMultiactiveGroup(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteMultiactiveGroup(t *testing.T) { + err := GAIADB_CLIENT.DeleteMultiactiveGroup("gaiagroup-fru5yw") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RenameMultiactiveGroup(t *testing.T) { + args := &RenameMultiactiveGroupArgs{ + MultiActiveGroupName: "test_multiactive_group", + } + err := GAIADB_CLIENT.RenameMultiactiveGroup("gaiagroup-5r5aur", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_MultiactiveGroupList(t *testing.T) { + result, err := GAIADB_CLIENT.MultiactiveGroupList() + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_MultiactiveGroupDetail(t *testing.T) { + result, err := GAIADB_CLIENT.MultiactiveGroupDetail("gaiagroup-0luzwo") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSyncStatus(t *testing.T) { + result, err := GAIADB_CLIENT.GetSyncStatus("gaiagroup-0luzwo", GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupExchange(t *testing.T) { + args := &ExchangeArgs{ + ExecuteAction: "executeNow", + NewLeaderClusterId: GAIADB_ID, + } + err := GAIADB_CLIENT.GroupExchange("gaiagroup-0luzwo", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetParamsList(t *testing.T) { + result, err := GAIADB_CLIENT.GetParamsList(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetParamsHistory(t *testing.T) { + result, err := GAIADB_CLIENT.GetParamsHistory(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateParams(t *testing.T) { + args := &UpdateParamsArgs{ + Params: map[string]interface{}{ + "auto_increment_increment": "5", + }, + Timing: "now", + } + err := GAIADB_CLIENT.UpdateParams(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListParamTemplate(t *testing.T) { + args := &ListParamTempArgs{ + Detail: 0, + Type: "mysql", + PageNo: 1, + PageSize: 10, + } + result, err := GAIADB_CLIENT.ListParamTemplate(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_SaveAsParamTemplate(t *testing.T) { + args := &ParamTempArgs{ + Type: "mysql", + Version: "8.0", + Description: "create by sdk", + Name: "sdk_test", + Source: GAIADB_ID, + } + err := GAIADB_CLIENT.SaveAsParamTemplate(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetTemplateApplyRecords(t *testing.T) { + result, err := GAIADB_CLIENT.GetTemplateApplyRecords("ce8a8245-1d9b-c844-bff8-818933461baa") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteParamsFromTemp(t *testing.T) { + args := &Params{ + Params: []string{"long_query_time"}, + } + err := GAIADB_CLIENT.DeleteParamsFromTemp("ce8a8245-1d9b-c844-bff8-818933461baa", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateParamTemplate(t *testing.T) { + args := &UpdateParamTplArgs{ + Name: "test_template", + Description: "test_template_description", + } + err := GAIADB_CLIENT.UpdateParamTemplate("ce8a8245-1d9b-c844-bff8-818933461baa", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ModifyParams(t *testing.T) { + args := &ModifyParamsArgs{ + Params: map[string]interface{}{ + "auto_increment_increment": "5", + "long_query_time": "6.6", + }, + } + err := GAIADB_CLIENT.ModifyParams("ce8a8245-1d9b-c844-bff8-818933461baa", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteParamTemplate(t *testing.T) { + err := GAIADB_CLIENT.DeleteParamTemplate("ce8a8245-1d9b-c844-bff8-818933461baa") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateParamTemplate(t *testing.T) { + args := &CreateParamTemplateArgs{ + Name: "test_template", + Type: "mysql", + Version: "8.0", + Description: "test_template_description", + } + err := GAIADB_CLIENT.CreateParamTemplate(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetParamTemplateDetail(t *testing.T) { + result, err := GAIADB_CLIENT.GetParamTemplateDetail("ce8a8245-1d9b-c844-bff8-818933461baa", "0") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetParamTemplateHistory(t *testing.T) { + result, err := GAIADB_CLIENT.GetParamTemplateHistory("ce8a8245-1d9b-c844-bff8-818933461baa", "addParam") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ApplyParamTemplate(t *testing.T) { + args := &ApplyParamTemplateArgs{ + Timing: "now", + Clusters: map[string]interface{}{ + "gaiadbk3pyxv": []interface{}{}, + }, + } + err := GAIADB_CLIENT.ApplyParamTemplate("ce8a8245-1d9b-c844-bff8-818933461baa", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateMaintenTime(t *testing.T) { + args := &UpdateMaintenTimeArgs{ + Period: "1,2,3", + StartTime: "03:00", + Duration: 1, + } + err := GAIADB_CLIENT.UpdateMaintenTime(GAIADB_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetMaintenTime(t *testing.T) { + result, err := GAIADB_CLIENT.GetMaintenTime(GAIADB_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlDetail(t *testing.T) { + args := &GetSlowSqlArgs{ + Page: "1", + PageSize: "10", + } + result, err := GAIADB_CLIENT.GetSlowSqlDetail(GAIADB_ID, args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_SlowSqlAdvice(t *testing.T) { + result, err := GAIADB_CLIENT.SlowSqlAdvice(GAIADB_ID, "a41ff8fe-b0c6-407c-91f6-354717c3fbaa") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBinlogDetail(t *testing.T) { + args := &GetBinlogArgs{ + AppID: GAIADB_ID, + LogBackupType: "logical", + } + result, err := GAIADB_CLIENT.GetBinlogDetail("1694660508228961814", args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBinlogList(t *testing.T) { + args := &GetBinlogListArgs{ + AppID: GAIADB_ID, + LogBackupType: "logical", + PageNo: 1, + PageSize: 10, + } + result, err := GAIADB_CLIENT.GetBinlogList(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ExecuteTaskNow(t *testing.T) { + taskId := "3773297" + err := GAIADB_CLIENT.ExecuteTaskNow(taskId) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CancelTask(t *testing.T) { + taskId := "3773297" + err := GAIADB_CLIENT.CancelTask(taskId) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetTaskList(t *testing.T) { + args := &TaskListArgs{ + Region: "bj", + StartTime: "2023-09-11 16:00:00", + } + result, err := GAIADB_CLIENT.GetTaskList(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetClusterByVpcId(t *testing.T) { + result, err := GAIADB_CLIENT.GetClusterByVpcId("9556bf45-5867-4495-83c5-bd945b782503") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetClusterByLbId(t *testing.T) { + result, err := GAIADB_CLIENT.GetClusterByLbId("496d6b552f316b313863786a4b32457a2f4732416e773d3d") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetOrderInfo(t *testing.T) { + result, err := GAIADB_CLIENT.GetOrderInfo("8a3c9bb4313e489f859938b7d199487f") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/gaiadb/gaiadb.go b/bce-sdk-go/services/gaiadb/gaiadb.go new file mode 100644 index 0000000..5652257 --- /dev/null +++ b/bce-sdk-go/services/gaiadb/gaiadb.go @@ -0,0 +1,1391 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// gaiadb.go - the gaiadb APIs definition supported by the GAIADB service +package gaiadb + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func (c *Client) Request(method, uri string, body interface{}) (interface{}, error) { + res := struct{}{} + req := bce.NewRequestBuilder(c). + WithMethod(method). + WithURL(uri). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + var err error + if body != nil { + err = req. + WithBody(body). + WithResult(res). + Do() + } else { + err = req. + WithResult(res). + Do() + } + + return res, err +} +func getGaiadbUri() string { + return "/v1/gaiadb" +} +func Json(v interface{}) string { + jsonStr, err := json.Marshal(v) + if err != nil { + panic("convert to json faild") + } + return string(jsonStr) +} + +// Convert struct to request params +func getQueryParams(val interface{}) (map[string]string, error) { + var params map[string]string + if val != nil { + err := json.Unmarshal([]byte(Json(val)), ¶ms) + if err != nil { + return nil, err + } + } + return params, nil +} + +// CreateCluster - create gaiadb cluster +// +// PARAMS: +// - args: the arguments to create gaiadb cluster +// +// RETURNS: +// - *CreateResult: the result of create gaiadb cluster +// - error: nil if success otherwise the specific error +func (c *Client) CreateCluster(args *CreateClusterArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + result := &CreateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/cluster"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// DeleteCluster - delete gaiadb cluster +// +// PARAMS: +// - clusterId: the cluster id which you want to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteCluster(clusterId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getGaiadbUri()+"/cluster/"+clusterId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// RenameCluster - rename gaiadb cluster +// +// PARAMS: +// - clusterId: the cluster id which you want to delete +// - *ClusterName: the new cluster name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenameCluster(clusterId string, args *ClusterName) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/cluster/"+clusterId). + WithQueryParam("clusterName", ""). + WithBody(args). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// ResizeCluster - resize gaiadb cluster +// +// PARAMS: +// - clusterId: the cluster id which you want to delete +// - *ResizeClusterArgs: the arguments to resize gaiadb cluster +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ResizeResult: the result of resize gaiadb cluster +func (c *Client) ResizeCluster(clusterId string, args *ResizeClusterArgs) (*OrderId, error) { + result := &OrderId{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/cluster/"+clusterId). + WithQueryParam("resize", ""). + WithBody(args). + WithResult(result). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return result, err +} + +// GetClusterList - get gaiadb cluster list +// +// PARAMS: +// - *Markder: the arguments to get cluster list +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ClusterListResult: the result of get cluster list +func (c *Client) GetClusterList(args *Marker) (*ClusterListResult, error) { + result := &ClusterListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/cluster"). + WithBody(args). + WithResult(result). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return result, err +} + +// GetClusterCapacity - get cluster Capacity +// PARAMS: +// - ClusterId: cluster id +// +// RETURNS: +// - *ClusterCapacityResult: the result of cluster detail +// - error: nil if success otherwise the specific error +func (c *Client) GetClusterDetail(clusterId string) (*ClusterDetailResult, error) { + result := &ClusterDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri() + "/cluster/" + clusterId). + WithResult(result). + Do() + + return result, err +} + +// GetClusterCapacity - get cluster capacity +// PARAMS: +// - ClusterId: cluster id +// +// RETURNS: +// - *ClusterCapacityResult: the result of cluster capacity +// - error: nil if success otherwise the specific error +func (c *Client) GetClusterCapacity(clusterId string) (*ClusterCapacityResult, error) { + result := &ClusterCapacityResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri() + "/" + clusterId + "/capacity"). + WithResult(result). + Do() + + return result, err +} + +// QueryClusterPrice - query cluster price +// +// PARAMS: +// - args: the arguments to query cluster price +// +// RETURNS: +// - *PriceResult: the result of query cluster price +// - error: nil if success otherwise the specific error +func (c *Client) QueryClusterPrice(args *QueryPriceArgs) (*PriceResult, error) { + result := &PriceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/price"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// QueryResizeClusterPrice - query resize cluster price +// +// PARAMS: +// - args: the arguments to query resize cluster price +// +// RETURNS: +// - *PriceResult: the result of query resize cluster price +// - error: nil if success otherwise the specific error +func (c *Client) QueryResizeClusterPrice(args *QueryResizePriceArgs) (*PriceResult, error) { + result := &PriceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/price/diff"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// RebootInstance - reboot instance +// +// PARAMS: +// - args: the arguments to reboot instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstance(clusterId, instanceId string, args *RebootInstanceArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/cluster/"+clusterId+"/instance/"+instanceId+"/reboot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// BindTags - bind tags +// +// PARAMS: +// - args: the arguments to bind tags +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindTags(args *BindTagsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL("/v1/tags"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// ClusterSwitch - cluster switch +// +// PARAMS: +// - clusterId: the cluster id +// - args: the arguments to switch cluster +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *SwitchResult: the result of switch cluster +func (c *Client) ClusterSwitch(clusterId string, args *ClusterSwitchArgs) (*ClusterSwitchResult, error) { + result := &ClusterSwitchResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/cluster/"+clusterId+"/switch"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetInterfaceList - get interface list +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - *InterfaceListResult: the result of interface list +// - error: nil if success otherwise the specific error +func (c *Client) GetInterfaceList(clusterId string) (*InterfaceListResult, error) { + result := &InterfaceListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri() + "/" + clusterId + "/interface"). + WithResult(result). + Do() + + return result, err +} + +// UpdateDnsName - update dns name +// +// PARAMS: +// - clusterId: the cluster id +// - args: the arguments to update dns name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateDnsName(clusterId string, args *UpdateDnsNameArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/interface/dns-name"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// UpdateInterface - update interface +// +// PARAMS: +// - clusterId: cluster id +// - args: the arguments to update interface +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInterface(clusterId string, args *UpdateInterfaceArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/interface"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// NewInstanceAutoJoin - new instance auto join +// +// PARAMS: +// - clusterId: cluster id +// - args: the arguments to new instance auto join +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) NewInstanceAutoJoin(clusterId string, args *NewInstanceAutoJoinArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/interface/new-instance-auto-join"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// CreateAccount - create account +// +// PARAMS: +// - clusterId: cluster id +// - args: the arguments to create account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateAccount(clusterId string, args *CreateAccountArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/"+clusterId+"/account"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// DeleteAccount - delete account +// +// PARAMS: +// - clusterId: cluster id +// - accountName: account name to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAccount(clusterId, accountName string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getGaiadbUri()+"/"+clusterId+"/account/"+accountName). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// GetAccountDetail - get account detail +// +// PARAMS: +// - clusterId: cluster id +// - accountName: account name to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetAccountDetail(clusterId, accountName string) (*AccountDetail, error) { + result := &AccountDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/account/"+accountName). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// GetAccountList - get account list +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetAccountList(clusterId string) (*AccountList, error) { + result := &AccountList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/account"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// UpdateAccountRemark - update account remark +// +// PARAMS: +// - clusterId: cluster id +// - accountName: account name to update +// - args: the arguments to update account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountRemark(clusterId, accountName string, args *RemarkArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/account/"+accountName). + WithQueryParam("remark", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// UpdateAccountAuthIp - update account auth ip +// +// PARAMS: +// - clusterId: cluster id +// - accountName: account name to update +// - args: the arguments to update account auth ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountAuthIp(clusterId, accountName string, args *AuthIpArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/account/"+accountName). + WithQueryParam("authip", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// UpdateAccountPrivileges - update account privileges +// +// PARAMS: +// - clusterId: cluster id +// - accountName: account name to update +// - args: the arguments to update account privileges +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPrivileges(clusterId, accountName string, args *PrivilegesArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/account/"+accountName). + WithQueryParam("privileges", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// UpdateAccountPassword - update account password +// +// PARAMS: +// - clusterId: cluster id +// - accountName: account name to update +// - args: the arguments to update account password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPassword(clusterId, accountName string, args *PasswordArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/account/"+accountName). + WithQueryParam("password", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// CreateDatabase - create database +// +// PARAMS: +// - clusterId: cluster id +// - args: the arguments to create database +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateDatabase(clusterId string, args *CreateDatabaseArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/"+clusterId+"/database"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// DeleteDatabase - delete database +// +// PARAMS: +// - clusterId: cluster id +// - dbName: the database name to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDatabase(clusterId, dbName string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getGaiadbUri()+"/"+clusterId+"/database/"+dbName). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// ListDatabase - list database +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *DatabaseList: the database list +func (c *Client) ListDatabase(clusterId string) (*DatabaseList, error) { + result := &DatabaseList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/database"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// CreateSnapshot - create snapshot +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateSnapshot(clusterId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/"+clusterId+"/snapshot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// ListSnapshot - list snapshot +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *SnapshotList: the snapshot list +func (c *Client) ListSnapshot(clusterId string) (*SnapshotList, error) { + result := &SnapshotList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/snapshot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// UpdateSnapshotPolicy - update snapshot policy +// +// PARAMS: +// - clusterId: cluster id +// - args: the arguments to update snapshot policy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSnapshotPolicy(clusterId string, args *UpdateSnapshotPolicyArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/snapshot/policy"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// GetSnapshotPolicy - get snapshot policy +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *SnapshotPolicy: the snapshot policy +func (c *Client) GetSnapshotPolicy(clusterId string) (*SnapshotPolicy, error) { + result := &SnapshotPolicy{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/snapshot/policy"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// UpdateWhiteList - update white list +// +// PARAMS: +// - clusterId : cluster id +// - args: the arguments to update white list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateWhiteList(clusterId string, args *WhiteList) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/whitelist"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// GetWhiteList - get white list +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *WhiteListResult: the result of white list +func (c *Client) GetWhiteList(clusterId string) (*WhiteList, error) { + result := &WhiteList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/whitelist"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// CreateMultiactiveGroup - create multiactive group +// +// PARAMS: +// - args: the arguments to create multiactive group +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *CreateMultiactiveGroupResult: multiactive group result +func (c *Client) CreateMultiactiveGroup(args *CreateMultiactiveGroupArgs) (*CreateMultiactiveGroupResult, error) { + result := &CreateMultiactiveGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/multiactivegroup"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// DeleteMultiactiveGroup - elete multiactive group +// +// PARAMS: +// - groupId: multiactive group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteMultiactiveGroup(groupId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getGaiadbUri()+"/multiactivegroup/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// RenameMultiactiveGroup - rename multiactive group +// +// PARAMS: +// - groupId: multiactive group id +// - args: the arguments to rename multiactive group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenameMultiactiveGroup(groupId string, args *RenameMultiactiveGroupArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/multiactivegroup/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("multiActiveGroupName", ""). + WithBody(args). + Do() + + return err +} + +// MultiactiveGroupList - list multiactive group +// +// PARAMS: +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *MultiactiveGroupListResult: multiactive group list result +func (c *Client) MultiactiveGroupList() (*MultiactiveGroupListResult, error) { + result := &MultiactiveGroupListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/multiactivegroup"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// MultiactiveGroupDetail - get multiactive group detail +// +// PARAMS: +// - groupId: multiactive group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *MultiactiveGroupDetailResult: multiactive group Detail result +func (c *Client) MultiactiveGroupDetail(groupId string) (*MultiactiveGroupDetailResult, error) { + result := &MultiactiveGroupDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/multiactivegroup/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// GetSyncStatus - get multiactive group sync status +// +// PARAMS: +// - groupId: multiactive group id +// - followerClusterId: the follower cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetSyncStatusResult: multiactive group Detail result +func (c *Client) GetSyncStatus(groupId, followerClusterId string) (*GetSyncStatusResult, error) { + result := &GetSyncStatusResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/multiactivegroup/"+groupId+"/syncStatus"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("followerClusterId", followerClusterId). + WithResult(result). + Do() + + return result, err +} + +// GroupExchange - group exchange +// +// PARAMS: +// - groupId: multiactive group id +// - args: the arguments to group exchange +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupExchange(groupId string, args *ExchangeArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/multiactivegroup/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("exchange", ""). + WithBody(args). + Do() + + return err +} + +// GetParamsList - get paremeters list +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetParamsListResult: get paremeters list result +func (c *Client) GetParamsList(clusterId string) (*GetParamsListResult, error) { + result := &GetParamsListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/cluster/"+clusterId+"/compute/params"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// GetParamsHistory - get paremeters history +// +// PARAMS: +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetParamsHistoryResult: get paremeters history result +func (c *Client) GetParamsHistory(clusterId string) (*GetParamsHistoryResult, error) { + result := &GetParamsHistoryResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/cluster/"+clusterId+"/compute/params/history"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// UpdateParams - update paremeters +// +// PARAMS: +// - clusterId: cluster id +// - args: the arguments to update paremeters +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateParams(clusterId string, args *UpdateParamsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/cluster/"+clusterId+"/compute/params"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// ListParamTemplate - list param template +// +// PARAMS: +// - args: the arguments to list param template +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ListParamTemplateResult: get paremeters list result +func (c *Client) ListParamTemplate(args *ListParamTempArgs) (*ListParamTempResult, error) { + result := &ListParamTempResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/paramTemplate/listParaTemplate"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("detail", strconv.Itoa(args.Detail)). + WithQueryParamFilter("type", args.Type). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithResult(result). + Do() + + return result, err +} + +// SaveAsParamTemplate - save as params template +// +// PARAMS: +// - args: the arguments to save as params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SaveAsParamTemplate(args *ParamTempArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/paramTemplate"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// GetTemplateApplyRecords - get template apply records +// +// PARAMS: +// - templateId: template id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetTemplateApplyRecordsResult: get template apply records result +func (c *Client) GetTemplateApplyRecords(templateId string) (*GetTemplateApplyRecordsResult, error) { + result := &GetTemplateApplyRecordsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId+"/apply"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// DeleteParamsFromTemp - delete params from template +// +// PARAMS: +// - templateId: template id +// - args: the params to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteParamsFromTemp(templateId string, args *Params) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId+"/delParams"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// UpdateParamTemplate - update param template +// +// PARAMS: +// - templateId: template id +// - args: the params to update +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateParamTemplate(templateId string, args *UpdateParamTplArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// ModifyParams - modify params +// +// PARAMS: +// - templateId: template id +// - args: the params to modify +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyParams(templateId string, args *ModifyParamsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId+"/modifyParams"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// DeleteParamTemplate - delete param template +// +// PARAMS: +// - templateId: template id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteParamTemplate(templateId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// CreateParamTemplate - create param template +// +// PARAMS: +// - args: the params to create param template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateParamTemplate(args *CreateParamTemplateArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/paramTemplate/create"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// GetParamTemplateDetail - get param template detail +// +// PARAMS: +// - templateId: template id +// - detail: detail type +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetParamTemplateDetail(templateId, detail string) (*ParamTemplateDetail, error) { + result := &ParamTemplateDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId). + WithQueryParamFilter("detail", detail). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// GetParamTemplateHistory - get param template history +// +// PARAMS: +// - templateId: template id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetParamTemplateHistory(templateId, action string) (*ParamTemplateHistory, error) { + result := &ParamTemplateHistory{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId+"/history"). + WithQueryParamFilter("action", action). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// ApplyParamTemplate - apply param template +// +// PARAMS: +// +// -templateId: template id +// - args: the params to apply param template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ApplyParamTemplate(templateId string, args *ApplyParamTemplateArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGaiadbUri()+"/paramTemplate/"+templateId+"/apply"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// UpdateMaintenTime - update maintenTime +// +// PARAMS: +// +// - clusterId: cluster id +// - args: the params to update maintenTime +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateMaintenTime(clusterId string, args *UpdateMaintenTimeArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/"+clusterId+"/maintentime"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// GetMaintenTime - get maintenTime +// +// PARAMS: +// +// - clusterId: cluster id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *MaintenTime: maintenTime data +func (c *Client) GetMaintenTime(clusterId string) (*MaintenTimeDetail, error) { + result := &MaintenTimeDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/maintentime"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlDetail - get slow sql detail +// +// PARAMS: +// +// - args: the params to get slow sql detail +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *SlowSqlDetail: slow sql detail +func (c *Client) GetSlowSqlDetail(clusterId string, args *GetSlowSqlArgs) (*SlowSqlDetailDetail, error) { + result := &SlowSqlDetailDetail{} + params, err2 := getQueryParams(args) + if err2 != nil { + return nil, err2 + } + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/slowsql/gaiadb-s"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParams(params). + WithResult(result). + Do() + + return result, err +} + +// SlowSqlAdvice - slow sql advice +// +// PARAMS: +// +// - clusterId: cluster id +// - sqlId : sql id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *SlowSqlAdviceDetail: slow sql advice detail +func (c *Client) SlowSqlAdvice(clusterId, sqlId string) (*SlowSqlAdviceDetail, error) { + result := &SlowSqlAdviceDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/"+clusterId+"/slowsql/gaiadb-s/"+sqlId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} + +// GetBinlogDetail - get binlog detail +// +// PARAMS: +// - binlogId : binlog id +// - args: the params to get binlog detail +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *BinlogDetail: binlog detail +func (c *Client) GetBinlogDetail(binlogId string, args *GetBinlogArgs) (*BinlogDetail, error) { + result := &BinlogDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/binlog/"+binlogId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("appID", args.AppID). + WithQueryParamFilter("logBackupType", args.LogBackupType). + WithResult(result). + Do() + + return result, err +} + +// GetBinlogList - get binlog list +// +// PARAMS: +// +// - args: the params to get binlog list +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *BinlogList: binlog List +func (c *Client) GetBinlogList(args *GetBinlogListArgs) (*BinlogList, error) { + result := &BinlogList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/binlog/list"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("appID", args.AppID). + WithQueryParamFilter("logBackupType", args.LogBackupType). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithQueryParamFilter("startDateTime", args.StartDateTime). + WithQueryParamFilter("endDateTime", args.EndDateTime). + WithResult(result). + Do() + + return result, err +} + +// ExecuteTaskNow - execute task now +// +// PARAMS: +// - taskId : task id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ExecuteTaskNow(taskId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/task/"+taskId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("executeNow", ""). + Do() + + return err +} + +// CancelTask - cancel task +// +// PARAMS: +// - taskId : task id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CancelTask(taskId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGaiadbUri()+"/task/"+taskId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParam("cancel", ""). + Do() + + return err +} + +// GetTaskList - get task list +// +// PARAMS: +// - args : the params to get task list +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *TaskList: task List +func (c *Client) GetTaskList(args *TaskListArgs) (*TaskList, error) { + result := &TaskList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/task"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("region", args.Region). + WithQueryParamFilter("startTime", args.StartTime). + WithQueryParamFilter("endTime", args.EndTime). + WithResult(result). + Do() + + return result, err +} + +// GetClusterByVpcId - get cluster by vpc id +// +// PARAMS: +// - vpcId : the params to get cluster by vpc id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ClusterList: cluster List +func (c *Client) GetClusterByVpcId(vpcId string) (*ClusterList, error) { + result := &ClusterList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/security/byVpc"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("vpcId", vpcId). + WithResult(result). + Do() + + return result, err +} + +// GetClusterByLbId - get cluster by lb id +// +// PARAMS: +// - LbId : the params to get cluster by lb id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ClusterList: cluster List +func (c *Client) GetClusterByLbId(lbIds string) (*ClusterList, error) { + result := &ClusterList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/security/byLb"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParamFilter("lbIds", lbIds). + WithResult(result). + Do() + + return result, err +} + +// GetOrderInfo - get order info +// +// PARAMS: +// - orderId : the params to get order info +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *OrderInfo: order info +func (c *Client) GetOrderInfo(orderId string) (*OrderInfo, error) { + result := &OrderInfo{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGaiadbUri()+"/order/"+orderId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/gaiadb/model.go b/bce-sdk-go/services/gaiadb/model.go new file mode 100644 index 0000000..04d9e69 --- /dev/null +++ b/bce-sdk-go/services/gaiadb/model.go @@ -0,0 +1,693 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package gaiadb + +type CreateClusterArgs struct { + ClientToken string `json:"-"` + ProductType string `json:"productType"` + Duration string `json:"duration,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + Number int `json:"number"` + InstanceParam InstanceParam `json:"instanceParam"` +} +type InstanceParam struct { + ReleaseVersion string `json:"releaseVersion"` + AllocatedCpuInCore int `json:"allocatedCpuInCore"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB"` + AllocatedStorageInGB int `json:"allocatedStorageInGB"` + InstanceAmount int `json:"instanceAmount"` + ProxyAmount int `json:"proxyAmount"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + SrcClusterId string `json:"srcClusterId,omitempty"` + SnapshotId string `json:"snapshotId,omitempty"` + Pit string `json:"pit,omitempty"` + LowerCaseTableNames string `json:"lowercaseTableNames,omitempty"` +} +type CreateResult struct { + OrderId string `json:"orderId"` + ClusterIds []string `json:"clusterIds"` +} + +type ClusterName struct { + ClusterName string `json:"clusterName"` +} + +type ResizeClusterArgs struct { + ResizeType string `json:"resizeType"` + SlaveId string `json:"slaveId,omitempty"` + AllocatedCpuInCore int `json:"allocatedCpuInCore,omitempty"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB,omitempty"` + ProxyAmount int `json:"proxyAmount,omitempty"` + InterfaceId int `json:"interfaceId,omitempty"` + Interfacee Interfacee `json:"interfacee"` +} +type Interfacee struct { + AddressName string `json:"addressName,omitempty"` + InstanceBinding []string `json:"instanceBinding,omitempty"` + ProxyAmount int `json:"proxyAmount,omitempty"` + ReadWriteMode string `json:"readWriteMode,omitempty"` + MasterReadable int `json:"masterReadable,omitempty"` +} + +type OrderId struct { + OrderId string `json:"orderId"` +} + +type Marker struct { + Marker string + MaxKeys int +} + +type ClusterListResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + Istruncated bool `json:"istruncated"` + Clusters []Cluster `json:"clusters"` +} + +type Cluster struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + Endpoint Endpoint `json:"endpoint"` + AllocatedCpuInCore int `json:"allocatedCpuInCore"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB"` + InstanceStatus string `json:"instanceStatus"` + PubliclyAccessible bool `json:"publiclyAccessible"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + InstanceAmount int `json:"instanceAmount"` + ProxyAmount int `json:"proxyAmount"` + ProductType string `json:"productType"` + MultiActiveGroupId string `json:"multiActiveGroupId"` + MultiActiveGroupRole string `json:"multiActiveGroupRole"` + MultiActiveGroupName string `json:"multiActiveGroupName"` +} + +type Endpoint struct { + Port int `json:"port"` + Address string `json:"address"` + VnetIp string `json:"vnetIp,omitempty"` + InetIp string `json:"inetIp,omitempty"` +} + +type ClusterDetailResult struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + Endpoint Endpoint `json:"endpoint"` + AllocatedCpuInCore int `json:"allocatedCpuInCore"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB"` + InstanceStatus string `json:"instanceStatus"` + PubliclyAccessible bool `json:"publiclyAccessible"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + InstanceAmount int `json:"instanceAmount"` + ProductType string `json:"productType"` + MultiActiveGroupId string `json:"multiActiveGroupId"` + MultiActiveGroupRole string `json:"multiActiveGroupRole"` + MultiActiveGroupName string `json:"multiActiveGroupName"` + ComputeList []ComputeNode `json:"computeList"` +} +type ComputeNode struct { + Role string `json:"role"` + InstanceId string `json:"instanceId"` + InstanceShortId string `json:"instanceShortId"` + InstanceUniqueId string `json:"instanceUniqueId"` + Status string `json:"status"` +} + +type ClusterCapacityResult struct { + TotalFree int `json:"totalFree"` + TotalCapacity int `json:"totalCapacity"` +} + +type QueryPriceArgs struct { + Number int `json:"number"` + InstanceParam InstanceInfo `json:"instanceParam"` + ProductType string `json:"productType"` + Duration int `json:"duration"` +} + +type InstanceInfo struct { + ReleaseVersion string `json:"releaseVersion"` + AllocatedStorageInGB int `json:"allocatedStorageInGB"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB"` + AllocatedCpuInCore int `json:"allocatedCpuInCore"` + InstanceAmount int `json:"instanceAmount"` + ProxyAmount int `json:"proxyAmount"` +} + +type PriceResult struct { + Price float32 `json:"price"` + CatalogPrice float32 `json:"catalogPrice,omitempty"` +} + +type QueryResizePriceArgs struct { + ClusterId string `json:"clusterId"` + ResizeType string `json:"resizeType"` + SlaveId string `json:"slaveId"` + AllocatedCpuInCore int `json:"allocatedCpuInCore"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB"` + ProxyAmount int `json:"proxyAmount"` + InterfaceId string `json:"interfaceId"` + Interfacee Interfacee `json:"interfacee"` +} + +type RebootInstanceArgs struct { + ExecuteAction string `json:"executeAction"` +} + +type BindTagsArgs struct { + Resources []Resource `json:"resources"` +} + +type Resource struct { + ResourceId string `json:"resourceId"` + Tags []Tag `json:"tags"` +} + +type Tag struct { + TagKey string `json:"tagKey"` + TagValue string `json:"tagValue"` +} + +type InterfaceListResult struct { + Interfaces []Interface `json:"interfaces"` +} +type Interface struct { + AppId string `json:"appId"` + InterfaceId string `json:"interfaceId"` + Status string `json:"status"` + CreateTime string `json:"createTime"` + InstanceBinding []string `json:"instanceBinding"` + NewInstanceAutoJoin int `json:"newInstanceAutoJoin"` + ReadWriteMode string `json:"readWriteMode"` + InterfaceType string `json:"interfaceType"` + MasterReadable int `json:"masterReadable"` + Access Access `json:"access"` + Flavor Flavor `json:"flavor"` + Proxies []Proxy `json:"proxies"` +} +type Proxy struct { + Id int `json:"id"` + ProxyId string `json:"proxyId"` +} +type Flavor struct { + RamInMB int `json:"ramInMB"` + DiskInGB string `json:"diskInGB"` + CpuInCore int `json:"cpuInCore"` +} +type Access struct { + Name string `json:"name"` + DnsName string `json:"dnsName"` + AddressName string `json:"addressName"` + Eip string `json:"eip"` +} + +type UpdateDnsNameArgs struct { + InterfaceId string `json:"instanceId"` + DnsName string `json:"dnsName"` +} + +type UpdateInterfaceArgs struct { + InterfaceId string `json:"instanceId"` + Interface InterfaceInfo `json:"interface"` +} +type InterfaceInfo struct { + MasterReadable int `json:"masterReadable"` + AddressName string `json:"addressName"` + InstanceBinding []string `json:"instanceBinding"` +} + +type NewInstanceAutoJoinArgs struct { + AutoJoinRequestItems []AutoJoinRequestItem `json:"autoJoinRequestItems"` +} +type AutoJoinRequestItem struct { + NewInstanceAutoJoin string `json:"newInstanceAutoJoin"` + InterfaceId string `json:"interfaceId"` +} +type WhiteList struct { + AuthIps []string `json:"authIps"` + Etag string `json:"etag"` +} + +type ClusterSwitchArgs struct { + ExecuteAction string `json:"executeAction"` + SecondaryInstanceId string `json:"secondaryInstanceId"` +} + +type ClusterSwitchResult struct { + Switch TaskId `json:"switch"` +} +type TaskId struct { + TaskId int `json:"taskId"` +} + +type CreateAccountArgs struct { + AccountName string `json:"accountName"` + Password string `json:"password"` + AccountType string `json:"accountType"` + Remark string `json:"remark"` +} + +type AccountDetail struct { + Account AccountInfo `json:"account"` +} +type AccountInfo struct { + AccountName string `json:"accountName"` + Remark string `json:"remark"` + AccountStatus string `json:"accountStatus"` + AccountType string `json:"accountType"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` + Etag string `json:"etag"` +} +type DatabasePrivilege struct { + DbName string `json:"dbName"` + AuthType string `json:"authType"` + Privileges []string `json:"privileges"` +} + +type AccountList struct { + Accounts []AccountInfo `json:"accounts"` +} + +type RemarkArgs struct { + Remark string `json:"remark"` + Etag string `json:"etag"` +} + +type AuthIpArgs struct { + Action string `json:"action"` + Value AuthIp `json:"value"` + Etag string `json:"etag"` +} +type AuthIp struct { + Authip []string `json:"authip"` + Authbns []string `json:"authbns"` +} + +type PrivilegesArgs struct { + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` + Etag string `json:"etag"` +} +type PasswordArgs struct { + Password string `json:"password"` + Etag string `json:"etag"` +} + +type CreateDatabaseArgs struct { + DbName string `json:"dbName"` + CharacterSetName string `json:"characterSetName"` + Remark string `json:"remark"` +} + +type DatabaseList struct { + Databases []DatabaseInfo `json:"databases"` +} +type DatabaseInfo struct { + DbName string `json:"dbName"` + Remark string `json:"remark"` + DbStatus string `json:"dbStatus"` + CharacterSetName string `json:"characterSetName"` + AccountPrivileges []AccountPrivilege `json:"accountPrivileges"` +} +type AccountPrivilege struct { + AccountName string `json:"accountName"` + AuthType string `json:"authType"` +} + +type SnapshotList struct { + Snapshots []Snapshot `json:"snapshots"` +} +type Snapshot struct { + SnapshotId string `json:"snapshotId"` + AppId string `json:"appId"` + SnapshotSizeInBytes int `json:"snapshotSizeInBytes"` + SnapshotType string `json:"snapshotType"` + SnapshotStatus string `json:"snapshotStatus"` + SnapshotStartTime string `json:"snapshotStartTime"` + SnapshotEndTime string `json:"snapshotEndTime"` + SnapshotDataTime string `json:"snapshotDataTime"` +} + +type UpdateSnapshotPolicyArgs struct { + DataBackupWeekDay []string `json:"dataBackupWeekDay"` + DataBackupRetainStrategys []DataBackupRetainStrategy `json:"dataBackupRetainStrategys"` + DataBackupTime string `json:"dataBackupTime"` +} +type DataBackupRetainStrategy struct { + StartSeconds int `json:"startSeconds"` + RetainCount string `json:"retainCount"` + Precision int `json:"precision"` + EndSeconds int `json:"endSeconds"` +} +type SnapshotPolicy struct { + Policys []SnapshotPolicyPolicy `json:"policys"` +} +type SnapshotPolicyPolicy struct { + PolicyID string `json:"policyID"` + PolicyName string `json:"policyName"` + DataBackupWeekDay []string `json:"dataBackupWeekDay"` + DataBackupTime string `json:"dataBackupTime"` + DataBackupRetainStrategys []DataBackupRetainStrategy `json:"dataBackupRetainStrategys"` + LogBackupRetainDays int `json:"logBackupRetainDays"` + SpeedLimitBytesPerSec int `json:"speedLimitBytesPerSec"` + EncryptStrategy EncryptStrategy `json:"encryptStrategy"` +} +type EncryptStrategy struct { + EncryptEnable bool `json:"encryptEnable"` + KeyManagementType string `json:"keyManagementType"` + KeyManagementServiceName string `json:"keyManagementServiceName"` + SecretKeyID string `json:"secretKeyID"` +} +type CreateMultiactiveGroupArgs struct { + LeaderClusterId string `json:"leaderClusterId"` + MultiActiveGroupName string `json:"multiActiveGroupName"` +} +type CreateMultiactiveGroupResult struct { + MultiActiveGroupId string `json:"multiActiveGroupId"` +} + +type RenameMultiactiveGroupArgs struct { + MultiActiveGroupName string `json:"multiActiveGroupName"` +} + +type MultiactiveGroupListResult struct { + MultiActiveGroupInfoList []MultiactiveGroupInfo `json:"multiActiveGroupInfoList"` +} +type MultiactiveGroupInfo struct { + MultiActiveGroupId string `json:"multiActiveGroupId"` + MultiActiveGroupName string `json:"multiActiveGroupName"` + Status string `json:"status"` + CreateTime string `json:"createTime"` + LeaderCluster LeaderCluster `json:"leaderCluster"` + FollowerClusterList []FollowerCluster `json:"followerClusterList"` +} +type LeaderCluster struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + Region string `json:"region"` + Azone string `json:"azone"` + Status string `json:"status"` + ScaleOutFlag bool `json:"scaleOutFlag"` +} +type FollowerCluster struct { + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + Region string `json:"region"` + Azone string `json:"azone"` + Status string `json:"status"` +} + +type MultiactiveGroupDetailResult struct { + MultiActiveGroupInfo MultiactiveGroupInfo `json:"multiActiveGroupInfo"` +} + +type GetSyncStatusResult struct { + DelayTime int `json:"delayTime"` + Status string `json:"status"` +} + +type ExchangeArgs struct { + ExecuteAction string `json:"executeAction"` + NewLeaderClusterId string `json:"newLeaderClusterId"` +} + +type GetParamsListResult struct { + Params []Param `json:"params"` +} +type Param struct { + Status string `json:"status"` + UpdateTime string `json:"updateTime"` + Type string `json:"type"` + Name string `json:"name"` + CaseSensitive bool `json:"caseSensitive"` + Modifiable bool `json:"modifiable"` + CreateTime string `json:"createTime"` + Attention string `json:"attention"` + Precision int `json:"precision"` + Value string `json:"value"` + AllowedValues string `json:"allowedValues"` + BestValue string `json:"bestValue"` + Id int64 `json:"id"` + Description string `json:"description"` + AllowEmpty bool `json:"allowEmpty"` +} + +type GetParamsHistoryResult struct { + Records []Record `json:"records"` +} +type Record struct { + Status string `json:"status"` + FinishTime string `json:"finishTime"` + Name string `json:"name"` + StartTime string `json:"startTime"` + AfterValue string `json:"afterValue"` + BeforeValue string `json:"beforeValue"` + TaskId int64 `json:"taskId"` + Id int64 `json:"id"` +} + +type UpdateParamsArgs struct { + Params ParamsItem `json:"params"` + Timing string `json:"timing"` +} + +type ParamsItem map[string]interface{} + +type ListParamTempArgs struct { + Detail int `json:"detail,omitempty"` + Type string `json:"type,omitempty"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` +} +type ListParamTempResult struct { + ParamTemplates []ParamTemplate `json:"paramTemplates"` +} +type ParamTemplate struct { + Uuid string `json:"uuid"` + Name string `json:"name"` + Type string `json:"type"` + Version string `json:"version"` + Description string `json:"description"` + IsReboot bool `json:"isReboot"` + ParamAmount int `json:"paramAmount"` + Status string `json:"status"` + IsSystem bool `json:"isSystem"` + UserId string `json:"userId,omitempty"` + UserName string `json:"userName,omitempty"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type ParamTempArgs struct { + Type string `json:"type"` + Version string `json:"version"` + Description string `json:"description"` + Name string `json:"name"` + Source string `json:"source"` +} + +type GetTemplateApplyRecordsResult struct { + Records []ApplyRecord `json:"records"` +} +type ApplyRecord struct { + Status string `json:"status"` + FinishTime string `json:"finishTime"` + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + ClusterStatus string `json:"clusterStatus"` + ClusterRegion string `json:"clusterRegion"` + StartTime string `json:"startTime"` + ErrMsg string `json:"errMsg"` +} +type Params struct { + Params []string `json:"params"` +} + +type UpdateParamTplArgs struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type ModifyParamsArgs struct { + Params ParamsItem `json:"params"` +} + +type CreateParamTemplateArgs struct { + Name string `json:"name"` + Type string `json:"type"` + Version string `json:"version"` + Description string `json:"description"` +} +type ParamTemplateDetail struct { + ParamTemplate ParamTemplate `json:"paramTemplate"` +} +type ParamTemplateHistory struct { + Records []ParamTemplateRecord `json:"records"` +} +type ParamTemplateRecord struct { + Action string `json:"action"` + Name string `json:"name"` + ParamTemplateId string `json:"paramTemplateId"` + RequestId string `json:"requestId"` + Id int64 `json:"id"` + ErrMsg string `json:"errMsg"` + AfterValue string `json:"afterValue"` + StartTime string `json:"startTime"` + FinishTime string `json:"finishTime"` +} + +type ApplyParamTemplateArgs struct { + Timing string `json:"timing"` + Clusters ParamsItem `json:"clusters"` +} + +type UpdateMaintenTimeArgs struct { + Period string `json:"period"` + StartTime string `json:"startTime"` + Duration int `json:"duration"` +} + +type MaintenTimeDetail struct { + MaintenTime MaintenTime `json:"maintenTime"` +} +type MaintenTime struct { + ClusterId string `json:"clusterId"` + Period string `json:"period"` + StartTime string `json:"startTime"` + Duration int `json:"duration"` +} + +type GetSlowSqlArgs struct { + Page string `json:"page,omitempty"` + PageSize string `json:"pageSize,omitempty"` + Offset string `json:"offset,omitempty"` + Sort string `json:"sort,omitempty"` + NodeId string `json:"nodeId,omitempty"` + Engine string `json:"engine,omitempty"` + Schema string `json:"schema,omitempty"` + Digest string `json:"digest,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +type SlowSqlDetailDetail struct { + Items []SlowSqlDetailItem `json:"items"` + TotalCount int64 `json:"totalCount"` +} +type SlowSqlDetailItem struct { + AffectedRows int64 `json:"affectedRows"` + App string `json:"app"` + ClientHost string `json:"clientHost"` + ClientIP string `json:"clientIP"` + Cluster string `json:"cluster"` + ConnectionId int `json:"connectionId"` + CurrentDB string `json:"currentDB"` + Digest string `json:"digest"` + Duration string `json:"duration"` + ExaminedRows int64 `json:"examinedRows"` + LockTime string `json:"lockTime"` + Node string `json:"node"` + NumRows int64 `json:"numRows"` + SqlId string `json:"sqlId"` + Start string `json:"start"` + User string `json:"user"` +} + +type SlowSqlAdviceDetail struct { + IndexAdvice []SlowSqlAdvice `json:"indexAdvice"` + StatementAdvice []SlowSqlAdvice `json:"statementAdvice"` +} +type SlowSqlAdvice struct { + Advice string `json:"advice"` + Title string `json:"title"` +} + +type GetBinlogArgs struct { + AppID string `json:"appID"` + LogBackupType string `json:"logBackupType"` +} +type BinlogDetail struct { + Name string `json:"name"` + LogStartDateTime string `json:"logStartDateTime"` + LogEndDateTime string `json:"logEndDateTime"` + LogSizeBytes int64 `json:"logSizeBytes"` + OuterLinks []string `json:"outerLinks"` +} +type BinlogList struct { + LogBackups []BinlogItem `json:"logBackups"` + Pagination Pagination `json:"pagination"` +} +type BinlogItem struct { + Id string `json:"id"` + Name string `json:"name"` + LogStartDateTime string `json:"logStartDateTime"` + LogEndDateTime string `json:"logEndDateTime"` + LogSizeBytes int64 `json:"logSizeBytes"` +} +type Pagination struct { + TotalKeys int64 `json:"totalKeys"` +} + +type GetBinlogListArgs struct { + AppID string `json:"appID"` + LogBackupType string `json:"logBackupType"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + StartDateTime string `json:"startDateTime"` + EndDateTime string `json:"endDateTime"` +} + +type TaskListArgs struct { + Region string `json:"region,omitempty"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime,omitempty"` +} +type TaskList struct { + Task []TaskItem `json:"task"` +} +type TaskItem struct { + TaskId int64 `json:"taskId"` + Region string `json:"region"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + TaskName string `json:"taskName"` + ClusterId string `json:"clusterId"` + ClusterName string `json:"clusterName"` + TaskStatus string `json:"taskStatus"` + SupportedOperate []string `json:"supportedOperate"` +} + +type ClusterList struct { + Clusters []ClusterItem `json:"clusters"` +} +type ClusterItem struct { + ClusterId string `json:"clusterId"` + Name string `json:"name"` + LbInfos []LbInfos `json:"lbInfos"` +} +type LbInfos struct { + LbId string `json:"lbId"` + LbIp string `json:"lbIp"` + Eip string `json:"eip"` +} +type OrderInfo struct { + Status string `json:"status"` +} diff --git a/bce-sdk-go/services/gaiadb/util.go b/bce-sdk-go/services/gaiadb/util.go new file mode 100644 index 0000000..091db2a --- /dev/null +++ b/bce-sdk-go/services/gaiadb/util.go @@ -0,0 +1,36 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of GAIADB service +package gaiadb + +import ( + "encoding/hex" + "fmt" + + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} diff --git a/bce-sdk-go/services/havip/client.go b/bce-sdk-go/services/havip/client.go new file mode 100644 index 0000000..b6a2486 --- /dev/null +++ b/bce-sdk-go/services/havip/client.go @@ -0,0 +1,49 @@ +/* + * Copyright Baidu, Inc. + * + * 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 havip + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_HAVIP = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_HAVIP_URL = "/havip" +) + +// Client of ESG service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_HAVIP + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForHaVip() string { + return URI_PREFIX + REQUEST_HAVIP_URL +} + +func getURLForHaVipId(haVipId string) string { + return getURLForHaVip() + "/" + haVipId +} diff --git a/bce-sdk-go/services/havip/client_test.go b/bce-sdk-go/services/havip/client_test.go new file mode 100644 index 0000000..bd4e79e --- /dev/null +++ b/bce-sdk-go/services/havip/client_test.go @@ -0,0 +1,186 @@ +/* + * Copyright Baidu, Inc. + * + * 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 havip + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + HAVIP_CLIENT *Client + region string +) + +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + //for i := 0; i < 7; i++ { + // f = filepath.Dir(f) + //} + f = filepath.Dir(f) + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + _ = decoder.Decode(confObj) + HAVIP_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + + region = confObj.Endpoint[4:6] +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateHaVip(t *testing.T) { + args := &CreateHaVipArgs{ + Name: "havipGoSdkTest", + Description: "go sdk test", + SubnetId: "sbn-mnnhbyd2tbqr", + PrivateIpAddress: "192.168.1.3", + ClientToken: getClientToken(), + } + result, err := HAVIP_CLIENT.CreateHaVip(args) + ExpectEqual(t.Errorf, nil, err) + HaVipId := result.HaVipId + log.Debug(HaVipId) +} + +func TestClient_ListHaVips(t *testing.T) { + args := &ListHaVipArgs{} + res, err := HAVIP_CLIENT.ListHaVip(args) + fmt.Println(res) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) +} + +func TestClient_GetHaVipDetail(t *testing.T) { + result, err := HAVIP_CLIENT.GetHaVipDetail("havip-ied0wq4fs8va") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_UpdateHaVip(t *testing.T) { + args := &UpdateHaVipArgs{ + HaVipId: "havip-yxz7bx3tskqs", + ClientToken: getClientToken(), + Name: "havipGoSdkTest2", + } + err := HAVIP_CLIENT.UpdateHaVip(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteHaVip(t *testing.T) { + args := &DeleteHaVipArgs{ + HaVipId: "havip-qzctfgy0uadj", + ClientToken: getClientToken(), + } + err := HAVIP_CLIENT.DeleteHaVip(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_HaVipAttachInstance(t *testing.T) { + args := &HaVipInstanceArgs{ + HaVipId: "havip-yxz7bx3tskqs", + ClientToken: getClientToken(), + InstanceIds: []string{ + "eni-xgg3pfhw384n", + }, + InstanceType: "ENI", + } + err := HAVIP_CLIENT.HaVipAttachInstance(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_HaVipDetachInstance(t *testing.T) { + args := &HaVipInstanceArgs{ + HaVipId: "havip-yxz7bx3tskqs", + ClientToken: getClientToken(), + InstanceIds: []string{ + "eni-xgg3pfhw384n", + }, + InstanceType: "ENI", + } + err := HAVIP_CLIENT.HaVipDetachInstance(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_HaVipBindPublicIp(t *testing.T) { + args := &HaVipBindPublicIpArgs{ + HaVipId: "havip-ied0wq4fs8va", + ClientToken: getClientToken(), + PublicIpAddress: "110.242.73.217", + } + err := HAVIP_CLIENT.HaVipBindPublicIp(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_HaVipUnbindPublicIp(t *testing.T) { + args := &HaVipUnbindPublicIpArgs{ + HaVipId: "havip-ied0wq4fs8va", + ClientToken: getClientToken(), + } + err := HAVIP_CLIENT.HaVipUnbindPublicIp(args) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/havip/havip.go b/bce-sdk-go/services/havip/havip.go new file mode 100644 index 0000000..b98d319 --- /dev/null +++ b/bce-sdk-go/services/havip/havip.go @@ -0,0 +1,226 @@ +/* + * Copyright Baidu, Inc. + * + * 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 havip + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +// CreateHaVip - create an havip with the specific parameters +// +// PARAMS: +// - args: the arguments to create an havip +// +// RETURNS: +// - *CreateHavipResult: the result of create havip +// - error: nil if success otherwise the specific error +func (c *Client) CreateHaVip(args *CreateHaVipArgs) (*CreateHavipResult, error) { + if args == nil { + return nil, fmt.Errorf("The createHaVipArgs cannot be nil.") + } + + result := &CreateHavipResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForHaVip()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListHaVip - list all havip with the specific parameters +// +// PARAMS: +// - args: the arguments to list all havip +// +// RETURNS: +// - *ListHaVipResult: the result of list all havip +// - error: nil if success otherwise the specific error +func (c *Client) ListHaVip(args *ListHaVipArgs) (*ListHaVipResult, error) { + if args == nil { + return nil, fmt.Errorf("The listHaVipArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListHaVipResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForHaVip()). + WithMethod(http.GET). + WithQueryParamFilter("vpcId", args.VpcId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)) + + err := builder.WithResult(result).Do() + + return result, err +} + +// GetHaVipDetail - get the havip detail +// +// PARAMS: +// - haVipId: the specific haVipId +// +// RETURNS: +// - *HaVip: the havip +// - error: nil if success otherwise the specific error +func (c *Client) GetHaVipDetail(haVipId string) (*HaVip, error) { + if haVipId == "" { + return nil, fmt.Errorf("The haVipId cannot be empty.") + } + + result := &HaVip{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(haVipId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// UpdateHaVip - update an havip +// +// PARAMS: +// - UpdateHaVipArgs: the arguments to update an havip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateHaVip(args *UpdateHaVipArgs) error { + if args == nil { + return fmt.Errorf("The updateHaVipArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(args.HaVipId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("modifyAttribute", ""). + Do() +} + +// DeleteHaVip - delete an havip +// +// PARAMS: +// - DeleteHaVipArgs: the arguments to delete an havip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteHaVip(args *DeleteHaVipArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(args.HaVipId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// HaVipAttachInstance - havip attach instance +// +// PARAMS: +// - args: the arguments to attach instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) HaVipAttachInstance(args *HaVipInstanceArgs) error { + if args == nil { + return fmt.Errorf("The haVipInstanceArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(args.HaVipId)). + WithMethod(http.PUT). + WithQueryParam("attach", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// HaVipDetachInstance - havip detach instance +// +// PARAMS: +// - args: the arguments to detach instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) HaVipDetachInstance(args *HaVipInstanceArgs) error { + if args == nil { + return fmt.Errorf("The haVipInstanceArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(args.HaVipId)). + WithMethod(http.PUT). + WithQueryParam("detach", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// HaVipBindPublicIp - havip bind public ip +// +// PARAMS: +// - args: the arguments to bind public ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) HaVipBindPublicIp(args *HaVipBindPublicIpArgs) error { + if args == nil { + return fmt.Errorf("The haVipBindPublicIpArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(args.HaVipId)). + WithMethod(http.PUT). + WithQueryParam("bindPublicIp", ""). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} + +// HaVipUnbindPublicIp - havip unbind public ip +// +// PARAMS: +// - args: the arguments to unbind public ip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) HaVipUnbindPublicIp(args *HaVipUnbindPublicIpArgs) error { + if args == nil { + return fmt.Errorf("The HaVipUnbindPublicIpArgs cannot be nil.") + } + + err := bce.NewRequestBuilder(c). + WithURL(getURLForHaVipId(args.HaVipId)). + WithMethod(http.PUT). + WithQueryParam("unbindPublicIp", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() + + return err +} diff --git a/bce-sdk-go/services/havip/model.go b/bce-sdk-go/services/havip/model.go new file mode 100644 index 0000000..6258ec1 --- /dev/null +++ b/bce-sdk-go/services/havip/model.go @@ -0,0 +1,90 @@ +/* + * Copyright Baidu, Inc. + * + * 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 havip + +type CreateHaVipArgs struct { + ClientToken string `json:"-"` + SubnetId string `json:"subnetId"` + Name string `json:"name"` + PrivateIpAddress string `json:"privateIpAddress"` + Description string `json:"description"` +} + +type CreateHavipResult struct { + HaVipId string `json:"haVipId"` +} + +type HaVipBindedInstance struct { + InstanceId string `json:"instanceId"` + InstanceType string `json:"instanceType"` + Master bool `json:"master"` +} + +type HaVip struct { + HaVipId string `json:"haVipId"` + Name string `json:"name"` + Description string `json:"description"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Status string `json:"status"` + PrivateIpAddress string `json:"privateIpAddress"` + PublicIpAddress string `json:"publicIpAddress,omitempty"` + BindedInstances []HaVipBindedInstance `json:"bindedInstances,omitempty"` + CreatedTime string `json:"createdTime"` +} + +type ListHaVipArgs struct { + VpcId string + Marker string + MaxKeys int +} + +type ListHaVipResult struct { + HaVips []HaVip `json:"haVips"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type UpdateHaVipArgs struct { + HaVipId string `json:"-"` + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description,omitempty"` +} + +type DeleteHaVipArgs struct { + HaVipId string + ClientToken string +} + +type HaVipInstanceArgs struct { + HaVipId string `json:"-"` + InstanceIds []string `json:"instanceIds"` + InstanceType string `json:"instanceType"` + ClientToken string `json:"-"` +} + +type HaVipBindPublicIpArgs struct { + HaVipId string `json:"-"` + ClientToken string `json:"-"` + PublicIpAddress string `json:"publicIpAddress"` +} + +type HaVipUnbindPublicIpArgs struct { + HaVipId string + ClientToken string +} diff --git a/bce-sdk-go/services/iam/api/accesskey.go b/bce-sdk-go/services/iam/api/accesskey.go new file mode 100644 index 0000000..0dd6134 --- /dev/null +++ b/bce-sdk-go/services/iam/api/accesskey.go @@ -0,0 +1,130 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateAccessKey(cli bce.Client, userName string) (*CreateAccessKeyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getAccessKeyUri(userName)) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateAccessKeyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DisableAccessKey(cli bce.Client, userName, accessKeyId string) (*UpdateAccessKeyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getAccessKeyWithIdUri(userName, accessKeyId)) + req.SetParam(ACCESSKEY_STATUS_DISABLE, "") + req.SetMethod(http.PUT) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &UpdateAccessKeyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func EnableAccessKey(cli bce.Client, userName, accessKeyId string) (*UpdateAccessKeyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getAccessKeyWithIdUri(userName, accessKeyId)) + req.SetParam(ACCESSKEY_STATUS_ENABLE, "") + req.SetMethod(http.PUT) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &UpdateAccessKeyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DeleteAccessKey(cli bce.Client, userName, accessKeyId string) error { + req := &bce.BceRequest{} + req.SetUri(getAccessKeyWithIdUri(userName, accessKeyId)) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListAccessKey(cli bce.Client, userName string) (*ListAccessKeyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getAccessKeyUri(userName)) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListAccessKeyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func getAccessKeyUri(userName string) string { + return URI_PREFIX + URI_USER + "/" + userName + URI_ACCESSKEY +} + +func getAccessKeyWithIdUri(userName, accessKeyId string) string { + return getAccessKeyUri(userName) + "/" + accessKeyId +} diff --git a/bce-sdk-go/services/iam/api/constants.go b/bce-sdk-go/services/iam/api/constants.go new file mode 100644 index 0000000..adbe01c --- /dev/null +++ b/bce-sdk-go/services/iam/api/constants.go @@ -0,0 +1,32 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +const ( + URI_PREFIX = "/v1" + URI_USER = "/user" + URI_GROUP = "/group" + URI_POLICY = "/policy" + URI_ACCESSKEY = "/accesskey" + URI_ROLE = "/role" + + SUB_USER = "/subUser" + + POLICY_TYPE_SYSTEM = "System" + POLICY_TYPE_CUSTOM = "Custom" + + ACCESSKEY_STATUS_ENABLE = "enable" + ACCESSKEY_STATUS_DISABLE = "disable" +) diff --git a/bce-sdk-go/services/iam/api/group.go b/bce-sdk-go/services/iam/api/group.go new file mode 100644 index 0000000..d55061e --- /dev/null +++ b/bce-sdk-go/services/iam/api/group.go @@ -0,0 +1,196 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateGroup(cli bce.Client, body *bce.Body) (*CreateGroupResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_GROUP) + req.SetMethod(http.POST) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &CreateGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func GetGroup(cli bce.Client, name string) (*GetGroupResult, error) { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(name)) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func UpdateGroup(cli bce.Client, name string, body *bce.Body) (*UpdateGroupResult, error) { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(name)) + req.SetMethod(http.PUT) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &UpdateGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DeleteGroup(cli bce.Client, name string) error { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(name)) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListGroup(cli bce.Client) (*ListGroupResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_GROUP) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func AddUserToGroup(cli bce.Client, userName string, groupName string) error { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_GROUP + "/" + groupName + URI_USER + "/" + userName) + req.SetMethod(http.PUT) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func DeleteUserFromGroup(cli bce.Client, userName string, groupName string) error { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_GROUP + "/" + groupName + URI_USER + "/" + userName) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListUsersInGroup(cli bce.Client, name string) (*ListUsersInGroupResult, error) { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(name) + URI_USER) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListUsersInGroupResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func ListGroupsForUser(cli bce.Client, name string) (*ListGroupsForUserResult, error) { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name) + URI_GROUP) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListGroupsForUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func getGroupUri(name string) string { + return URI_PREFIX + URI_GROUP + "/" + name +} diff --git a/bce-sdk-go/services/iam/api/model.go b/bce-sdk-go/services/iam/api/model.go new file mode 100644 index 0000000..2343e15 --- /dev/null +++ b/bce-sdk-go/services/iam/api/model.go @@ -0,0 +1,227 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +import "time" + +type UserModel struct { + Id string `json:"id"` + Name string `json:"name"` + CreateTime time.Time `json:"createTime"` + Description string `json:"description"` + Enabled bool `json:"enabled"` +} + +type CreateUserArgs struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type CreateUserResult UserModel + +type GetUserResult UserModel + +type UpdateUserArgs struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` +} + +type UpdateUserResult UserModel + +type ListUserResult struct { + Users []UserModel `json:"users"` +} + +type AccessKeyModel struct { + Id string `json:"id"` + Secret string `json:"secret"` + CreateTime time.Time `json:"createTime"` + LastUsedTime time.Time `json:"lastUsedTime"` + Enabled bool `json:"enabled"` + Description string `json:"description"` +} + +type CreateAccessKeyResult AccessKeyModel + +type UpdateAccessKeyResult AccessKeyModel + +type ListAccessKeyResult struct { + AccessKeys []AccessKeyModel `json:"accessKeys"` +} + +type LoginProfileModel struct { + Password string `json:"password,omitempty"` + NeedResetPassword bool `json:"needResetPassword"` + EnabledLoginMfa bool `json:"enabledLoginMfa"` + LoginMfaType string `json:"loginMfaType,omitempty"` + ThirdPartyType bool `json:"thirdPartyType,omitempty"` + ThirdPartyAccount bool `json:"thirdPartyAccount,omitempty"` +} + +type UpdateUserLoginProfileArgs LoginProfileModel + +type UpdateUserLoginProfileResult LoginProfileModel + +type GetUserLoginProfileResult LoginProfileModel + +type GroupModel struct { + Id string `json:"id"` + Name string `json:"name"` + CreateTime time.Time `json:"createTime"` + Description string `json:"description"` +} + +type CreateGroupArgs struct { + Name string `json:"name"` + Description string `json:"description"` +} + +type CreateGroupResult GroupModel + +type GetGroupResult GroupModel + +type UpdateGroupArgs struct { + Name string `json:"name,omitempty"` + Description string `json:"description,omitempty"` +} + +type UpdateGroupResult GroupModel + +type ListGroupResult struct { + Groups []GroupModel `json:"groups"` +} + +type ListUsersInGroupResult ListUserResult + +type ListGroupsForUserResult ListGroupResult + +type AclEntry struct { + Eid string `json:"eid,omitempty"` + Service string `json:"service"` + Region string `json:"region"` + Permission []string `json:"permission"` + Resource []string `json:"resource,omitempty"` + Grantee []Grantee `json:"grantee,omitempty"` + Effect string `json:"effect"` +} + +type Grantee struct { + ID string `json:"id"` +} + +type Acl struct { + Id string `json:"id,omitempty"` + AccessControlList []AclEntry `json:"accessControlList"` +} + +type PolicyModel struct { + Id string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + CreateTime time.Time `json:"createTime"` + Description string `json:"description"` + Document string `json:"document"` +} + +type CreatePolicyArgs struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + Document string `json:"document"` +} + +type CreatePolicyResult PolicyModel + +type GetPolicyResult PolicyModel + +type ListPolicyResult struct { + Policies []PolicyModel `json:"policies"` +} + +type AttachPolicyToUserArgs struct { + UserName string `json:"userName"` + PolicyName string `json:"policyName"` + PolicyType string `json:"policyType,omitempty"` +} + +type DetachPolicyFromUserArgs struct { + UserName string `json:"userName"` + PolicyName string `json:"policyName"` + PolicyType string `json:"policyType,omitempty"` +} + +type AttachPolicyToGroupArgs struct { + GroupName string `json:"groupName"` + PolicyName string `json:"policyName"` + PolicyType string `json:"policyType,omitempty"` +} + +type DetachPolicyFromGroupArgs struct { + GroupName string `json:"groupName"` + PolicyName string `json:"policyName"` + PolicyType string `json:"policyType,omitempty"` +} + +type AttachPolicyToRoleArgs struct { + RoleName string `json:"roleName"` + PolicyName string `json:"policyName"` + PolicyType string `json:"policyType,omitempty"` +} + +type DetachPolicyToRoleArgs struct { + RoleName string `json:"roleName"` + PolicyName string `json:"policyName"` + PolicyType string `json:"policyType,omitempty"` +} + +type RoleModel struct { + Id string `json:"id"` + Name string `json:"name"` + CreateTime time.Time `json:"createTime"` + Description string `json:"description"` + AssumeRolePolicyDocument string `json:"assumeRolePolicyDocument"` +} + +type CreateRoleArgs struct { + Name string `json:"name"` + Description string `json:"description,omitempty"` + AssumeRolePolicyDocument string `json:"assumeRolePolicyDocument"` +} + +type UpdateRoleArgs struct { + Description string `json:"description"` + AssumeRolePolicyDocument string `json:"assumeRolePolicyDocument,omitempty"` +} + +type CreateRoleResult RoleModel + +type GetRoleResult RoleModel + +type UpdateRoleResult RoleModel + +type ListRoleResult struct { + Roles []RoleModel `json:"roles"` +} + +type UserSwitchMfaArgs struct { + UserName string `json:"userName,omitempty"` + EnabledMfa bool `json:"enabledMfa"` + MfaType string `json:"mfaType,omitempty"` +} + +type UpdateSubUserArgs struct { + Password string `json:"password,omitempty"` + Provider string `json:"provider,omitempty"` + Enable bool `json:"enable"` +} diff --git a/bce-sdk-go/services/iam/api/policy.go b/bce-sdk-go/services/iam/api/policy.go new file mode 100644 index 0000000..8a7f4ec --- /dev/null +++ b/bce-sdk-go/services/iam/api/policy.go @@ -0,0 +1,285 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreatePolicy(cli bce.Client, body *bce.Body) (*CreatePolicyResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_POLICY) + req.SetMethod(http.POST) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &CreatePolicyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func GetPolicy(cli bce.Client, name, policyType string) (*GetPolicyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getPolicyUri(name)) + if policyType != "" { + req.SetParam("policyType", policyType) + } + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetPolicyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DeletePolicy(cli bce.Client, name string) error { + req := &bce.BceRequest{} + req.SetUri(getPolicyUri(name)) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListPolicy(cli bce.Client, nameFilter, policyType string) (*ListPolicyResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_POLICY) + if nameFilter != "" { + req.SetParam("nameFilter", nameFilter) + } + if policyType != "" { + req.SetParam("policyType", policyType) + } + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPolicyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func AttachPolicyToUser(cli bce.Client, args *AttachPolicyToUserArgs) error { + req := &bce.BceRequest{} + req.SetUri(getUserUri(args.UserName) + URI_POLICY + "/" + args.PolicyName) + if args.PolicyType != "" { + req.SetParam("policyType", args.PolicyType) + } + req.SetMethod(http.PUT) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func DetachPolicyFromUser(cli bce.Client, args *DetachPolicyFromUserArgs) error { + req := &bce.BceRequest{} + req.SetUri(getUserUri(args.UserName) + URI_POLICY + "/" + args.PolicyName) + if args.PolicyType != "" { + req.SetParam("policyType", args.PolicyType) + } + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListUserAttachedPolicies(cli bce.Client, name string) (*ListPolicyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name) + URI_POLICY) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPolicyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func AttachPolicyToGroup(cli bce.Client, args *AttachPolicyToGroupArgs) error { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(args.GroupName) + URI_POLICY + "/" + args.PolicyName) + if args.PolicyType != "" { + req.SetParam("policyType", args.PolicyType) + } + req.SetMethod(http.PUT) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func DetachPolicyFromGroup(cli bce.Client, args *DetachPolicyFromGroupArgs) error { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(args.GroupName) + URI_POLICY + "/" + args.PolicyName) + if args.PolicyType != "" { + req.SetParam("policyType", args.PolicyType) + } + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListGroupAttachedPolicies(cli bce.Client, name string) (*ListPolicyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getGroupUri(name) + URI_POLICY) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPolicyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func AttachPolicyToRole(cli bce.Client, args *AttachPolicyToRoleArgs) error { + req := &bce.BceRequest{} + req.SetUri(getRoleUri(args.RoleName) + URI_POLICY + "/" + args.PolicyName) + req.SetMethod(http.PUT) + if args.PolicyType != "" { + req.SetParam("policyType", args.PolicyType) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func DetachPolicyFromRole(cli bce.Client, args *DetachPolicyToRoleArgs) error { + req := &bce.BceRequest{} + req.SetUri(getRoleUri(args.RoleName) + URI_POLICY + "/" + args.PolicyName) + req.SetMethod(http.DELETE) + if args.PolicyType != "" { + req.SetParam("policyType", args.PolicyType) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListRoleAttachedPolicies(cli bce.Client, roleName string) (*ListPolicyResult, error) { + req := &bce.BceRequest{} + req.SetUri(getRoleUri(roleName) + URI_POLICY) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPolicyResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func getPolicyUri(name string) string { + return URI_PREFIX + URI_POLICY + "/" + name +} diff --git a/bce-sdk-go/services/iam/api/role.go b/bce-sdk-go/services/iam/api/role.go new file mode 100644 index 0000000..db4372c --- /dev/null +++ b/bce-sdk-go/services/iam/api/role.go @@ -0,0 +1,125 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateRole(cli bce.Client, body *bce.Body) (*CreateRoleResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_ROLE) + req.SetMethod(http.POST) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + jsonBody := &CreateRoleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func GetRole(cli bce.Client, roleName string) (*GetRoleResult, error) { + req := &bce.BceRequest{} + req.SetUri(getRoleUri(roleName)) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetRoleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func UpdateRole(cli bce.Client, roleName string, body *bce.Body) (*UpdateRoleResult, error) { + req := &bce.BceRequest{} + req.SetUri(getRoleUri(roleName)) + req.SetMethod(http.PUT) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &UpdateRoleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DeleteRole(cli bce.Client, roleName string) error { + req := &bce.BceRequest{} + req.SetUri(getRoleUri(roleName)) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func ListRole(cli bce.Client) (*ListRoleResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_ROLE) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListRoleResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func getRoleUri(roleName string) string { + return URI_PREFIX + URI_ROLE + "/" + roleName +} diff --git a/bce-sdk-go/services/iam/api/user.go b/bce-sdk-go/services/iam/api/user.go new file mode 100644 index 0000000..b87c785 --- /dev/null +++ b/bce-sdk-go/services/iam/api/user.go @@ -0,0 +1,225 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateUser(cli bce.Client, body *bce.Body) (*CreateUserResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_USER) + req.SetMethod(http.POST) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &CreateUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func GetUser(cli bce.Client, name string) (*GetUserResult, error) { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name)) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DeleteUser(cli bce.Client, name string) error { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name)) + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func UpdateUser(cli bce.Client, name string, body *bce.Body) (*UpdateUserResult, error) { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name)) + req.SetMethod(http.PUT) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &UpdateUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func ListUser(cli bce.Client) (*ListUserResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_USER) + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func UpdateUserLoginProfile(cli bce.Client, name string, body *bce.Body) (*UpdateUserLoginProfileResult, error) { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name) + "/loginProfile") + req.SetMethod(http.PUT) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &UpdateUserLoginProfileResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func GetUserLoginProfile(cli bce.Client, name string) (*GetUserLoginProfileResult, error) { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name) + "/loginProfile") + req.SetMethod(http.GET) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetUserLoginProfileResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func DeleteUserLoginProfile(cli bce.Client, name string) error { + req := &bce.BceRequest{} + req.SetUri(getUserUri(name) + "/loginProfile") + req.SetMethod(http.DELETE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func UserOperationMfaSwitch(cli bce.Client, body *bce.Body) error { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + URI_USER + "/operation/mfa/switch") + req.SetMethod(http.POST) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func SubUserUpdate(cli bce.Client, body *bce.Body, name string) (*UpdateUserResult, error) { + req := &bce.BceRequest{} + req.SetUri(getSubUserUri(name) + "/update") + req.SetMethod(http.PUT) + req.SetBody(body) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &UpdateUserResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return jsonBody, nil +} + +func getUserUri(name string) string { + return URI_PREFIX + URI_USER + "/" + name +} + +func getSubUserUri(name string) string { + return URI_PREFIX + SUB_USER + "/" + name +} diff --git a/bce-sdk-go/services/iam/client.go b/bce-sdk-go/services/iam/client.go new file mode 100644 index 0000000..40cb280 --- /dev/null +++ b/bce-sdk-go/services/iam/client.go @@ -0,0 +1,283 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for IAM service which is derived from BceClient + +// Package iam defines the IAM service of BCE. +// It contains the model sub package to implement the concrete request and response of the +// IAM user/accessKey/policy API +package iam + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/iam/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "iam." + bce.DEFAULT_REGION + ".baidubce.com" +) + +// Client of IAM service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk string) (*Client, error) { + return NewClientWithEndpoint(ak, sk, DEFAULT_SERVICE_DOMAIN) +} + +func NewClientWithEndpoint(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +func (c *Client) CreateUser(args *api.CreateUserArgs) (*api.CreateUserResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.CreateUser(c, body) +} + +func (c *Client) GetUser(name string) (*api.GetUserResult, error) { + return api.GetUser(c, name) +} + +func (c *Client) UpdateUser(name string, args *api.UpdateUserArgs) (*api.UpdateUserResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.UpdateUser(c, name, body) +} + +func (c *Client) DeleteUser(name string) error { + return api.DeleteUser(c, name) +} + +func (c *Client) ListUser() (*api.ListUserResult, error) { + return api.ListUser(c) +} + +func (c *Client) UpdateUserLoginProfile(name string, args *api.UpdateUserLoginProfileArgs) ( + *api.UpdateUserLoginProfileResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.UpdateUserLoginProfile(c, name, body) +} + +func (c *Client) GetUserLoginProfile(name string) (*api.GetUserLoginProfileResult, error) { + return api.GetUserLoginProfile(c, name) +} + +func (c *Client) DeleteUserLoginProfile(name string) error { + return api.DeleteUserLoginProfile(c, name) +} + +func (c *Client) CreateGroup(args *api.CreateGroupArgs) (*api.CreateGroupResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.CreateGroup(c, body) +} + +func (c *Client) GetGroup(name string) (*api.GetGroupResult, error) { + return api.GetGroup(c, name) +} + +func (c *Client) UpdateGroup(name string, args *api.UpdateGroupArgs) (*api.UpdateGroupResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.UpdateGroup(c, name, body) +} + +func (c *Client) DeleteGroup(name string) error { + return api.DeleteGroup(c, name) +} + +func (c *Client) ListGroup() (*api.ListGroupResult, error) { + return api.ListGroup(c) +} + +func (c *Client) AddUserToGroup(userName string, groupName string) error { + return api.AddUserToGroup(c, userName, groupName) +} + +func (c *Client) DeleteUserFromGroup(userName string, groupName string) error { + return api.DeleteUserFromGroup(c, userName, groupName) +} + +func (c *Client) ListUsersInGroup(name string) (*api.ListUsersInGroupResult, error) { + return api.ListUsersInGroup(c, name) +} + +func (c *Client) ListGroupsForUser(name string) (*api.ListGroupsForUserResult, error) { + return api.ListGroupsForUser(c, name) +} + +func (c *Client) CreatePolicy(args *api.CreatePolicyArgs) (*api.CreatePolicyResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.CreatePolicy(c, body) +} + +func (c *Client) GetPolicy(name, policyType string) (*api.GetPolicyResult, error) { + return api.GetPolicy(c, name, policyType) +} + +func (c *Client) DeletePolicy(name string) error { + return api.DeletePolicy(c, name) +} + +func (c *Client) ListPolicy(nameFilter, policyType string) (*api.ListPolicyResult, error) { + return api.ListPolicy(c, nameFilter, policyType) +} + +func (c *Client) AttachPolicyToUser(args *api.AttachPolicyToUserArgs) error { + return api.AttachPolicyToUser(c, args) +} + +func (c *Client) DetachPolicyFromUser(args *api.DetachPolicyFromUserArgs) error { + return api.DetachPolicyFromUser(c, args) +} + +func (c *Client) ListUserAttachedPolicies(name string) (*api.ListPolicyResult, error) { + return api.ListUserAttachedPolicies(c, name) +} + +func (c *Client) AttachPolicyToGroup(args *api.AttachPolicyToGroupArgs) error { + return api.AttachPolicyToGroup(c, args) +} + +func (c *Client) DetachPolicyFromGroup(args *api.DetachPolicyFromGroupArgs) error { + return api.DetachPolicyFromGroup(c, args) +} + +func (c *Client) ListGroupAttachedPolicies(name string) (*api.ListPolicyResult, error) { + return api.ListGroupAttachedPolicies(c, name) +} + +func (c *Client) CreateAccessKey(userName string) (*api.CreateAccessKeyResult, error) { + return api.CreateAccessKey(c, userName) +} + +func (c *Client) DisableAccessKey(userName, accessKeyId string) (*api.UpdateAccessKeyResult, error) { + return api.DisableAccessKey(c, userName, accessKeyId) +} + +func (c *Client) EnableAccessKey(userName, accessKeyId string) (*api.UpdateAccessKeyResult, error) { + return api.EnableAccessKey(c, userName, accessKeyId) +} + +func (c *Client) DeleteAccessKey(userName, accessKeyId string) error { + return api.DeleteAccessKey(c, userName, accessKeyId) +} + +func (c *Client) ListAccessKey(userName string) (*api.ListAccessKeyResult, error) { + return api.ListAccessKey(c, userName) +} + +func (c *Client) CreateRole(args *api.CreateRoleArgs) (*api.CreateRoleResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.CreateRole(c, body) +} + +func (c *Client) GetRole(roleName string) (*api.GetRoleResult, error) { + return api.GetRole(c, roleName) +} + +func (c *Client) UpdateRole(roleName string, args *api.UpdateRoleArgs) (*api.UpdateRoleResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.UpdateRole(c, roleName, body) +} + +func (c *Client) DeleteRole(roleName string) error { + return api.DeleteRole(c, roleName) +} + +func (c *Client) ListRole() (*api.ListRoleResult, error) { + return api.ListRole(c) +} + +func (c *Client) AttachPolicyToRole(args *api.AttachPolicyToRoleArgs) error { + return api.AttachPolicyToRole(c, args) +} + +func (c *Client) DetachPolicyFromRole(args *api.DetachPolicyToRoleArgs) error { + return api.DetachPolicyFromRole(c, args) +} + +func (c *Client) ListRoleAttachedPolicies(name string) (*api.ListPolicyResult, error) { + return api.ListRoleAttachedPolicies(c, name) +} + +func (c *Client) UserOperationMfaSwitch(args *api.UserSwitchMfaArgs) error { + body, err := NewBodyFromStruct(args) + if err != nil { + return err + } + return api.UserOperationMfaSwitch(c, body) +} + +func (c *Client) SubUserUpdate(userName string, args *api.UpdateSubUserArgs) (*api.UpdateUserResult, error) { + body, err := NewBodyFromStruct(args) + if err != nil { + return nil, err + } + return api.SubUserUpdate(c, body, userName) +} + +func NewBodyFromStruct(args interface{}) (*bce.Body, error) { + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + return body, nil +} diff --git a/bce-sdk-go/services/iam/client_test.go b/bce-sdk-go/services/iam/client_test.go new file mode 100644 index 0000000..27b6877 --- /dev/null +++ b/bce-sdk-go/services/iam/client_test.go @@ -0,0 +1,591 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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 iam + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/services/iam/api" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +var IAM_CLIENT *Client + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given: %+v\n", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + IAM_CLIENT, _ = NewClientWithEndpoint(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestCreateListUpdateDeleteUser(t *testing.T) { + name := "test-user-sdk-go" + args := &api.CreateUserArgs{ + Name: name, + Description: "description", + } + res, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(res) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, res.Name, args.Name) + ExpectEqual(t.Errorf, res.Description, args.Description) + + users, err := IAM_CLIENT.ListUser() + ExpectEqual(t.Errorf, err, nil) + if users == nil || len(users.Users) == 0 { + t.Errorf("list user return no result") + } + jsonRes, _ = json.Marshal(users) + t.Logf(string(jsonRes)) + + updateArgs := &api.UpdateUserArgs{ + Description: "updated description", + } + updated, err := IAM_CLIENT.UpdateUser(name, updateArgs) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ = json.Marshal(updated) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, updated.Name, name) + ExpectEqual(t.Errorf, updated.Description, updateArgs.Description) + + err = IAM_CLIENT.DeleteUser(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUpdateGetDeleteUserLoginProfile(t *testing.T) { + name := "test-user-sdk-go-login-profile" + args := &api.CreateUserArgs{ + Name: name, + } + _, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + + updateArgs := &api.UpdateUserLoginProfileArgs{ + Password: "1@3Qwe4f", + EnabledLoginMfa: true, + LoginMfaType: "PHONE", + } + updateRes, err := IAM_CLIENT.UpdateUserLoginProfile(name, updateArgs) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(updateRes) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, updateRes.EnabledLoginMfa, true) + ExpectEqual(t.Errorf, updateRes.LoginMfaType, "PHONE") + + getRes, err := IAM_CLIENT.GetUserLoginProfile(name) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ = json.Marshal(getRes) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, updateRes.EnabledLoginMfa, true) + ExpectEqual(t.Errorf, updateRes.LoginMfaType, "PHONE") + + err = IAM_CLIENT.DeleteUser(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateGroupUpdateGetListDeleteGroup(t *testing.T) { + name := "test_sdk_go_group" + args := &api.CreateUserArgs{ + Name: name, + } + _, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + + groupArgs := &api.CreateGroupArgs{ + Name: name, + Description: "description", + } + group, err := IAM_CLIENT.CreateGroup(groupArgs) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, name, group.Name) + ExpectEqual(t.Errorf, groupArgs.Description, group.Description) + + updateGroupArgs := &api.UpdateGroupArgs{ + Description: "updated group", + } + updated, err := IAM_CLIENT.UpdateGroup(name, updateGroupArgs) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, name, updated.Name) + ExpectEqual(t.Errorf, updateGroupArgs.Description, updated.Description) + + getRes, err := IAM_CLIENT.GetGroup(name) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, name, getRes.Name) + ExpectEqual(t.Errorf, updateGroupArgs.Description, getRes.Description) + + listRes, err := IAM_CLIENT.ListGroup() + ExpectEqual(t.Errorf, err, nil) + if listRes == nil || len(listRes.Groups) == 0 { + t.Errorf("list group return no result") + } + + err = IAM_CLIENT.DeleteUser(name) + ExpectEqual(t.Errorf, err, nil) + err = IAM_CLIENT.DeleteGroup(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAddDeleteUserFromGroup(t *testing.T) { + name := "test_sdk_go_group" + args := &api.CreateUserArgs{ + Name: name, + } + user, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + + groupArgs := &api.CreateGroupArgs{ + Name: name, + Description: "description", + } + group, err := IAM_CLIENT.CreateGroup(groupArgs) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.AddUserToGroup(name, name) + ExpectEqual(t.Errorf, err, nil) + + usersRes, err := IAM_CLIENT.ListUsersInGroup(name) + ExpectEqual(t.Errorf, err, nil) + if usersRes == nil || len(usersRes.Users) != 1 { + t.Errorf("list group result not 1") + } + ExpectEqual(t.Errorf, 1, len(usersRes.Users)) + ExpectEqual(t.Errorf, user.Id, usersRes.Users[0].Id) + ExpectEqual(t.Errorf, user.Name, usersRes.Users[0].Name) + + groupsRes, err := IAM_CLIENT.ListGroupsForUser(name) + ExpectEqual(t.Errorf, err, nil) + if groupsRes == nil || len(groupsRes.Groups) != 1 { + t.Errorf("list user result not 1") + } + ExpectEqual(t.Errorf, 1, len(groupsRes.Groups)) + ExpectEqual(t.Errorf, group.Id, groupsRes.Groups[0].Id) + ExpectEqual(t.Errorf, group.Name, groupsRes.Groups[0].Name) + + err = IAM_CLIENT.DeleteUserFromGroup(name, name) + ExpectEqual(t.Errorf, err, nil) + + usersRes, err = IAM_CLIENT.ListUsersInGroup(name) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, 0, len(usersRes.Users)) + + groupsRes, err = IAM_CLIENT.ListGroupsForUser(name) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, 0, len(groupsRes.Groups)) + + err = IAM_CLIENT.DeleteUser(name) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeleteGroup(name) + ExpectEqual(t.Errorf, err, nil) +} + +func getPolicyDocument() string { + aclEntry := api.AclEntry{ + Service: "bos", + Region: "bj", + Permission: []string{"ListBucket"}, + Resource: []string{"*"}, + Effect: "Allow", + } + acl := &api.Acl{ + AccessControlList: []api.AclEntry{aclEntry}, + } + document, _ := json.Marshal(acl) + return string(document) +} + +func getAssumeRolePolicyDocument() string { + + grantee := api.Grantee{ + ID: "test-account-id", + } + + aclEntry := api.AclEntry{ + Service: "bce:iam", + Region: "*", + Permission: []string{"AssumeRole"}, + Grantee: []api.Grantee{grantee}, + Effect: "Allow", + } + acl := &api.Acl{ + AccessControlList: []api.AclEntry{aclEntry}, + } + document, _ := json.Marshal(acl) + return string(document) +} + +func TestCreateGetListDeletePolicy(t *testing.T) { + name := "test_sdk_go_policy" + args := &api.CreatePolicyArgs{ + Name: name, + Description: "description", + Document: getPolicyDocument(), + } + + res, err := IAM_CLIENT.CreatePolicy(args) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, name, res.Name) + ExpectEqual(t.Errorf, args.Description, res.Description) + + getRes, err := IAM_CLIENT.GetPolicy(name, "") + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, name, getRes.Name) + ExpectEqual(t.Errorf, args.Description, getRes.Description) + + listRes, err := IAM_CLIENT.ListPolicy(name, "") + ExpectEqual(t.Errorf, err, nil) + if listRes == nil || len(listRes.Policies) == 0 { + t.Errorf("list policy result is empty") + } + + err = IAM_CLIENT.DeletePolicy(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestUserAttachDetachPolicy(t *testing.T) { + userName := "test_sdk_go_policy" + args := &api.CreateUserArgs{ + Name: userName, + } + _, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + + policyName := "test_sdk_go_policy" + policyArgs := &api.CreatePolicyArgs{ + Name: policyName, + Description: "description", + Document: getPolicyDocument(), + } + + _, err = IAM_CLIENT.CreatePolicy(policyArgs) + ExpectEqual(t.Errorf, err, nil) + + attachArgs := &api.AttachPolicyToUserArgs{ + UserName: userName, + PolicyName: policyName, + } + err = IAM_CLIENT.AttachPolicyToUser(attachArgs) + ExpectEqual(t.Errorf, err, nil) + + policies, err := IAM_CLIENT.ListUserAttachedPolicies(userName) + ExpectEqual(t.Errorf, err, nil) + if policies == nil || len(policies.Policies) != 1 { + t.Errorf("list policy result is not 1") + } + policy := policies.Policies[0] + ExpectEqual(t.Errorf, policyName, policy.Name) + + detachArgs := &api.DetachPolicyFromUserArgs{ + UserName: userName, + PolicyName: policyName, + } + err = IAM_CLIENT.DetachPolicyFromUser(detachArgs) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeletePolicy(policyName) + ExpectEqual(t.Errorf, err, nil) + err = IAM_CLIENT.DeleteUser(userName) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGroupAttachDetachPolicy(t *testing.T) { + groupName := "test_sdk_go_policy" + args := &api.CreateGroupArgs{ + Name: groupName, + } + _, err := IAM_CLIENT.CreateGroup(args) + ExpectEqual(t.Errorf, err, nil) + + policyName := "test_sdk_go_policy" + policyArgs := &api.CreatePolicyArgs{ + Name: policyName, + Description: "description", + Document: getPolicyDocument(), + } + + _, err = IAM_CLIENT.CreatePolicy(policyArgs) + ExpectEqual(t.Errorf, err, nil) + + attachArgs := &api.AttachPolicyToGroupArgs{ + GroupName: groupName, + PolicyName: policyName, + } + err = IAM_CLIENT.AttachPolicyToGroup(attachArgs) + ExpectEqual(t.Errorf, err, nil) + + policies, err := IAM_CLIENT.ListGroupAttachedPolicies(groupName) + ExpectEqual(t.Errorf, err, nil) + if policies == nil || len(policies.Policies) != 1 { + t.Errorf("list policy result is not 1") + } + policy := policies.Policies[0] + ExpectEqual(t.Errorf, policyName, policy.Name) + + detachArgs := &api.DetachPolicyFromGroupArgs{ + GroupName: groupName, + PolicyName: policyName, + } + err = IAM_CLIENT.DetachPolicyFromGroup(detachArgs) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeletePolicy(policyName) + ExpectEqual(t.Errorf, err, nil) + err = IAM_CLIENT.DeleteGroup(groupName) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAccessKeyCreateAndDelete(t *testing.T) { + name := "test-user-sdk-go-ak" + args := &api.CreateUserArgs{ + Name: name, + Description: "description", + } + res, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(res) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, res.Name, args.Name) + ExpectEqual(t.Errorf, res.Description, args.Description) + + akRes, err := IAM_CLIENT.CreateAccessKey(name) + jsonAkRes, _ := json.Marshal(akRes) + t.Logf(string(jsonAkRes)) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, akRes.Enabled, true) + + accessKeys, err := IAM_CLIENT.ListAccessKey(name) + ExpectEqual(t.Errorf, err, nil) + if accessKeys == nil || len(accessKeys.AccessKeys) == 0 { + t.Errorf("list accessKeys return no result") + } + aksJsonRes, _ := json.Marshal(accessKeys) + t.Logf(string(aksJsonRes)) + + err = IAM_CLIENT.DeleteAccessKey(name, akRes.Id) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeleteUser(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestAccessKeyDisableAndEnable(t *testing.T) { + name := "test-user-sdk-go-ak" + args := &api.CreateUserArgs{ + Name: name, + Description: "description", + } + res, err := IAM_CLIENT.CreateUser(args) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(res) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, res.Name, args.Name) + ExpectEqual(t.Errorf, res.Description, args.Description) + + akRes, err := IAM_CLIENT.CreateAccessKey(name) + jsonAkRes, _ := json.Marshal(akRes) + t.Logf(string(jsonAkRes)) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, akRes.Enabled, true) + + disAbleAkRes, err := IAM_CLIENT.DisableAccessKey(name, akRes.Id) + ExpectEqual(t.Errorf, err, nil) + jsonDisAbleAkRes, _ := json.Marshal(disAbleAkRes) + t.Logf(string(jsonDisAbleAkRes)) + ExpectEqual(t.Errorf, disAbleAkRes.Enabled, false) + + enAbleAkRes, err := IAM_CLIENT.EnableAccessKey(name, akRes.Id) + ExpectEqual(t.Errorf, err, nil) + jsonEnAbleAkRes, _ := json.Marshal(enAbleAkRes) + t.Logf(string(jsonEnAbleAkRes)) + ExpectEqual(t.Errorf, enAbleAkRes.Enabled, true) + + err = IAM_CLIENT.DeleteAccessKey(name, akRes.Id) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeleteUser(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRoleCreateAndDelete(t *testing.T) { + name := "test-role-sdk-go" + args := &api.CreateRoleArgs{ + Name: name, + Description: "description", + AssumeRolePolicyDocument: getAssumeRolePolicyDocument(), + } + res, err := IAM_CLIENT.CreateRole(args) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(res) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, res.Name, args.Name) + ExpectEqual(t.Errorf, res.Description, args.Description) + + getRes, err := IAM_CLIENT.GetRole(name) + ExpectEqual(t.Errorf, err, nil) + getJsonRes, _ := json.Marshal(getRes) + t.Logf(string(getJsonRes)) + ExpectEqual(t.Errorf, res.Name, args.Name) + ExpectEqual(t.Errorf, res.Description, args.Description) + + rolesRes, err := IAM_CLIENT.ListRole() + ExpectEqual(t.Errorf, err, nil) + if rolesRes == nil || len(rolesRes.Roles) == 0 { + t.Errorf("list roles return no result") + } + rolesResJson, _ := json.Marshal(rolesRes) + t.Logf(string(rolesResJson)) + + newDescription := "newDescription" + updateArgs := &api.UpdateRoleArgs{ + Description: newDescription, + } + updateRes, err := IAM_CLIENT.UpdateRole(name, updateArgs) + ExpectEqual(t.Errorf, err, nil) + ExpectEqual(t.Errorf, updateRes.Description, newDescription) + + err = IAM_CLIENT.DeleteRole(name) + ExpectEqual(t.Errorf, err, nil) +} + +func TestRoleAttachPolicyAndDetachPolicy(t *testing.T) { + roleName := "test-role-sdk-go" + args := &api.CreateRoleArgs{ + Name: roleName, + Description: "description", + AssumeRolePolicyDocument: getAssumeRolePolicyDocument(), + } + res, err := IAM_CLIENT.CreateRole(args) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(res) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, res.Name, args.Name) + ExpectEqual(t.Errorf, res.Description, args.Description) + + policyName := "test_sdk_go_policy" + policyArgs := &api.CreatePolicyArgs{ + Name: policyName, + Description: "description", + Document: getPolicyDocument(), + } + + _, err = IAM_CLIENT.CreatePolicy(policyArgs) + ExpectEqual(t.Errorf, err, nil) + + attachArgs := &api.AttachPolicyToRoleArgs{ + RoleName: roleName, + PolicyName: policyName, + } + err = IAM_CLIENT.AttachPolicyToRole(attachArgs) + ExpectEqual(t.Errorf, err, nil) + + policies, err := IAM_CLIENT.ListRoleAttachedPolicies(roleName) + ExpectEqual(t.Errorf, err, nil) + if policies == nil || len(policies.Policies) != 1 { + t.Errorf("list policy result is not 1") + } + policy := policies.Policies[0] + ExpectEqual(t.Errorf, policyName, policy.Name) + + detachArgs := &api.DetachPolicyToRoleArgs{ + RoleName: roleName, + PolicyName: policyName, + } + err = IAM_CLIENT.DetachPolicyFromRole(detachArgs) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeletePolicy(policyName) + ExpectEqual(t.Errorf, err, nil) + + err = IAM_CLIENT.DeleteRole(roleName) + ExpectEqual(t.Errorf, err, nil) + +} + +func TestUserOperationMfaSwitch(t *testing.T) { + userName := "test-user-sdk-go-switch-operation-mfa" + enableMfa := true + mfaType := "PHONE,TOTP" + args := &api.UserSwitchMfaArgs{ + UserName: userName, + EnabledMfa: enableMfa, + MfaType: mfaType, + } + err := IAM_CLIENT.UserOperationMfaSwitch(args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestSubUserUpdate(t *testing.T) { + userName := "test-user-name-sdk-go-sub-update" + Password := "Baidu@123" + args := &api.UpdateSubUserArgs{ + Password: Password, + } + res, err := IAM_CLIENT.SubUserUpdate(userName, args) + ExpectEqual(t.Errorf, err, nil) + jsonRes, _ := json.Marshal(res) + t.Logf(string(jsonRes)) + ExpectEqual(t.Errorf, res.Name, userName) +} diff --git a/bce-sdk-go/services/lbdc/client.go b/bce-sdk-go/services/lbdc/client.go new file mode 100644 index 0000000..e9e0ba7 --- /dev/null +++ b/bce-sdk-go/services/lbdc/client.go @@ -0,0 +1,49 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for Application LBDC service + +// Package lbdc defines the LBDC services of BCE. The supported APIs are all defined in sub-package +package lbdc + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + DEFAULT_SERVICE_DOMAIN = "blb." + bce.DEFAULT_REGION + ".baidubce.com" + URI_PREFIX = bce.URI_PREFIX + "v1" + REQUEST_LBDC_URL = "/lbdc" +) + +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getUrlForLbdc() string { + return URI_PREFIX + REQUEST_LBDC_URL +} + +func getUrlForLbdcId(lbdcId string) string { + return getUrlForLbdc() + "/" + lbdcId +} diff --git a/bce-sdk-go/services/lbdc/client_test.go b/bce-sdk-go/services/lbdc/client_test.go new file mode 100644 index 0000000..399f00a --- /dev/null +++ b/bce-sdk-go/services/lbdc/client_test.go @@ -0,0 +1,185 @@ +package lbdc + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + LDBC_CLIENT *Client + + region string + + LDBCID string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + Endpoint string `json:"Endpoint"` +} + +func init() { + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + f = filepath.Dir(f) + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + LDBC_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + + region = confObj.Endpoint[4:6] + + log.SetLogHandler(log.FILE) + log.SetLogDir("/Users/xxx/go/log/baidu/bce/go-sdk") + log.SetRotateType(log.ROTATE_SIZE) + log.Info("this is my own logger from the sdk") +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_CreateLbdc(t *testing.T) { + description := "" + args := &CreateLbdcArgs{ + ClientToken: getClientToken(), + Name: "abc", + Type: "7Layer", + CcuCount: 2, + Description: &description, + Billing: &Billing{ + PaymentTiming: "Prepaid", + Reservation: &Reservation{ + ReservationLength: 1, + }, + }, + RenewReservation: &Reservation{ + ReservationLength: 1, + }, + } + res, err := LDBC_CLIENT.CreateLbdc(args) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_UpgradeLbdc(t *testing.T) { + args := &UpgradeLbdcArgs{ + ClientToken: getClientToken(), + Id: "bgw_group-81196491", + CcuCount: 4, + } + err := LDBC_CLIENT.UpgradeLbdc(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RenewLbdc(t *testing.T) { + args := &RenewLbdcArgs{ + ClientToken: getClientToken(), + Id: "bgw_group-81196491", + Billing: &BillingForRenew{ + Reservation: &Reservation{ + ReservationLength: 1, + }, + }, + } + err := LDBC_CLIENT.RenewLbdc(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListLbdc(t *testing.T) { + args := &ListLbdcArgs{ + //Id: "bgw_group-a6dd5dc2", + //Name: "abc", + } + res, err := LDBC_CLIENT.ListLbdc(args) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_GetLbdcDetail(t *testing.T) { + lbdcId := "bgw_group-81196491" + //lbdcId := "nginx_group-39d9d255" + res, err := LDBC_CLIENT.GetLbdcDetail(lbdcId) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_UpdateLbdc(t *testing.T) { + name := "" + desc := "test" + args := &UpdateLbdcArgs{ + ClientToken: getClientToken(), + Id: "bgw_group-81196491", + UpdateLbdcBody: &UpdateLbdcBody{ + Name: &name, + Description: &desc, + }, + } + err := LDBC_CLIENT.UpdateLbdc(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBoundBlBListOfLbdc(t *testing.T) { + lbdcId := "bgw_group-81196491" + res, err := LDBC_CLIENT.GetBoundBlBListOfLbdc(lbdcId) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} diff --git a/bce-sdk-go/services/lbdc/lbdc.go b/bce-sdk-go/services/lbdc/lbdc.go new file mode 100644 index 0000000..b4b1a6b --- /dev/null +++ b/bce-sdk-go/services/lbdc/lbdc.go @@ -0,0 +1,190 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 lbdc lbdc.go - the LBDC APIs definition supported by the LBDC service +package lbdc + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateLbdc - create the LBDC instance with the specific parameters +// +// PARAMS: +// - args: the arguments to create LBDC +// +// RETURNS: +// - *CreateLoadBalancerResult: the result of create LoadBalancer, contains new LoadBalancer's ID +// - error: nil if success otherwise the specific error +func (c *Client) CreateLbdc(args *CreateLbdcArgs) (*CreateLbdcResult, error) { + if args == nil { + return nil, fmt.Errorf("the CreateLbdcArgs cannot be nil") + } + result := &CreateLbdcResult{} + err := bce.NewRequestBuilder(c). + WithURL(getUrlForLbdc()). + WithMethod(http.POST). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpgradeLbdc - upgrade LBDC with the specific parameters +// +// PARAMS: +// - args: the arguments to update LBDC +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpgradeLbdc(args *UpgradeLbdcArgs) error { + if args == nil { + return fmt.Errorf("the UpgradeLbdcArgs cannot be nil") + } + + if len(args.Id) == 0 { + return fmt.Errorf("the LbdcId cannot be empty") + } + return bce.NewRequestBuilder(c). + WithURL(getUrlForLbdcId(args.Id)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("resize", ""). + Do() +} + +// RenewLbdc - renew LBDC with the specific parameters +// +// PARAMS: +// - args: the arguments to renew LBDC +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenewLbdc(args *RenewLbdcArgs) error { + if args == nil { + return fmt.Errorf("the RenewLbdcArgs cannot be nil") + } + + if len(args.Id) == 0 { + return fmt.Errorf("the LbdcId cannot be empty") + } + return bce.NewRequestBuilder(c). + WithURL(getUrlForLbdcId(args.Id)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("purchaseReserved", ""). + Do() +} + +// ListLbdc - list LBDC with the specific id and/or name +// +// PARAMS: +// - args: the arguments to list LBDC instances +// +// RETURNS: +// - *ListSslVpnUserResult: the result of Cluster list contains page infos +// - error: nil if success otherwise the specific error +func (c *Client) ListLbdc(args *ListLbdcArgs) (*ListLbdcResult, error) { + if args == nil { + args = &ListLbdcArgs{} + } + result := &ListLbdcResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getUrlForLbdc()). + WithMethod(http.GET). + WithResult(result) + if len(args.Id) > 0 { + builder.WithQueryParamFilter("id", args.Id) + } + if len(args.Name) > 0 { + builder.WithQueryParamFilter("name", args.Name) + } + err := builder.Do() + return result, err +} + +// GetLbdcDetail - get details of the specific lbdc +// +// PARAMS: +// - lbdcId: the id of the specified lbdc +// +// RETURNS: +// - *LbdcDetailResult: the result of the specific lbdc details +// - error: nil if success otherwise the specific error +func (c *Client) GetLbdcDetail(lbdcId string) (*GetLbdcDetailResult, error) { + if len(lbdcId) == 0 { + return nil, fmt.Errorf("the LbdcId cannot be empty") + } + + result := &GetLbdcDetailResult{} + err := bce.NewRequestBuilder(c). + WithURL(getUrlForLbdcId(lbdcId)). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} + +// UpdateLbdc - update lbdc with the specific parameters +// +// PARAMS: +// - args: the arguments to update lbdc +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateLbdc(args *UpdateLbdcArgs) error { + if args == nil { + return fmt.Errorf("the UpdateLbdcArgs cannot be nil") + } + if len(args.Id) == 0 { + return fmt.Errorf("the LbdcId cannot be empty") + } + + if args.UpdateLbdcBody == nil { + return fmt.Errorf("the UpdateLbdcBody cannot be nil") + } + + return bce.NewRequestBuilder(c). + WithURL(getUrlForLbdcId(args.Id)). + WithMethod(http.PUT). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args.UpdateLbdcBody). + Do() +} + +// GetBoundBlBListOfLbdc - get Bound blb list of lbdc +// +// PARAMS: +// - lbdcId: the id of the specified lbdc +// +// RETURNS: +// - *GetBoundBlBListOfLbdcResult: the result of the bound blb list of lbdc +// - error: nil if success otherwise the specific error +func (c *Client) GetBoundBlBListOfLbdc(lbdcId string) (*GetBoundBlBListOfLbdcResult, error) { + if len(lbdcId) == 0 { + return nil, fmt.Errorf("the LbdcId cannot be empty") + } + result := &GetBoundBlBListOfLbdcResult{} + err := bce.NewRequestBuilder(c). + WithURL(getUrlForLbdcId(lbdcId) + "/blb"). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} diff --git a/bce-sdk-go/services/lbdc/model.go b/bce-sdk-go/services/lbdc/model.go new file mode 100644 index 0000000..6368024 --- /dev/null +++ b/bce-sdk-go/services/lbdc/model.go @@ -0,0 +1,147 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package lbdc + +type Reservation struct { + ReservationLength int `json:"reservationLength"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation *Reservation `json:"reservation"` +} + +type ReservationForCreate struct { + ReservationLength int `json:"reservationLength,omitempty"` +} + +type BillingForRenew struct { + Reservation *Reservation `json:"reservation"` +} + +type Cluster struct { + Id string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Status string `json:"status"` + CcuCount int `json:"ccuCount"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + Description string `json:"desc"` +} + +// CreateLbdcArgs defines the structure of input parameters for the CreateLbdc api +type CreateLbdcArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Type string `json:"type"` + CcuCount int `json:"ccuCount"` + Description *string `json:"desc,omitempty"` + Billing *Billing `json:"billing"` + RenewReservation *Reservation `json:"renewReservation"` +} + +// CreateLbdcResult defines the structure of output parameters for the CreateLbdc api +type CreateLbdcResult struct { + Id string `json:"id"` + Type string `json:"type"` + Description string `json:"desc"` +} + +// UpgradeLbdcArgs defines the structure of input parameters for the UpgradeLbdc api +type UpgradeLbdcArgs struct { + ClientToken string `json:"-"` + Id string `json:"id"` + CcuCount int `json:"ccuCount"` +} + +// RenewLbdcArgs defines the structure of input parameters for the RenewLbdc api +type RenewLbdcArgs struct { + ClientToken string `json:"-"` + Id string `json:"id"` + Billing *BillingForRenew `json:"billing"` +} + +// ListLbdcArgs defines the structure of input parameters for the ListLbdc api +type ListLbdcArgs struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` +} + +// ListLbdcResult defines the structure of output parameters for the ListLbdc api +type ListLbdcResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + ClusterList []Cluster `json:"clusterList"` +} + +// GetLbdcDetailResult defines the structure of output parameters for the GetLbdcDetail api +type GetLbdcDetailResult struct { + // 4 layer + Id string `json:"id"` + Name string `json:"name"` + Type string `json:"type"` + Status string `json:"status"` + CcuCount int `json:"ccuCount"` + CreateTime string `json:"createTime"` + ExpireTime string `json:"expireTime"` + TotalConnectCount int64 `json:"totalConnectCount"` + NewConnectCps *int64 `json:"newConnectCps,omitempty"` + NetworkInBps int64 `json:"networkInBps"` + NetworkOutBps int64 `json:"networkOutBps"` + + // 7layer + HttpsQps *int64 `json:"httpsQps,omitempty"` + HttpQps *int64 `json:"httpQps,omitempty"` + HttpNewConnectCps *int64 `json:"httpNewConnectCps,omitempty"` + HttpsNewConnectCps *int64 `json:"httpsNewConnectCps,omitempty"` + SslNewConnectCps *int64 `json:"sslNewConnectCps,omitempty"` +} + +// UpdateLbdcArgs defines the structure of input parameters for the UpdateLbdc api +type UpdateLbdcArgs struct { + ClientToken string `json:"-"` + Id string `json:"id"` + UpdateLbdcBody *UpdateLbdcBody `json:"updateLbdcBody"` +} + +// UpdateLbdcBody defines the structure of input parameters for the UpdateLbdc api request body +type UpdateLbdcBody struct { + Name *string `json:"name,omitempty"` + Description *string `json:"desc,omitempty"` +} + +type AssociateBlb struct { + BlbId string `json:"blbId"` + Name string `json:"name"` + Status string `json:"status"` + BlbType string `json:"blbType"` + PublicIp string `json:"publicIp"` + EipRouteType string `json:"eipRouteType"` + Bandwidth int `json:"bandwidth"` + Address string `json:"address"` + Ipv6 string `json:"ipv6"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` +} + +// GetBoundBlBListOfLbdcResult defines the structure of output parameters for the GetBoundBlBListOfLbdc api +type GetBoundBlBListOfLbdcResult struct { + BlbList []AssociateBlb `json:"blbList"` +} diff --git a/bce-sdk-go/services/localDns/client.go b/bce-sdk-go/services/localDns/client.go new file mode 100644 index 0000000..befe9e5 --- /dev/null +++ b/bce-sdk-go/services/localDns/client.go @@ -0,0 +1,221 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 localDns + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "http://privatezone.baidubce.com" + DEFAULT_MAX_PARALLEL = 10 + MULTIPART_ALIGN = 1 << 20 // 1MB + MIN_MULTIPART_SIZE = 1 << 20 // 1MB + DEFAULT_MULTIPART_SIZE = 12 * (1 << 20) // 12MB + MAX_PART_NUMBER = 10000 +) + +// Client of bcd service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient + + // Fileds that used in parallel operation for BOS service + MaxParallel int64 + MultipartSize int64 +} + +// NewClient make the bcd service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer), + DEFAULT_MAX_PARALLEL, DEFAULT_MULTIPART_SIZE} + return client, nil +} + +// AddRecord - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - *api.AddRecordResponse: +// - error: the return error if any occurs +func (c *Client) AddRecord(zoneId string, body *AddRecordRequest) ( + *AddRecordResponse, error) { + return AddRecord(c, zoneId, body, body.ClientToken) +} + +// DeletePrivateZone - +// +// PARAMS: +// - zoneId: zone的id +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeletePrivateZone(zoneId string, clientToken string) error { + return DeletePrivateZone(c, zoneId, clientToken) +} + +// CreatePrivateZone - +// +// PARAMS: +// - body: body参数 +// +// RETURNS: +// - *api.CreatePrivateZoneResponse: +// - error: the return error if any occurs +func (c *Client) CreatePrivateZone(body *CreatePrivateZoneRequest) ( + *CreatePrivateZoneResponse, error) { + return CreatePrivateZone(c, body, body.ClientToken) +} + +// BindVpc - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) BindVpc(zoneId string, body *BindVpcRequest) error { + return BindVpc(c, zoneId, body, body.ClientToken) +} + +// DeleteRecord - +// +// PARAMS: +// - recordId: 解析记录ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteRecord(recordId string, clientToken string) error { + return DeleteRecord(c, recordId, clientToken) +} + +// DisableRecord - +// +// PARAMS: +// - recordId: 解析记录ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DisableRecord(recordId string, clientToken string) error { + return DisableRecord(c, recordId, clientToken) +} + +// EnableRecord - +// +// PARAMS: +// - recordId: 解析记录ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) EnableRecord(recordId string, clientToken string) error { + return EnableRecord(c, recordId, clientToken) +} + +// GetPrivateZone - +// +// PARAMS: +// - zoneId: zone的ID +// +// RETURNS: +// - *api.GetPrivateZoneResponse: +// - error: the return error if any occurs +func (c *Client) GetPrivateZone(zoneId string) (*GetPrivateZoneResponse, error) { + return GetPrivateZone(c, zoneId) +} + +// ListPrivateZone - +// +// PARAMS: +// - request: 获取privateZone列表的入参 +// +// RETURNS: +// - *api.ListPrivateZoneResponse: +// - error: the return error if any occurs +func (c *Client) ListPrivateZone(request *ListPrivateZoneRequest) ( + *ListPrivateZoneResponse, error) { + return ListPrivateZone(c, request.Marker, request.MaxKeys) +} + +// ListRecord - +// +// PARAMS: +// - zoneId: Zone的ID +// +// RETURNS: +// - *api.ListRecordResponse: +// - error: the return error if any occurs +func (c *Client) ListRecord(zoneId string) (*ListRecordResponse, error) { + return ListRecord(c, zoneId) +} + +// UnbindVpc - +// +// PARAMS: +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UnbindVpc(zoneId string, body *UnbindVpcRequest) error { + return UnbindVpc(c, zoneId, body, body.ClientToken) +} + +// UpdateRecord - +// +// PARAMS: +// - recordId: 解析记录的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: body参数 +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateRecord(recordId string, body *UpdateRecordRequest) error { + return UpdateRecord(c, recordId, body, body.ClientToken) +} diff --git a/bce-sdk-go/services/localDns/client_test.go b/bce-sdk-go/services/localDns/client_test.go new file mode 100644 index 0000000..7e9029a --- /dev/null +++ b/bce-sdk-go/services/localDns/client_test.go @@ -0,0 +1,169 @@ +package localDns + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + LD_CLIENT *Client + + // set these values before start test + VPC_ID = "vpc-0n1hhh8759b0" + Region = "bj" + RR = "rr" + TYPE = "A" + VALUE = "1.2.3.5" + ZONE_ID = "zone-mk2guy4qxd7c" + RECORD_ID = "rc-9mfacvjk6weq" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + LD_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreatePrivateZone(t *testing.T) { + createArgs := &CreatePrivateZoneRequest{ + ClientToken: getClientToken(), + ZoneName: "sdkLd.com", + } + createResult, err := LD_CLIENT.CreatePrivateZone(createArgs) + ExpectEqual(t.Errorf, nil, err) + + ZONE_ID = createResult.ZoneId +} + +func TestClient_DeletePrivateZone(t *testing.T) { + err := LD_CLIENT.DeletePrivateZone(ZONE_ID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListPrivateZone(t *testing.T) { + listPrivateZoneRequest := &ListPrivateZoneRequest{} + res, err := LD_CLIENT.ListPrivateZone(listPrivateZoneRequest) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetPrivateZone(t *testing.T) { + res, err := LD_CLIENT.GetPrivateZone(ZONE_ID) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BindVpc(t *testing.T) { + bindVpcRequest := &BindVpcRequest{ + Region: Region, + VpcIds: []string{VPC_ID}, + } + err := LD_CLIENT.BindVpc(ZONE_ID, bindVpcRequest) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnbindVpc(t *testing.T) { + unbindVpcRequest := &UnbindVpcRequest{ + Region: Region, + VpcIds: []string{VPC_ID}, + } + err := LD_CLIENT.UnbindVpc(ZONE_ID, unbindVpcRequest) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_AddRecord(t *testing.T) { + addRecordRequest := &AddRecordRequest{ + Rr: RR, + Type: TYPE, + Value: VALUE, + } + res, err := LD_CLIENT.AddRecord(ZONE_ID, addRecordRequest) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateRecord(t *testing.T) { + updateRecordRequest := &UpdateRecordRequest{ + Rr: RR, + Type: TYPE, + Value: VALUE, + } + err := LD_CLIENT.UpdateRecord(RECORD_ID, updateRecordRequest) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteRecord(t *testing.T) { + err := LD_CLIENT.DeleteRecord(RECORD_ID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListRecord(t *testing.T) { + res, err := LD_CLIENT.ListRecord(ZONE_ID) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EnableRecord(t *testing.T) { + err := LD_CLIENT.EnableRecord(RECORD_ID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DisableRecord(t *testing.T) { + err := LD_CLIENT.DisableRecord(RECORD_ID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/localDns/ld.go b/bce-sdk-go/services/localDns/ld.go new file mode 100644 index 0000000..aa7b881 --- /dev/null +++ b/bce-sdk-go/services/localDns/ld.go @@ -0,0 +1,431 @@ +/* + * Copyright 2022 Baidu, Inc. + * + * 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 localDns + +import ( + "encoding/json" + "strconv" + "strings" +) +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// AddRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - *api.AddRecordResponse: +// - error: the return error if any occurs +func AddRecord(cli bce.Client, zoneId string, body *AddRecordRequest, clientToken string) ( + *AddRecordResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/privatezone/[zoneId]/record" + path = strings.Replace(path, "[zoneId]", zoneId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &AddRecordResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// BindVpc - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func BindVpc(cli bce.Client, zoneId string, body *BindVpcRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/privatezone/[zoneId]" + path = strings.Replace(path, "[zoneId]", zoneId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + req.SetParam("bind", "") + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// CreatePrivateZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - *api.CreatePrivateZoneResponse: +// - error: the return error if any occurs +func CreatePrivateZone(cli bce.Client, body *CreatePrivateZoneRequest, clientToken string) ( + *CreatePrivateZoneResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.POST) + path := "/v1/privatezone" + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return nil, err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &CreatePrivateZoneResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// DeletePrivateZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneId: zone的id +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DeletePrivateZone(cli bce.Client, zoneId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/privatezone/[zoneId]" + path = strings.Replace(path, "[zoneId]", zoneId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - recordId: 解析记录ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func DeleteRecord(cli bce.Client, recordId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.DELETE) + path := "/v1/privatezone/record/[recordId]" + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DisableRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - recordId: 解析记录ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func DisableRecord(cli bce.Client, recordId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/privatezone/record/[recordId]" + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("disable", "") + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// EnableRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - recordId: 解析记录ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// +// RETURNS: +// - error: the return error if any occurs +func EnableRecord(cli bce.Client, recordId string, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/privatezone/record/[recordId]" + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("enable", "") + req.SetParam("clientToken", clientToken) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// GetPrivateZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneId: zone的ID +// +// RETURNS: +// - *api.GetPrivateZoneResponse: +// - error: the return error if any occurs +func GetPrivateZone(cli bce.Client, zoneId string) (*GetPrivateZoneResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/privatezone/[zoneId]" + path = strings.Replace(path, "[zoneId]", zoneId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &GetPrivateZoneResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListPrivateZone - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - marker: 批量获取列表的查询的起始位置,是一个由系统生成的字符串 +// - maxKeys: 每页包含的最大数量,最大数量通常不超过1000。缺省值为1000 +// +// RETURNS: +// - *api.ListPrivateZoneResponse: +// - error: the return error if any occurs +func ListPrivateZone(cli bce.Client, marker string, maxKeys int) ( + *ListPrivateZoneResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/privatezone" + req.SetUri(path) + if "" != marker { + req.SetParam("marker", marker) + } + if 0 != maxKeys { + req.SetParam("maxKeys", strconv.Itoa(maxKeys)) + } + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListPrivateZoneResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// ListRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - zoneId: Zone的ID +// +// RETURNS: +// - *api.ListRecordResponse: +// - error: the return error if any occurs +func ListRecord(cli bce.Client, zoneId string) (*ListRecordResponse, error) { + req := &bce.BceRequest{} + req.SetMethod(http.GET) + path := "/v1/privatezone/[zoneId]/record" + path = strings.Replace(path, "[zoneId]", zoneId, -1) + req.SetUri(path) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + res := &ListRecordResponse{} + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +// UnbindVpc - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UnbindVpc(cli bce.Client, zoneId string, body *UnbindVpcRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/privatezone/[zoneId]" + path = strings.Replace(path, "[zoneId]", zoneId, -1) + req.SetUri(path) + req.SetParam("unbind", "") + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// UpdateRecord - +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - recordId: 解析记录的ID +// - clientToken: 幂等性Token,是一个长度不超过64位的ASCII字符串 +// - body: +// +// RETURNS: +// - error: the return error if any occurs +func UpdateRecord(cli bce.Client, recordId string, body *UpdateRecordRequest, clientToken string) error { + req := &bce.BceRequest{} + req.SetMethod(http.PUT) + path := "/v1/privatezone/record/[recordId]" + path = strings.Replace(path, "[recordId]", recordId, -1) + req.SetUri(path) + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(body) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/localDns/model.go b/bce-sdk-go/services/localDns/model.go new file mode 100644 index 0000000..380edfa --- /dev/null +++ b/bce-sdk-go/services/localDns/model.go @@ -0,0 +1,144 @@ +/* + * Copyright Baidu, Inc. + * + * 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 localDns + +type AddRecordRequest struct { + ClientToken string `json:"-"` + Rr string `json:"rr"` + Value string `json:"value"` + Type string `json:"type"` + Ttl int32 `json:"ttl,omitempty"` + Priority int32 `json:"priority,omitempty"` + Description string `json:"description,omitempty"` +} + +type AddRecordResponse struct { + RecordId string `json:"recordId"` +} + +type BindVpcRequest struct { + ClientToken string `json:"-"` + Region string `json:"region"` + VpcIds []string `json:"vpcIds"` +} + +type BindVpcRequestVpcIds struct { +} + +type ListPrivateZoneRequest struct { + Marker string + MaxKeys int +} + +type CreatePrivateZoneRequest struct { + ClientToken string `json:"-"` + ZoneName string `json:"zoneName"` +} + +type CreatePrivateZoneResponse struct { + ZoneId string `json:"zoneId"` +} + +type DeletePrivateZoneRequest struct { + ZoneName string `json:"zoneName"` +} + +type DeleteRecordRequest struct { + RecordId string `json:"recordId"` + Rr string `json:"rr"` + Value string `json:"value"` + Type string `json:"type"` + Ttl *int32 `json:"ttl"` + Priority *int32 `json:"priority"` + Description *string `json:"description"` +} + +type GetPrivateZoneResponse struct { + ZoneId string `json:"zoneId"` + ZoneName string `json:"zoneName"` + RecordCount int32 `json:"recordCount"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` + BindVpcs []Vpc `json:"bindVpcs"` +} + +type GetPrivateZoneResponseBindVpcs struct { +} + +type ListPrivateZoneResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int32 `json:"maxKeys"` + Zones []Zone `json:"zones"` +} + +type ListPrivateZoneResponseZones struct { +} + +type ListRecordResponse struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int32 `json:"maxKeys"` + Records []Record `json:"records"` +} + +type ListRecordResponseRecords struct { +} + +type Record struct { + RecordId string `json:"recordId"` + Rr string `json:"rr"` + Value string `json:"value"` + Status string `json:"status"` + Type string `json:"type"` + Ttl int32 `json:"ttl"` + Priority int32 `json:"priority"` + Description string `json:"description"` +} + +type UnbindVpcRequest struct { + ClientToken string `json:"-"` + Region string `json:"region"` + VpcIds []string `json:"vpcIds"` +} + +type UnbindVpcRequestVpcIds struct { +} + +type UpdateRecordRequest struct { + ClientToken string `json:"-"` + Rr string `json:"rr"` + Value string `json:"value"` + Type string `json:"type"` + Ttl int32 `json:"ttl,omitempty"` + Priority int32 `json:"priority,omitempty"` + Description string `json:"description,omitempty"` +} + +type Vpc struct { + VpcId string `json:"vpcId"` + VpcName string `json:"vpcName"` + VpcRegion string `json:"vpcRegion"` +} + +type Zone struct { + ZoneId string `json:"zoneId"` + ZoneName string `json:"zoneName"` + RecordCount int32 `json:"recordCount"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} diff --git a/bce-sdk-go/services/media/api/job.go b/bce-sdk-go/services/media/api/job.go new file mode 100644 index 0000000..a4cb251 --- /dev/null +++ b/bce-sdk-go/services/media/api/job.go @@ -0,0 +1,121 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateJob(cli bce.Client, pipelineName, sourceKey, targetKey, presetName string) (*CreateJobResponse, error) { + args := &CreateJobArgs{} + args.PipelineName = pipelineName + + source := &Source{} + source.SourceKey = sourceKey + + target := &Target{} + target.TargetKey = targetKey + target.PresetName = presetName + + args.Source = source + args.Target = target + + req := &bce.BceRequest{} + req.SetUri(getTrandCodingJobUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, jsonErr := bce.NewBodyFromBytes(jsonBytes) + if jsonErr != nil { + return nil, jsonErr + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + result := &CreateJobResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return result, nil + +} + +func CreateJobCustomize(cli bce.Client, args *CreateJobArgs) (*CreateJobResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getTrandCodingJobUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, jsonErr := bce.NewBodyFromBytes(jsonBytes) + if jsonErr != nil { + return nil, jsonErr + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + result := &CreateJobResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + defer func() { resp.Body().Close() }() + return result, nil +} + +func ListTranscodingJobs(cli bce.Client, pipelineName string) (*ListTranscodingJobsResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getTrandCodingJobUrl()) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListTranscodingJobsResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetTranscodingJob(cli bce.Client, jobId string) (*GetTranscodingJobResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getTrandCodingJobUrl() + "/" + jobId) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetTranscodingJobResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/media/api/media_info.go b/bce-sdk-go/services/media/api/media_info.go new file mode 100644 index 0000000..268d975 --- /dev/null +++ b/bce-sdk-go/services/media/api/media_info.go @@ -0,0 +1,29 @@ +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func GetMediaInfoOfFile(cli bce.Client, bucket, key string) (*GetMediaInfoOfFileResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getMediaInfoUrl()) + req.SetMethod(http.GET) + paramMap := make(map[string]string) + paramMap["bucket"] = bucket + paramMap["key"] = key + req.SetParams(paramMap) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetMediaInfoOfFileResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/media/api/model.go b/bce-sdk-go/services/media/api/model.go new file mode 100644 index 0000000..84525b7 --- /dev/null +++ b/bce-sdk-go/services/media/api/model.go @@ -0,0 +1,453 @@ +package api + +// create pipline args +type CreatePiplineArgs struct { + PipelineName string `json:"pipelineName"` + Description string `json:"description,omitempty"` + SourceBucket string `json:"sourceBucket"` + TargetBucket string `json:"targetBucket"` + Config *CreatePiplineConfig `json:"config"` +} + +type CreatePiplineConfig struct { + Capacity int `json:"capacity"` + Notification string `json:"notification,omitempty"` + PipelineType string `json:"pipelineType,omitempty"` +} + +type ListPipelinesResponse struct { + Pipelines []PipelineStatus `json:"pipelines"` +} + +type JobStatus struct { + Total int `json:"total,omitempty"` + Running int `json:"running,omitempty"` + Pending int `json:"pending,omitempty"` + Failed int `json:"failed,omitempty"` +} + +type PipelineStatus struct { + PipelineName string `json:"pipelineName"` + Description string `json:"description,omitempty"` + SourceBucket string `json:"sourceBucket"` + TargetBucket string `json:"targetBucket"` + Config CreatePiplineConfig `json:"config"` + State string `json:"state,omitempty"` + Createtime string `json:"createtime,omitempty"` + JobStatus JobStatus `json:"jobStatus,omitempty"` +} + +type UpdatePipelineArgs struct { + PipelineName string `json:"pipelineName,omitempty"` + Description string `json:"description,omitempty"` + SourceBucket string `json:"sourceBucket,omitempty"` + TargetBucket string `json:"targetBucket,omitempty"` + UpdatePipelineConfig *UpdatePipelineConfig `json:"config,omitempty"` +} + +type UpdatePipelineConfig struct { + Capacity int `json:"capacity,omitempty"` + Notification string `json:"notification,omitempty"` +} + +type CreateJobArgs struct { + PipelineName string `json:"pipelineName,omitempty"` + Source *Source `json:"source"` + Target *Target `json:"target"` +} + +type Source struct { + SourceKey string `json:"sourceKey,omitempty"` + Clips *[]SourceClip `json:"clips,omitempty"` +} + +type SourceClip struct { + Bucket string `json:"bucket,omitempty"` + SourceKey string `json:"sourceKey,omitempty"` + StartTimeInSecond int `json:"startTimeInSecond,omitempty"` + DurationInSecond int `json:"durationInSecond,omitempty"` + StartTimeInMillisecond int `json:"startTimeInMillisecond,omitempty"` + DurationInMillisecond int `json:"durationInMillisecond,omitempty"` + EnableLogo bool `json:"enableLogo,omitempty"` + AsMasterClip bool `json:"asMasterClip,omitempty"` + EnableDelogo bool `json:"enableDelogo,omitempty"` + EnableCrop bool `json:"enableCrop,omitempty"` +} + +type Target struct { + TargetKey string `json:"targetKey,omitempty"` + PresetName string `json:"presetName,omitempty"` + AutoDelogo bool `json:"autoDelogo,omitempty"` + DelogoMode string `json:"delogoMode,omitempty"` + DelogoArea *Area `json:"delogoArea,omitempty"` + DelogoAreas *[]Area `json:"delogoAreas,omitempty"` + AutoCrop bool `json:"autoCrop,omitempty"` + Crop *Area `json:"crop,omitempty"` + WatermarkIds []string `json:"watermarkIds,omitempty"` + Inserts *[]Insert `json:"inserts,omitempty"` +} + +type Area struct { + X int `json:"x,omitempty"` + Y int `json:"y,omitempty"` + Width int `json:"width,omitempty"` + Height int `json:"height,omitempty"` +} + +type Insert struct { + Bucket string `json:"bucket,omitempty"` + Key string `json:"key,omitempty"` + Type string `json:"type,omitempty"` + Text string `json:"text"` + Font *Font `json:"font,omitempty"` + Timeline *Timeline `json:"timeline"` + Layout *Layout `json:"layout,omitempty"` +} + +type Font struct { + Family string `json:"family,omitempty"` + SizeInPoint int `json:"sizeInPoint,omitempty"` +} + +type Timeline struct { + StartTimeInMillisecond int `json:"startTimeInMillisecond,omitempty"` + DurationInMillisecond int `json:"durationInMillisecond,omitempty"` +} + +type Layout struct { + VerticalAlignment string `json:"verticalAlignment,omitempty"` + HorizontalAlignment string `json:"horizontalAlignment,omitempty"` + VerticalOffsetInPixel int `json:"verticalOffsetInPixel,omitempty"` + HorizontalOffsetInPixel int `json:"horizontalOffsetInPixel,omitempty"` +} + +type CreateJobResponse struct { + JobId string `json:"jobId"` +} + +type ListTranscodingJobsResponse struct { + Jobs []Job `json:"jobs"` +} + +type Job struct { + JobID string `json:"jobId"` + PipelineName string `json:"pipelineName"` + Source Source `json:"source"` + Target Target `json:"target"` + JobStatus string `json:"jobStatus"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + Error Error `json:"error"` +} + +type GetTranscodingJobResponse struct { + JobID string `json:"jobId"` + PipelineName string `json:"pipelineName"` + Source Source `json:"source"` + Target Target `json:"target"` + JobStatus string `json:"jobStatus"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` + Error Error `json:"error"` +} + +type Error struct { + Code string `json:"code"` + Message string `json:"message"` +} + +type ListPresetsResponse struct { + Presets []Preset `json:"presets"` +} + +type Preset struct { + PresetName string `json:"presetName,omitempty"` + Description string `json:"description,omitempty"` + Container string `json:"container,omitempty"` + Transmux bool `json:"transmux,omitempty"` + Clip *Clip `json:"clip,omitempty"` + Audio *Audio `json:"audio,omitempty"` + Video *Video `json:"video,omitempty"` + Encryption *Encryption `json:"encryption,omitempty"` + WatermarkID string `json:"watermarkId,omitempty"` + Watermarks *Watermarks `json:"watermarks,omitempty"` + TransCfg *TransCfg `json:"transCfg,omitempty"` + ExtraCfg *ExtraCfg `json:"extraCfg,omitempty"` + State string `json:"state,omitempty"` + CreatedTime string `json:"createdTime,omitempty"` +} + +type Clip struct { + StartTimeInSecond int `json:"startTimeInSecond,omitempty"` + DurationInSecond int `json:"durationInSecond,omitempty"` +} + +type Audio struct { + BitRateInBps int `json:"bitRateInBps,omitempty"` + SampleRateInHz int `json:"sampleRateInHz,omitempty"` + Channels int `json:"channels,omitempty"` + PcmFormat string `json:"pcmFormat,omitempty"` + VolumeAdjust *VolumeAdjust `json:"volumeAdjust,omitempty"` + Codec string `json:"codec,omitemptyc"` +} + +type VolumeAdjust struct { + Mute bool `json:"mute,omitempty"` + Norm bool `json:"norm,omitempty"` + Gain int `json:"gain,omitempty"` +} + +type Video struct { + Codec string `json:"codec,omitempty"` + CodecOptions *CodecOptions `json:"codecOptions,omitempty"` + RateControl string `json:"rateControl,omitempty"` + CodecEnhance bool `json:"codecEnhance,omitempty"` + BitRateInBps int `json:"bitRateInBps,omitempty"` + MaxFrameRate float64 `json:"maxFrameRate,omitempty"` + MaxWidthInPixel int `json:"maxWidthInPixel,omitempty"` + MaxHeigtInPixel int `json:"maxHeightInPixel,omitempty"` + SizingPolicy string `json:"sizingPolicy,omitempty"` + PlaybackSpeed float64 `json:"playbackSpeed,omitempty"` + Crf int `json:"crf,omitempty"` + AutoAdjustResolution bool `json:"autoAdjustResolution,omitempty"` +} + +type CodecOptions struct { + Profile string `json:"profile,omitempty"` +} + +type Encryption struct { + Strategy string `json:"strategy,omitempty"` + AesKey string `json:"aesKey,omitempty"` + KeyServerURL string `json:"keyServerUrl,omitempty"` +} + +type Watermarks struct { + Image []string `json:"image,omitempty"` +} + +type TransCfg struct { + TransMode string `json:"transMode,omitempty"` +} + +type ExtraCfg struct { + WatermarkDisableWhitelist []string `json:"watermarkDisableWhitelist,omitempty"` + SegmentDurationInSecond float64 `json:"segmentDurationInSecond,omitempty"` + GopLength int `json:"gopLength,omitempty"` + SkipBlackFrame bool `json:"skipBlackFrame,omitempty"` +} + +type GetPresetResponse struct { + PresetName string `json:"presetName"` + Description string `json:"description"` + Container string `json:"container"` + Transmux bool `json:"transmux"` + Clip Clip `json:"clip"` + Audio Audio `json:"audio"` + Video *Video `json:"video"` + Encryption *Encryption `json:"encryption"` + WatermarkID string `json:"watermarkId"` + Watermarks *Watermarks `json:"watermarks"` + TransCfg *TransCfg `json:"transCfg"` + ExtraCfg *ExtraCfg `json:"extraCfg"` + State string `json:"state"` + CreatedTime string `json:"createdTime"` +} + +type GetMediaInfoOfFileResponse struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + FileSizeInByte int `json:"fileSizeInByte"` + Container string `json:"container"` + DurationInSecond int `json:"durationInSecond"` + DurationInMillisecond int `json:"durationInMillisecond"` + Etag string `json:"etag"` + Type string `json:"type"` + VideoInfo *VideoInfo `json:"video"` + AudioInfo *AudioInfo `json:"audio"` +} + +type VideoInfo struct { + Codec string `json:"codec"` + HeightInPixel int `json:"heightInPixel"` + WidthInPixel int `json:"widthInPixel"` + BitRateInBps int `json:"bitRateInBps"` + FrameRate float64 `json:"frameRate"` + Rotate int `json:"rotate"` + Dar string `json:"dar"` +} + +type AudioInfo struct { + Codec string `json:"codec"` + Channels int `json:"channels"` + SampleRateInHz int `json:"sampleRateInHz"` + BitRateInBps int `json:"bitRateInBps"` +} + +type CreateThumbnailJobArgs struct { + PipelineName string `json:"pipelineName,omitempty"` + ThumbnailSource *ThumbnailSource `json:"source"` + PresetName string `json:"presetName,omitempty"` + ThumbnailTarget *ThumbnailTarget `json:"target,omitempty"` + ThumbnailCapture *ThumbnailCapture `json:"capture,omitempty"` + Area *Area `json:"delogoArea,omitempty"` + Crop *Area `json:"crop,omitempty"` +} + +type ThumbnailSource struct { + Key string `json:"key,omitempty"` +} + +type ThumbnailCapture struct { + Mode string `json:"mode,omitempty"` + StartTimeInSecond float64 `json:"startTimeInSecond,omitempty"` + EndTimeInSecond float64 `json:"endTimeInSecond,omitempty"` + IntervalInSecond float64 `json:"intervalInSecond,omitempty"` + MinIntervalInSecond float64 `json:"minIntervalInSecond,omitempty"` + FrameNumber int `json:"frameNumber,omitempty"` + SkipBlackFrame bool `json:"skipBlackFrame,omitempty"` + HighlightOutputCfg *HighlightOutputCfg `json:"highlightOutputCfg,omitempty"` + SpriteOutputCfg *SpriteOutputCfg `json:"spriteOutputCfg,omitempty"` +} + +type ThumbnailTarget struct { + KeyPrefix string `json:"keyPrefix,omitempty"` + Format string `json:"format,omitempty"` + FrameRate float64 `json:"frameRate,omitempty"` + GifQuality string `json:"gifQuality,omitempty"` + SizingPolicy string `json:"sizingPolicy,omitempty"` + WidthInPixel int `json:"widthInPixel,omitempty"` + HeightInPixel int `json:"heightInPixel,omitempty"` + SpriteOutputCfg *SpriteOutputCfg `json:"spriteOutputCfg,omitempty"` +} + +type HighlightOutputCfg struct { + DurationInSecond float64 `json:"durationInSecond,omitempty"` + FrameRate float64 `json:"frameRate,omitempty"` + PlaybackSpeed float64 `json:"playbackSpeed,omitempty"` + ReverseConcat bool `json:"reverseConcat,omitempty"` +} + +type SpriteOutputCfg struct { + Rows int `json:"rows,omitempty"` + Columns int `json:"columns,omitempty"` + Margin int `json:"margin,omitempty"` + Padding int `json:"padding,omitempty"` + KeepCellPic bool `json:"keepCellPic,omitempty"` + SpriteKeyTag string `json:"spriteKeyTag,omitempty"` +} + +type ThumbnailOptional struct { + PresetName string + Target *ThumbnailTarget + Capture *ThumbnailCapture + DelogoArea *Area + Crop *Area + ThumbnailSource *ThumbnailSource +} + +type GetThumbnailJobResponse struct { + JobID string `json:"jobId,omitempty"` + JobStatus string `json:"jobStatus,omitempty"` + PipelineName string `json:"pipelineName,omitempty"` + Source *ThumbnailSource `json:"source,omitempty"` + PresetName string `json:"presetName,omitempty"` + Target *ThumbnailTargetStatus `json:"target,omitempty"` + Capture *ThumbnailCapture `json:"capture,omitempty"` + DelogoArea *Area `json:"delogoArea,omitempty"` + Error *Error `json:"error,omitempty"` +} + +type ThumbnailTargetStatus struct { + KeyPrefix string `json:"keyPrefix,omitempty"` + Format string `json:"format,omitempty"` + FrameRate float64 `json:"frameRate,omitempty"` + GifQuality string `json:"gifQuality,omitempty"` + SizingPolicy string `json:"sizingPolicy,omitempty"` + WidthInPixel int `json:"widthInPixel,omitempty"` + HeightInPixel int `json:"heightInPixel,omitempty"` + SpriteOutputCfg *SpriteOutputCfg `json:"spriteOutputCfg,omitempty"` + Keys []string `json:"keys,omitempty"` +} + +type ListThumbnailJobsResponse struct { + Thumbnails []ThumbnailJobStatus `json:"thumbnails"` +} + +type ThumbnailJobStatus struct { + JobID string `json:"jobId"` + JobStatus string `json:"jobStatus"` + PipelineName string `json:"pipelineName"` + Source *ThumbnailSource `json:"source,omitempty"` + Target *ThumbnailTargetStatus `json:"target,omitempty"` + Capture *Area `json:"capture,omitempty"` + DelogoArea *Area `json:"delogoArea,omitempty"` + Error *Error `json:"error,omitempty"` +} + +type CreateWaterMarkArgs struct { + Bucket string `json:"bucket,omitempty"` + Key string `json:"key,omitempty"` + VerticalAlignment string `json:"verticalAlignment,omitempty"` + HorizontalAlignment string `json:"horizontalAlignment,omitempty"` + VerticalOffsetInPixel int `json:"verticalOffsetInPixel,omitempty"` + HorizontalOffsetInPixel int `json:"horizontalOffsetInPixel,omitempty"` + Timeline *Timeline `json:"timeline,omitempty"` + Repeated int `json:"repeated,omitempty"` + AllowScaling bool `json:"allowScaling,omitempty"` + Dx string `json:"dx,omitempty"` + Dy string `json:"dy,omitempty"` + Width string `json:"width,omitempty"` + Height string `json:"height,omitempty"` +} + +type CreateWaterMarkResponse struct { + WatermarkId string `json:"watermarkId"` +} + +type GetWaterMarkResponse struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + VerticalAlignment string `json:"verticalAlignment"` + HorizontalAlignment string `json:"horizontalAlignment"` + VerticalOffsetInPixel int `json:"verticalOffsetInPixel"` + HorizontalOffsetInPixel int `json:"horizontalOffsetInPixel"` + Timeline *Timeline `json:"timeline"` + Repeated int `json:"repeated"` + AllowScaling bool `json:"allowScaling"` + Dx string `json:"dx"` + Dy string `json:"dy"` + Width string `json:"width"` + Height string `json:"height"` +} + +type ListWaterMarkResponse struct { + Watermarks []Watermark `json:"watermarks"` +} + +type Watermark struct { + Bucket string `json:"bucket"` + Key string `json:"key"` + VerticalOffsetInPixel int `json:"verticalOffsetInPixel"` + HorizontalOffsetInPixel int `json:"horizontalOffsetInPixel"` + WatermarkID string `json:"watermarkId"` + CreateTime string `json:"createTime"` + VerticalAlignment string `json:"verticalAlignment"` + HorizontalAlignment string `json:"horizontalAlignment"` + Dx string `json:"dx"` + Dy string `json:"dy"` + Width string `json:"width"` + Height string `json:"height"` + Timeline *Timeline `json:"timeline,omitempty"` + Repeated int `json:"repeated"` + AllowScaling bool `json:"allowScaling"` +} + +type CreateNotificationArgs struct { + Name string `json:"name,omitempty"` + Endpoint string `json:"endpoint,omitempty"` +} + +type ListNotificationsResponse struct { + Notifications []CreateNotificationArgs `json:"notifications"` +} diff --git a/bce-sdk-go/services/media/api/notification.go b/bce-sdk-go/services/media/api/notification.go new file mode 100644 index 0000000..de188e9 --- /dev/null +++ b/bce-sdk-go/services/media/api/notification.go @@ -0,0 +1,88 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateNotification(cli bce.Client, name, endpoint string) error { + notify := &CreateNotificationArgs{} + notify.Name = name + notify.Endpoint = endpoint + + req := &bce.BceRequest{} + req.SetUri(getNotification()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + jsonBytes, err := json.Marshal(notify) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func GetNotification(cli bce.Client, name string) (*CreateNotificationArgs, error) { + req := &bce.BceRequest{} + req.SetUri(getNotification() + "/" + name) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &CreateNotificationArgs{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func ListNotification(cli bce.Client) (*ListNotificationsResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getNotification()) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListNotificationsResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func DeleteNotification(cli bce.Client, name string) error { + req := &bce.BceRequest{} + req.SetUri(getNotification() + "/" + name) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/media/api/pipline.go b/bce-sdk-go/services/media/api/pipline.go new file mode 100644 index 0000000..8a2571e --- /dev/null +++ b/bce-sdk-go/services/media/api/pipline.go @@ -0,0 +1,140 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreatePipeline(cli bce.Client, pipelineName, sourceBucket, targetBucket string, capacity int) error { + req := &bce.BceRequest{} + args := &CreatePiplineArgs{} + + args.PipelineName = pipelineName + args.SourceBucket = sourceBucket + args.TargetBucket = targetBucket + + config := &CreatePiplineConfig{} + config.Capacity = capacity + + args.Config = config + req.SetUri(getPipLineUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func CreatePipelineCustomize() { + +} + +func ListPipelines(cli bce.Client) (*ListPipelinesResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getPipLineUrl()) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPipelinesResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetPipeline(cli bce.Client, pipelineName string) (*PipelineStatus, error) { + req := &bce.BceRequest{} + req.SetUri(getPipLineUrl() + "/" + pipelineName) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &PipelineStatus{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetPipelineUpdate(cli bce.Client, pipelineName string) (*UpdatePipelineArgs, error) { + req := &bce.BceRequest{} + req.SetUri(getPipLineUrl() + "/" + pipelineName) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &UpdatePipelineArgs{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func DeletePipeline(cli bce.Client, pipelineName string) error { + req := &bce.BceRequest{} + req.SetUri(getPipLineUrl() + "/" + pipelineName) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func UpdatePipeline(cli bce.Client, pipelineName string, updatePipelineArgs *UpdatePipelineArgs) error { + req := &bce.BceRequest{} + jsonBytes, err := json.Marshal(updatePipelineArgs) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetUri(getPipLineUrl() + "/" + pipelineName) + req.SetMethod(http.PUT) + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/media/api/preset.go b/bce-sdk-go/services/media/api/preset.go new file mode 100644 index 0000000..9715177 --- /dev/null +++ b/bce-sdk-go/services/media/api/preset.go @@ -0,0 +1,128 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func ListPresets(cli bce.Client) (*ListPresetsResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getPresetUrl()) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListPresetsResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetPreset(cli bce.Client, presetName string) (*Preset, error) { + req := &bce.BceRequest{} + req.SetUri(getPresetUrl() + "/" + presetName) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &Preset{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil + +} + +func CreatePreset(cli bce.Client, presetName, description, container string) error { + req := &bce.BceRequest{} + req.SetUri(getPresetUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + args := &Preset{} + args.PresetName = presetName + args.Description = description + args.Container = container + args.Transmux = true + extraCfg := &ExtraCfg{} + args.ExtraCfg = extraCfg + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + + return nil +} + +func CreatePrestCustomize(cli bce.Client, preset *Preset) error { + req := &bce.BceRequest{} + req.SetUri(getPresetUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, err := json.Marshal(preset) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +func UpdatePreset(cli bce.Client, preset *Preset) error { + presetName := preset.PresetName + req := &bce.BceRequest{} + req.SetUri(getPresetUrl() + "/" + presetName) + req.SetMethod(http.PUT) + jsonBytes, err := json.Marshal(preset) + if err != nil { + return err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/media/api/thumbnail_job.go b/bce-sdk-go/services/media/api/thumbnail_job.go new file mode 100644 index 0000000..2992703 --- /dev/null +++ b/bce-sdk-go/services/media/api/thumbnail_job.go @@ -0,0 +1,83 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateThumbnailJob(cli bce.Client, pipelineName, sourceKey string, createThumbnialArgs *CreateThumbnailJobArgs) ( + *CreateJobResponse, error) { + + createThumbnialArgs.PipelineName = pipelineName + source := &ThumbnailSource{} + source.Key = sourceKey + createThumbnialArgs.ThumbnailSource = source + req := &bce.BceRequest{} + req.SetUri(getThumbnailUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + jsonBytes, err := json.Marshal(createThumbnialArgs) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CreateJobResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func GetThumbanilJob(cli bce.Client, jobId string) (*GetThumbnailJobResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getThumbnailUrl() + "/" + jobId) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetThumbnailJobResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func ListThumbnailJobs(cli bce.Client, pipelineName string) (*ListThumbnailJobsResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getThumbnailUrl()) + req.SetMethod(http.GET) + paramMap := make(map[string]string) + paramMap["pipelineName"] = pipelineName + req.SetParams(paramMap) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListThumbnailJobsResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/media/api/util.go b/bce-sdk-go/services/media/api/util.go new file mode 100644 index 0000000..2ddd3d9 --- /dev/null +++ b/bce-sdk-go/services/media/api/util.go @@ -0,0 +1,44 @@ +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + MEDIA_PREFIX = bce.URI_PREFIX + "v3/" + PIPLINE = "pipeline" + TRANSCODING_JOB = "job/transcoding" + PRESET = "preset" + MEDIA_INFO = "mediainfo" + THUMBNAIL = "job/thumbnail" + WATERMARK = "watermark" + NOTIFICATION = "notification" +) + +func getPipLineUrl() string { + return MEDIA_PREFIX + PIPLINE +} + +func getTrandCodingJobUrl() string { + return MEDIA_PREFIX + TRANSCODING_JOB +} + +func getPresetUrl() string { + return MEDIA_PREFIX + PRESET +} + +func getMediaInfoUrl() string { + return MEDIA_PREFIX + MEDIA_INFO +} + +func getThumbnailUrl() string { + return MEDIA_PREFIX + THUMBNAIL +} + +func getWatermarkUrl() string { + return MEDIA_PREFIX + WATERMARK +} + +func getNotification() string { + return MEDIA_PREFIX + NOTIFICATION +} diff --git a/bce-sdk-go/services/media/api/watermark.go b/bce-sdk-go/services/media/api/watermark.go new file mode 100644 index 0000000..1ee0a7c --- /dev/null +++ b/bce-sdk-go/services/media/api/watermark.go @@ -0,0 +1,87 @@ +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func CreateWaterMark(cli bce.Client, watermark *CreateWaterMarkArgs) (*CreateWaterMarkResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getWatermarkUrl()) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, err := json.Marshal(watermark) + if err != nil { + return nil, err + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CreateWaterMarkResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +func GetWaterMark(cli bce.Client, watermarkId string) (*GetWaterMarkResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getWatermarkUrl() + "/" + watermarkId) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetWaterMarkResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func ListWaterMark(cli bce.Client) (*ListWaterMarkResponse, error) { + req := &bce.BceRequest{} + req.SetUri(getWatermarkUrl()) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &ListWaterMarkResponse{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func DeleteWaterMark(cli bce.Client, watermarkId string) error { + req := &bce.BceRequest{} + req.SetUri(getWatermarkUrl() + "/" + watermarkId) + req.SetMethod(http.DELETE) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/media/client.go b/bce-sdk-go/services/media/client.go new file mode 100644 index 0000000..706c1d3 --- /dev/null +++ b/bce-sdk-go/services/media/client.go @@ -0,0 +1,232 @@ +package media + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/media/api" +) + +const DEFAULT_SERVICE_DOMAIN = "media.bj.baidubce.com" + +// mcp(media) client extends BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make MCP(media) service client with defualt configuration +// endPoint value can chose bj and sz or gz defualt bj +func NewClient(ak, sk, endPoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endPoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// create a simple pipeline with pipelieName,soureBucket,targetBucket,capacity +func (cli *Client) CreatePipeline(pipelineName, sourceBucket, targetBucket string, capacity int) error { + + return api.CreatePipeline(cli, pipelineName, sourceBucket, targetBucket, capacity) +} + +// list all pipelines for user +func (cli *Client) ListPipelines() (*api.ListPipelinesResponse, error) { + return api.ListPipelines(cli) +} + +// query pipeline by piplineName +func (cli *Client) GetPipeline(pipelineName string) (*api.PipelineStatus, error) { + return api.GetPipeline(cli, pipelineName) +} + +func (cli *Client) GetPipelineUpdate(pipelineName string) (*api.UpdatePipelineArgs, error) { + return api.GetPipelineUpdate(cli, pipelineName) +} + +// delete pipeline by pipelineName +func (cli *Client) DeletePipeline(pipelineName string) error { + return api.DeletePipeline(cli, pipelineName) +} + +// update pipeline with UpdatePipelineArgs +func (cli *Client) UpdatePipeline(pipelineName string, updatePipelineArgs *api.UpdatePipelineArgs) error { + return api.UpdatePipeline(cli, pipelineName, updatePipelineArgs) +} + +// create transcoding job with pipelineName, sourceKey, targetKey, presetName +func (cli *Client) CreateJob(pipelineName, sourceKey, targetKey, presetName string) (*api.CreateJobResponse, error) { + return api.CreateJob(cli, pipelineName, sourceKey, targetKey, presetName) +} + +// create trandcoding job with customize params +func (cli *Client) CreateJobCustomize(args *api.CreateJobArgs) (*api.CreateJobResponse, error) { + return api.CreateJobCustomize(cli, args) +} + +// list all jobs with piplineName +func (cli *Client) ListTranscodingJobs(pipelineName string) (*api.ListTranscodingJobsResponse, error) { + return api.ListTranscodingJobs(cli, pipelineName) +} + +// get transcoding job by jobId +func (cli *Client) GetTranscodingJob(jobId string) (*api.GetTranscodingJobResponse, error) { + return api.GetTranscodingJob(cli, jobId) +} + +// list all presets +func (cli *Client) ListPresets() (*api.ListPresetsResponse, error) { + return api.ListPresets(cli) +} + +// get preset by presetName +func (cli *Client) GetPreset(presetName string) (*api.Preset, error) { + return api.GetPreset(cli, presetName) +} + +// create preset at the same time perform container format conversion +func (cli *Client) CreatePreset(presetName, description, container string) error { + return api.CreatePreset(cli, presetName, description, container) +} + +// create preset with user-defined configuration +func (cli *Client) CreatePrestCustomize(preset *api.Preset) error { + return api.CreatePrestCustomize(cli, preset) +} + +// update preset +func (cli *Client) UpdatePreset(preset *api.Preset) error { + return api.UpdatePreset(cli, preset) +} + +// get media information with bucket and key +func (cli *Client) GetMediaInfoOfFile(bucket, key string) (*api.GetMediaInfoOfFileResponse, error) { + return api.GetMediaInfoOfFile(cli, bucket, key) +} + +// this option implements create thumbnail job function overloading +type Option func(thumbnailOptional *api.ThumbnailOptional) + +func PresetNameOp(presetName string) Option { + return func(thumbnailOptional *api.ThumbnailOptional) { + thumbnailOptional.PresetName = presetName + } +} + +func TargetOp(target *api.ThumbnailTarget) Option { + return func(thumbnailOptional *api.ThumbnailOptional) { + thumbnailOptional.Target = target + } +} + +func CaptureOp(capture *api.ThumbnailCapture) Option { + return func(thumbnailOptional *api.ThumbnailOptional) { + thumbnailOptional.Capture = capture + } +} + +func DelogoAreaOp(delogoArea *api.Area) Option { + return func(thumbnailOptional *api.ThumbnailOptional) { + thumbnailOptional.DelogoArea = delogoArea + } +} + +func CropOp(crop *api.Area) Option { + return func(thumbnailOptional *api.ThumbnailOptional) { + thumbnailOptional.Crop = crop + } +} + +func SourceOp(source *api.ThumbnailSource) Option { + return func(thumbnailOptional *api.ThumbnailOptional) { + thumbnailOptional.ThumbnailSource = source + } +} + +// create thumbnail job. +// you can create a thumbnail job with pipelineName and sourceKey and ThumbnailCapture and ThumbnailTarget or other args +func (cli *Client) CreateThumbnailJob(pipelineName, sourceKey string, ops ...Option) (*api.CreateJobResponse, error) { + var thumbnailOptional api.ThumbnailOptional + for _, op := range ops { + op(&thumbnailOptional) + } + + createThumbnialArgs := &api.CreateThumbnailJobArgs{} + createThumbnialArgs.PipelineName = pipelineName + source := &api.ThumbnailSource{} + source.Key = sourceKey + createThumbnialArgs.ThumbnailSource = source + createThumbnialArgs.PresetName = thumbnailOptional.PresetName + target := thumbnailOptional.Target + createThumbnialArgs.ThumbnailTarget = target + createThumbnialArgs.ThumbnailCapture = thumbnailOptional.Capture + createThumbnialArgs.Area = thumbnailOptional.DelogoArea + createThumbnialArgs.Crop = thumbnailOptional.Crop + return api.CreateThumbnailJob(cli, pipelineName, sourceKey, createThumbnialArgs) +} + +// query thumbanil job by jobId +func (cli *Client) GetThumbanilJob(jobId string) (*api.GetThumbnailJobResponse, error) { + return api.GetThumbanilJob(cli, jobId) +} + +// get thumbanil job by pipelineName +func (cli *Client) ListThumbnailJobs(pipelineName string) (*api.ListThumbnailJobsResponse, error) { + return api.ListThumbnailJobs(cli, pipelineName) +} + +// create watermark job +func (cli *Client) CreateWaterMark(watermarks *api.CreateWaterMarkArgs) (*api.CreateWaterMarkResponse, error) { + return api.CreateWaterMark(cli, watermarks) +} + +// get watermark by watermarkId +func (cli *Client) GetWaterMark(watermarkId string) (*api.GetWaterMarkResponse, error) { + return api.GetWaterMark(cli, watermarkId) +} + +// list user`s watermark by watermarkId +func (cli *Client) ListWaterMark() (*api.ListWaterMarkResponse, error) { + return api.ListWaterMark(cli) +} + +// delete watermark by watermarkId +func (cli *Client) DeleteWaterMark(watermarkId string) error { + return api.DeleteWaterMark(cli, watermarkId) +} + +// create notification with name and endpoint +func (cli *Client) CreateNotification(name, endpoint string) error { + return api.CreateNotification(cli, name, endpoint) +} + +// get notification by notification`name +func (cli *Client) GetNotification(name string) (*api.CreateNotificationArgs, error) { + return api.GetNotification(cli, name) +} + +// list all of user`s notification +func (cli *Client) ListNotification() (*api.ListNotificationsResponse, error) { + return api.ListNotification(cli) +} + +// delete notification by name +func (cli *Client) DeleteNotification(name string) error { + return api.DeleteNotification(cli, name) +} diff --git a/bce-sdk-go/services/media/client_test.go b/bce-sdk-go/services/media/client_test.go new file mode 100644 index 0000000..a64adcb --- /dev/null +++ b/bce-sdk-go/services/media/client_test.go @@ -0,0 +1,664 @@ +package media + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/services/media/api" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + MEDIA_CLIENT *Client +) + +type Conf struct { + AK string + SK string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + fmt.Printf("config json file of ak/sk not given: %+v\n", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + MEDIA_CLIENT, _ = NewClient(confObj.AK, confObj.SK, "") + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestCreatePipline(t *testing.T) { + err := MEDIA_CLIENT.CreatePipeline("test1", "go-sdk-test", "go-sdk-test", 10) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%s", "done") +} + +func TestListPipelines(t *testing.T) { + pipelines, err := MEDIA_CLIENT.ListPipelines() + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", pipelines) +} + +func TestGetPipeline(t *testing.T) { + pipeline, err := MEDIA_CLIENT.GetPipeline("go_sdk_test") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", pipeline) +} + +func TestDeletePipeline(t *testing.T) { + err := MEDIA_CLIENT.DeletePipeline("test11") + ExpectEqual(t.Errorf, err, nil) +} + +func TestUpdatePipeline(t *testing.T) { + args, _ := MEDIA_CLIENT.GetPipelineUpdate("test1") + args.Description = "update" + args.TargetBucket = "vwdemo" + args.SourceBucket = "vwdemo" + + config := &api.UpdatePipelineConfig{} + config.Capacity = 2 + config.Notification = "zz" + args.UpdatePipelineConfig = config + err := MEDIA_CLIENT.UpdatePipeline("test1", args) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateJob(t *testing.T) { + jobResponse, err := MEDIA_CLIENT.CreateJob("go_sdk_test", "01.mp4", "01_go_02.mp4", + "videoworks_system_preprocess_360p") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", jobResponse) +} + +func TestCreateJobCustomize(t *testing.T) { + args := &api.CreateJobArgs{} + args.PipelineName = "go_sdk_test" + source := &api.Source{Clips: &[]api.SourceClip{{ + SourceKey: "01.mp4", + EnableDelogo: false, + DurationInMillisecond: 6656, + StartTimeInSecond: 2}}} + args.Source = source + target := &api.Target{} + targetKey := "clips_playback_watermark_delogo_crop2.mp4" + watermarkId := "wmk-pcgqidaj13iv1eyf" + target.TargetKey = targetKey + watermarkIdSlice := append(target.WatermarkIds, watermarkId) + target.WatermarkIds = watermarkIdSlice + presetName := "go_test_customize_audio_video" + target.PresetName = presetName + + delogoArea := &api.Area{} + delogoArea.X = 10 + delogoArea.Y = 10 + delogoArea.Width = 30 + delogoArea.Height = 40 + target.DelogoArea = delogoArea + + args.Target = target + + jobResponse, err := MEDIA_CLIENT.CreateJobCustomize(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", jobResponse) +} + +func TestCreateJobCustomizeDelogoCrop(t *testing.T) { + args := &api.CreateJobArgs{} + args.PipelineName = "go_sdk_test" + source := &api.Source{Clips: &[]api.SourceClip{{ + SourceKey: "01.mp4", + EnableDelogo: false, + DurationInMillisecond: 6656, + StartTimeInSecond: 2}}} + args.Source = source + target := &api.Target{} + targetKey := "clips_playback_watermark_delogo_crop2.mp4" + watermarkId := "wmk-pcgqidaj13iv1eyf" + target.TargetKey = targetKey + watermarkIdSlice := append(target.WatermarkIds, watermarkId) + target.WatermarkIds = watermarkIdSlice + presetName := "go_test_customize_audio_video" + target.PresetName = presetName + + delogoArea := &api.Area{} + delogoArea.X = 10 + delogoArea.Y = 10 + delogoArea.Width = 30 + delogoArea.Height = 40 + target.DelogoArea = delogoArea + + args.Target = target + + jobResponse, err := MEDIA_CLIENT.CreateJobCustomize(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", jobResponse) +} + +func TestListTranscodingJobs(t *testing.T) { + listTranscodingJobsResponse, err := MEDIA_CLIENT.ListTranscodingJobs("go_sdk_test") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", listTranscodingJobsResponse) +} + +func TestGetTranscodingJob(t *testing.T) { + getTranscodingJobResponse, err := MEDIA_CLIENT.GetTranscodingJob("job-pbsq30p9161enwpz") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", getTranscodingJobResponse) +} + +func TestListPresets(t *testing.T) { + listPresetsResponse, err := MEDIA_CLIENT.ListPresets() + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", listPresetsResponse) +} + +func TestGetPreset(t *testing.T) { + getPresetResponse, err := MEDIA_CLIENT.GetPreset("q_go_test_customize_audio_video") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", getPresetResponse) + video := getPresetResponse.Video + t.Logf("%+v", video) + audio := getPresetResponse.Audio + t.Logf("%+v", audio) +} + +func TestCreatePreset(t *testing.T) { + err := MEDIA_CLIENT.CreatePreset("go_sdk_test_preset3", "测试go创建模板3", "mp4") + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreatePrestCustomizeAudio(t *testing.T) { + preset := &api.Preset{} + preset.PresetName = "go_test_customize" + preset.Description = "自定义创建模板" + preset.Container = "mp4" + + audio := &api.Audio{} + audio.BitRateInBps = 256000 + preset.Audio = audio + + err := MEDIA_CLIENT.CreatePrestCustomize(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreatePrestCustomizeAudioEncryptionC(t *testing.T) { + preset := &api.Preset{} + preset.PresetName = "go_test_customize_encryption_clip" + preset.Description = "自定义创建模板" + preset.Container = "mp3" + + audio := &api.Audio{} + audio.BitRateInBps = 256000 + preset.Audio = audio + + clip := &api.Clip{} + clip.StartTimeInSecond = 2 + clip.DurationInSecond = 10 + preset.Clip = clip + + encryption := &api.Encryption{} + encryption.Strategy = "PlayerBinding" + preset.Encryption = encryption + + err := MEDIA_CLIENT.CreatePrestCustomize(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreatePrestCustomizeAudioEncryption(t *testing.T) { + preset := &api.Preset{} + preset.PresetName = "go_test_customize_encryption" + preset.Description = "自定义创建模板" + preset.Container = "mp3" + + audio := &api.Audio{} + audio.BitRateInBps = 256000 + preset.Audio = audio + + encryption := &api.Encryption{} + encryption.Strategy = "PlayerBinding" + preset.Encryption = encryption + + err := MEDIA_CLIENT.CreatePrestCustomize(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreatePrestCustomizeAudioVideo(t *testing.T) { + preset := &api.Preset{} + preset.PresetName = "q_go_test_customize_audio_video" + preset.Description = "自定义创建模板" + preset.Container = "mp4" + + audio := &api.Audio{} + audio.BitRateInBps = 256000 + audio.Codec = "opus" + preset.Audio = audio + + video := &api.Video{} + //video.BitRateInBps = 1024000 + video.MaxHeigtInPixel = 1920 + video.MaxWidthInPixel = 1280 + video.CodecEnhance = true + video.Crf = 23 + video.RateControl = "crf" + preset.Video = video + + err := MEDIA_CLIENT.CreatePrestCustomize(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreatePrestCustomizeClpAudVidEncWat(t *testing.T) { + preset := &api.Preset{} + preset.PresetName = "go_test_customize_clp_aud_vid_en_wat" + preset.Description = "自定义创建模板" + preset.Container = "mp4" + + clip := &api.Clip{} + clip.StartTimeInSecond = 0 + clip.DurationInSecond = 60 + preset.Clip = clip + + audio := &api.Audio{} + audio.BitRateInBps = 256000 + preset.Audio = audio + + video := &api.Video{} + video.BitRateInBps = 1024000 + preset.Video = video + + encryption := &api.Encryption{} + encryption.Strategy = "PlayerBinding" + preset.Encryption = encryption + + preset.WatermarkID = "wmk-pc0rdhzbm8ff99qw" + + err := MEDIA_CLIENT.CreatePrestCustomize(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreatePrestCustomizeFullArgs(t *testing.T) { + preset := &api.Preset{} + preset.PresetName = "go_test_customize_full_args" + preset.Description = "全参数" + preset.Container = "hls" + preset.Transmux = false + + clip := &api.Clip{} + clip.StartTimeInSecond = 0 + clip.DurationInSecond = 60 + preset.Clip = clip + + audio := &api.Audio{} + audio.BitRateInBps = 256000 + preset.Audio = audio + + video := &api.Video{} + video.BitRateInBps = 1024000 + preset.Video = video + + encryption := &api.Encryption{} + encryption.Strategy = "PlayerBinding" + preset.Encryption = encryption + + water := &api.Watermarks{} + water.Image = []string{"wmk-pc0rdhzbm8ff99qw"} + preset.Watermarks = water + + transCfg := &api.TransCfg{} + transCfg.TransMode = "normal" + preset.TransCfg = transCfg + + extraCfg := &api.ExtraCfg{} + extraCfg.SegmentDurationInSecond = 6.66 + preset.ExtraCfg = extraCfg + + err := MEDIA_CLIENT.CreatePrestCustomize(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestClient_UpdatePreset(t *testing.T) { + preset, _ := MEDIA_CLIENT.GetPreset("go_test_customize") + preset.Description = "测试update-v2" + err := MEDIA_CLIENT.UpdatePreset(preset) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetMediaInfoOfFile(t *testing.T) { + info, err := MEDIA_CLIENT.GetMediaInfoOfFile("go-test", "01.mp4") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", info) + videoInfo := info.VideoInfo + t.Logf("%+v", videoInfo) + audioInfo := info.AudioInfo + t.Logf("%+v", audioInfo) +} + +func TestCreateThumbnailJob(t *testing.T) { + target := &api.ThumbnailTarget{} + target.Format = "jpg" + target.SizingPolicy = "keep" + capture := &api.ThumbnailCapture{} + capture.Mode = "manual" + capture.StartTimeInSecond = 0.0 + capture.EndTimeInSecond = 5.0 + capture.IntervalInSecond = 1.0 + // params piplineName sourceKey target capture + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01.mp4", + TargetOp(target), CaptureOp(capture)) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestCreateThumbnailJobTargetKeyPrefix(t *testing.T) { + //source := &api.ThumbnailSource{} + //source.Key = "01.mp4" + target := &api.ThumbnailTarget{} + target.KeyPrefix = "taget_key_prefix_test" + + // pipelineName presetName sourceKey targetKeyPrefix + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01_go_02.mp4", + PresetNameOp("test"), TargetOp(target)) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestCreateThumbnailJobDelogo(t *testing.T) { + target := &api.ThumbnailTarget{} + target.KeyPrefix = "taget_key_prefix_test_delogo3" + delogo := &api.Area{} + delogo.X = 20 + delogo.Y = 20 + delogo.Height = 50 + delogo.Width = 80 + // piplineName sourceKey target capture delogo + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01_go_02.mp4", + TargetOp(target), DelogoAreaOp(delogo)) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestCreateThumbnailJobDelogoCrop(t *testing.T) { + target := &api.ThumbnailTarget{} + target.KeyPrefix = "taget_key_prefix_test_delogo_crop" + delogo := &api.Area{} + delogo.X = 20 + delogo.Y = 20 + delogo.Height = 50 + delogo.Width = 80 + + crop := &api.Area{} + crop.X = 120 + crop.Y = 120 + crop.Height = 100 + crop.Width = 80 + // piplineName sourceKey target capture delogo crop + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01_go_02.mp4", + TargetOp(target), DelogoAreaOp(delogo), CropOp(crop)) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestCreateThumbnailJobCaptureDelogo(t *testing.T) { + target := &api.ThumbnailTarget{} + target.Format = "jpg" + target.SizingPolicy = "keep" + + capture := &api.ThumbnailCapture{} + capture.Mode = "split" + capture.FrameNumber = 30 + + delogo := &api.Area{} + delogo.X = 20 + delogo.Y = 20 + delogo.Height = 50 + delogo.Width = 80 + // params piplineName sourceKey target capture delogo + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01.mp4", + TargetOp(target), CaptureOp(capture), DelogoAreaOp(delogo)) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestCreateThumbnailJobCaptureDelogoCrop(t *testing.T) { + target := &api.ThumbnailTarget{} + target.Format = "jpg" + target.SizingPolicy = "keep" + + capture := &api.ThumbnailCapture{} + capture.Mode = "splitss0" + capture.FrameNumber = 10 + + delogo := &api.Area{} + delogo.X = 20 + delogo.Y = 20 + delogo.Height = 50 + delogo.Width = 80 + + crop := &api.Area{} + crop.X = 120 + crop.Y = 120 + crop.Height = 100 + crop.Width = 80 + // params piplineName sourceKey target capture delogo + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01.mp4", + TargetOp(target), CaptureOp(capture), DelogoAreaOp(delogo), CropOp(crop)) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestCreateThumbnailJobSimple(t *testing.T) { + // params piplineName sourceKey target capture delogo + createJobResponse, err := MEDIA_CLIENT.CreateThumbnailJob("go_sdk_test", "01.mp4") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createJobResponse) +} + +func TestGetThumbanilJob(t *testing.T) { + jobResponse, err := MEDIA_CLIENT.GetThumbanilJob("job-pcduuweehm1qd0et") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", jobResponse) + t.Logf("%+v", jobResponse.Source) + t.Logf("%+v", jobResponse.Target) + t.Logf("%+v", jobResponse.Capture) + t.Logf("%+v", jobResponse.DelogoArea) + t.Logf("%+v", jobResponse.Error) +} + +func TestListThumbnailJobs(t *testing.T) { + listThumbnailJobsResponse, err := MEDIA_CLIENT.ListThumbnailJobs("go_sdk_test") + ExpectEqual(t.Errorf, err, nil) + for _, job := range listThumbnailJobsResponse.Thumbnails { + t.Logf("%+v", job) + } +} + +func TestCreateWaterMark(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalOffsetInPixel, verticalOffsetInPixel + args.Bucket = "go-test" + args.Key = "01.jpg" + args.HorizontalOffsetInPixel = 20 + args.VerticalOffsetInPixel = 10 + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestCreateWaterMarkHV(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalAlignment, verticalAlignment + args.Bucket = "go-test" + args.Key = "01.jpg" + args.HorizontalAlignment = "right" + args.VerticalAlignment = "top" + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestCreateWaterMarkHHVV(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalAlignment, verticalAlignment + args.Bucket = "go-test" + args.Key = "01.jpg" + args.HorizontalOffsetInPixel = 200 + args.HorizontalAlignment = "left" + args.VerticalOffsetInPixel = 200 + args.VerticalAlignment = "bottom" + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestCreateWaterMarkHVXY(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalAlignment, verticalAlignment + args.Bucket = "go-test" + args.Key = "01.jpg" + args.HorizontalAlignment = "center" + args.VerticalAlignment = "center" + args.Dy = "0.1" + args.Dy = "0.2" + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestCreateWaterMarkHVXYWH(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalAlignment, verticalAlignment + args.Bucket = "go-test" + args.Key = "01.jpg" + args.HorizontalAlignment = "center" + args.VerticalAlignment = "center" + args.Dy = "0.1" + args.Dy = "0.2" + args.Width = "0.15" + args.Height = "0.11" + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestCreateWaterMarkHVTRA(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalAlignment, verticalAlignment + args.Bucket = "go-test" + args.Key = "01.jpg" + args.HorizontalAlignment = "left" + args.VerticalAlignment = "top" + args.HorizontalOffsetInPixel = 20 + args.VerticalOffsetInPixel = 10 + timeline := &api.Timeline{} + timeline.StartTimeInMillisecond = 1000 + timeline.DurationInMillisecond = 3000 + args.Timeline = timeline + args.Repeated = 1 + args.AllowScaling = true + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestCreateWaterMarkHVTXYWHTR(t *testing.T) { + args := &api.CreateWaterMarkArgs{} + // bucket, key, horizontalAlignment, verticalAlignment + args.Bucket = "go-test" + args.Key = "tupian.jpg" + args.HorizontalAlignment = "center" + args.VerticalAlignment = "center" + args.Dy = "0.1" + args.Dy = "0.2" + args.Width = "150" + args.Height = "110" + timeline := &api.Timeline{} + timeline.StartTimeInMillisecond = 1 + timeline.DurationInMillisecond = 5 + args.Timeline = timeline + args.Repeated = 10 + createWaterMarkResponse, err := MEDIA_CLIENT.CreateWaterMark(args) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", createWaterMarkResponse) +} + +func TestGetWaterMark(t *testing.T) { + response, err := MEDIA_CLIENT.GetWaterMark("wmk-pcep0x4vvmvvx84r") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) + t.Logf("%+v", response.Timeline) +} + +func TestListWaterMark(t *testing.T) { + response, err := MEDIA_CLIENT.ListWaterMark() + ExpectEqual(t.Errorf, err, nil) + for _, watermark := range response.Watermarks { + t.Logf("%+v", watermark) + } +} + +func TestDeleteWaterMark(t *testing.T) { + err := MEDIA_CLIENT.DeleteWaterMark("wmk-pcep0x4vvmvvx84r") + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateNotification(t *testing.T) { + err := MEDIA_CLIENT.CreateNotification("test", "http://www.baidu.com") + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetNotification(t *testing.T) { + response, err := MEDIA_CLIENT.GetNotification("zz") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", response) +} + +func TestListNotification(t *testing.T) { + response, err := MEDIA_CLIENT.ListNotification() + ExpectEqual(t.Errorf, err, nil) + for _, notification := range response.Notifications { + t.Logf("%+v", notification) + } +} + +func TestDeleteNotification(t *testing.T) { + err := MEDIA_CLIENT.DeleteNotification("test") + ExpectEqual(t.Errorf, err, nil) +} diff --git a/bce-sdk-go/services/mms/api/api.go b/bce-sdk-go/services/mms/api/api.go new file mode 100644 index 0000000..ca85246 --- /dev/null +++ b/bce-sdk-go/services/mms/api/api.go @@ -0,0 +1,303 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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 api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func InsertVideo(cli bce.Client, lib string, args *BaseRequest) (*BaseResponse, error) { + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + + resp, err := sendRequest(cli, http.PUT, URI_PREFIX+VIDEO_URI+"/"+lib, jsonBytes, map[string]string{}) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil + +} + +func GetInsertVideoResult(cli bce.Client, lib, source string) (*BaseResponse, error) { + + params := map[string]string{ + "source": source, + } + + resp, err := sendRequest(cli, http.GET, URI_PREFIX+VIDEO_URI+"/"+lib, []byte{}, params) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func GetInsertVideoResultById(cli bce.Client, libId, mediaId string) (*BaseResponse, error) { + + params := map[string]string{ + "mediaId": mediaId, + "getInsertResponseById": "", + } + + resp, err := sendRequest(cli, http.GET, URI_PREFIX+VIDEO_URI+"/"+libId, []byte{}, params) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func DeleteVideo(cli bce.Client, lib, source string) (*BaseResponse, error) { + + params := map[string]string{ + "source": source, + "deleteVideo": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+VIDEO_URI+"/"+lib, []byte{}, params) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func DeleteVideoById(cli bce.Client, libId, mediaId string) (*BaseResponse, error) { + + params := map[string]string{ + "mediaId": mediaId, + "deleteVideoById": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+VIDEO_URI+"/"+libId, []byte{}, params) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func InsertImage(cli bce.Client, lib string, args *BaseRequest) (*BaseResponse, error) { + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + + resp, err := sendRequest(cli, http.PUT, URI_PREFIX+IMAGE_URI+"/"+lib, jsonBytes, map[string]string{}) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func DeleteImage(cli bce.Client, lib, source string) (*BaseResponse, error) { + + params := map[string]string{ + "source": source, + "deleteImage": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+IMAGE_URI+"/"+lib, []byte{}, params) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func DeleteImageById(cli bce.Client, libId, mediaId string) (*BaseResponse, error) { + + params := map[string]string{ + "mediaId": mediaId, + "deleteImageById": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+IMAGE_URI+"/"+libId, []byte{}, params) + res := &BaseResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func SearchImageByImage(cli bce.Client, lib string, args *BaseRequest) (*SearchTaskResultResponse, error) { + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + + params := map[string]string{ + "searchByImage": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+IMAGE_URI+"/"+lib, jsonBytes, params) + res := &SearchTaskResultResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func SearchVideoByImage(cli bce.Client, lib string, args *BaseRequest) (*SearchTaskResultResponse, error) { + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + + params := map[string]string{ + "searchByImage": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+VIDEO_URI+"/"+lib, jsonBytes, params) + res := &SearchTaskResultResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func SearchVideoByVideo(cli bce.Client, lib string, args *BaseRequest) (*SearchTaskResultResponse, error) { + + jsonBytes, err := json.Marshal(args) + if err != nil { + return nil, err + } + + params := map[string]string{ + "searchByVideo": "", + } + + resp, err := sendRequest(cli, http.POST, URI_PREFIX+VIDEO_URI+"/"+lib, jsonBytes, params) + res := &SearchTaskResultResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func GetSearchVideoByVideoResult(cli bce.Client, lib, source string) (*SearchTaskResultResponse, error) { + + params := map[string]string{ + "searchByVideo": "", + "source": source, + } + + resp, err := sendRequest(cli, http.GET, URI_PREFIX+VIDEO_URI+"/"+lib, []byte{}, params) + res := &SearchTaskResultResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func GetSearchVideoByVideoResultById(cli bce.Client, lib, taskId string) (*SearchTaskResultResponse, error) { + + params := map[string]string{ + "getSearchResponseByTaskId": "", + "taskId": taskId, + } + + resp, err := sendRequest(cli, http.GET, URI_PREFIX+VIDEO_URI+"/"+lib, []byte{}, params) + res := &SearchTaskResultResponse{} + if err != nil { + return nil, err + } + + if err := resp.ParseJsonBody(res); err != nil { + return nil, err + } + return res, nil +} + +func sendRequest(cli bce.Client, httpMethod, url string, bodyJson []byte, params map[string]string) (*bce.BceResponse, error) { + req := &bce.BceRequest{} + req.SetHeader(http.CONTENT_TYPE, "application/json;charset=utf-8") + req.SetUri(url) + req.SetMethod(httpMethod) + req.SetParams(params) + + body, err := bce.NewBodyFromBytes(bodyJson) + if err != nil { + return nil, err + } + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + return resp, nil +} diff --git a/bce-sdk-go/services/mms/api/model.go b/bce-sdk-go/services/mms/api/model.go new file mode 100644 index 0000000..0e3993f --- /dev/null +++ b/bce-sdk-go/services/mms/api/model.go @@ -0,0 +1,96 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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 api + +import ( + "time" + + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v2" + VIDEO_URI = "/videolib" + IMAGE_URI = "/imagelib" +) + +type BaseRequest struct { + Source string `json:"source"` + Description string `json:"description"` + Notification string `json:"notification"` + NeedTag bool `json:"needTag"` +} + +type BaseResponse struct { + TaskID string `json:"taskId"` + Status string `json:"status"` + Description string `json:"description"` + Duration float64 `json:"duration"` + Error struct { + Code string `json:"code"` + Message string `json:"message"` + } `json:"error"` + Lib string `json:"lib"` + Source string `json:"source"` + UpdateTime time.Time `json:"updateTime"` + StartTime time.Time `json:"startTime"` + FinishTime time.Time `json:"finishTime"` + CreateTime time.Time `json:"createTime,"` +} + +type MatchFrame struct { + Distance float64 `json:"distance"` + Position int `json:"position"` + Timestamp float64 `json:"timestamp"` +} + +type VideoClip struct { + Clip bool `json:"clip"` + ClipNum int `json:"clipNum"` + Distance float64 `json:"distance"` + FrameNum int `json:"frameNum"` + InputEndPos int `json:"inputEndPos"` + InputEndTime float64 `json:"inputEndTime"` + InputStartPos int `json:"inputStartPos"` + InputStartTime float64 `json:"inputStartTime"` + InputSumTime float64 `json:"inputSumTime"` + MatchNum int `json:"matchNum"` + OutputEndPos int `json:"outputEndPos"` + OutputEndTime float64 `json:"outputEndTime"` + OutputStartPos int `json:"outputStartPos"` + OutputStartTime float64 `json:"outputStartTime"` + OutputSumTime float64 `json:"outputSumTime"` + PreIdx int `json:"preIdx"` +} + +type SearchTaskResult struct { + Cover string `json:"cover"` + Description string `json:"description"` + Distance float64 `json:"distance"` + Duration float64 `json:"duration"` + ID string `json:"id"` + Name string `json:"name"` + Score float64 `json:"score"` + Source string `json:"source"` + Type string `json:"type"` + Frames []MatchFrame `json:"frames"` + Clips []VideoClip `json:"clips"` +} + +type SearchTaskResultResponse struct { + BaseResponse + Results []SearchTaskResult `json:"results"` + TagResults []SearchTaskResult `json:"tagResults"` +} diff --git a/bce-sdk-go/services/mms/client.go b/bce-sdk-go/services/mms/client.go new file mode 100644 index 0000000..5636f10 --- /dev/null +++ b/bce-sdk-go/services/mms/client.go @@ -0,0 +1,212 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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 mms + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/mms/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "mms." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN +) + +// Client of MMS service +type Client struct { + *bce.BceClient +} + +// NewClient make the MMS service client +func NewClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// InsertVideo - insert a video, and create a video recognize task +// PARAMS: +// - lib: vedio library name +// - args: vedio source and description +// +// RETURN: +// - BaseResponse: the result of insert a video +// - error: nil if success otherwise the specific error +func (c *Client) InsertVideo(lib string, args *api.BaseRequest) (*api.BaseResponse, error) { + return api.InsertVideo(c, lib, args) +} + +// GetInsertVideoResult - get video insert result and video recognize task result +// PARAMS: +// - lib: vedio library name +// - source: vedio source +// +// RETURN: +// - BaseResponse: the result of get result +// - error: nil if success otherwise the specific error +func (c *Client) GetInsertVideoResult(lib, source string) (*api.BaseResponse, error) { + return api.GetInsertVideoResult(c, lib, source) +} + +// GetInsertVideoResultById - get video insert result and video recognize task result by id +// PARAMS: +// - libId: vedio library id +// - mediaId: vedio id +// +// RETURN: +// - BaseResponse: the result of get result +// - error: nil if success otherwise the specific error +func (c *Client) GetInsertVideoResultById(libId, mediaId string) (*api.BaseResponse, error) { + return api.GetInsertVideoResultById(c, libId, mediaId) +} + +// DeleteVideo - delete a video +// PARAMS: +// - lib: vedio library name +// - source: vedio source +// +// RETURN: +// - BaseResponse: the result of delete video +// - error: nil if success otherwise the specific error +func (c *Client) DeleteVideo(lib, source string) (*api.BaseResponse, error) { + return api.DeleteVideo(c, lib, source) +} + +// DeleteVideoById - delete a video +// PARAMS: +// - libId: video library id +// - mediaId: video id +// +// RETURN: +// - BaseResponse: the result of delete video +// - error: nil if success otherwise the specific error +func (c *Client) DeleteVideoById(libId, mediaId string) (*api.BaseResponse, error) { + return api.DeleteVideoById(c, libId, mediaId) +} + +// InsertImage - insert a image +// PARAMS: +// - lib: image library name +// - args: image source and description +// +// RETURN: +// - BaseResponse: the result of insert a image +// - error: nil if success otherwise the specific error +func (c *Client) InsertImage(lib string, args *api.BaseRequest) (*api.BaseResponse, error) { + return api.InsertImage(c, lib, args) +} + +// DeleteImage - delete a image +// PARAMS: +// - lib: image library name +// - source: image source +// +// RETURN: +// - BaseResponse: the result of delete a image +// - error: nil if success otherwise the specific error +func (c *Client) DeleteImage(lib, source string) (*api.BaseResponse, error) { + return api.DeleteImage(c, lib, source) +} + +// DeleteImageById - delete a image +// PARAMS: +// - libId: image library id +// - mediaId: image id +// +// RETURN: +// - BaseResponse: the result of delete a image +// - error: nil if success otherwise the specific error +func (c *Client) DeleteImageById(libId, mediaId string) (*api.BaseResponse, error) { + return api.DeleteImageById(c, libId, mediaId) +} + +// SearchImageByImage - search images by a image +// PARAMS: +// - lib: image library name +// - args: image source and description +// +// RETURN: +// - BaseResponse: the result of search +// - error: nil if success otherwise the specific error +func (c *Client) SearchImageByImage(lib string, args *api.BaseRequest) (*api.SearchTaskResultResponse, error) { + return api.SearchImageByImage(c, lib, args) +} + +// SearchVideoByImage - search videos by a image +// PARAMS: +// - lib: video library name +// - args: image source and description +// +// RETURN: +// - BaseResponse: the result of search +// - error: nil if success otherwise the specific error +func (c *Client) SearchVideoByImage(lib string, args *api.BaseRequest) (*api.SearchTaskResultResponse, error) { + return api.SearchVideoByImage(c, lib, args) +} + +// SearchVideoByVideo - create a search videos by a video task +// PARAMS: +// - lib: video library name +// - args: video source and description +// +// RETURN: +// - BaseResponse: search task info +// - error: nil if success otherwise the specific error +func (c *Client) SearchVideoByVideo(lib string, args *api.BaseRequest) (*api.SearchTaskResultResponse, error) { + return api.SearchVideoByVideo(c, lib, args) +} + +// GetSearchVideoByVideoResult - get result of searching videos by video +// PARAMS: +// - lib: video library name +// - source: video source +// +// RETURN: +// - BaseResponse: the result of searching videos by video +// - error: nil if success otherwise the specific error +func (c *Client) GetSearchVideoByVideoResult(lib, source string) (*api.SearchTaskResultResponse, error) { + return api.GetSearchVideoByVideoResult(c, lib, source) +} + +// GetSearchVideoByVideoResultById - get result of searching videos by taskId +// PARAMS: +// - lib: video library name +// - taskId: search task id +// +// RETURN: +// - BaseResponse: the result of searching videos by video +// - error: nil if success otherwise the specific error +func (c *Client) GetSearchVideoByVideoResultById(lib, taskId string) (*api.SearchTaskResultResponse, error) { + return api.GetSearchVideoByVideoResultById(c, lib, taskId) +} diff --git a/bce-sdk-go/services/mms/client_test.go b/bce-sdk-go/services/mms/client_test.go new file mode 100644 index 0000000..72e64ce --- /dev/null +++ b/bce-sdk-go/services/mms/client_test.go @@ -0,0 +1,180 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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 mms + +import ( + "testing" + + "github.com/baidubce/bce-sdk-go/services/mms/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var CLIENT *Client + +const ( + AK = "" + SK = "" + VIDEO_LIB = "" + VIDEO_LIB_ID = "" + IMAGE_LIB = "" + IMAGE_LIB_ID = "" + VIDEO_SOURCE = "http://xxx.mp4" + IMAGE_SOURCE = "http://xxx.png" + ENDPOINT = "http://xxx" + VIDEO_ID = "" + IMAGE_ID = "" + TASK_ID = "" +) + +func init() { + CLIENT, _ = NewClient(AK, SK, ENDPOINT) + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) +} + +func TestInsertVideo(t *testing.T) { + args := &api.BaseRequest{Source: VIDEO_SOURCE, Notification: "test", Description: "..."} + res, err := CLIENT.InsertVideo(VIDEO_LIB, args) + if err != nil { + t.Fatalf("InsertVideo failed: %s", err) + } + if res == nil { + t.Fatal("TestInsertVideo Failed. ") + } +} + +func TestGetInsertVideoResult(t *testing.T) { + res, err := CLIENT.GetInsertVideoResult(VIDEO_LIB, VIDEO_SOURCE) + if err != nil { + t.Fatalf("TestGetInsertVideoResult failed: %s", err) + } + if res.Source != VIDEO_SOURCE { + t.Fatal("TestGetInsertVideoResult Failed.") + } +} + +func TestGetInsertVideoResultById(t *testing.T) { + res, err := CLIENT.GetInsertVideoResultById(VIDEO_LIB_ID, VIDEO_ID) + if err != nil { + t.Fatalf("TestGetInsertVideoResult failed: %s", err) + } + if res.Source != VIDEO_SOURCE { + t.Fatal("TestGetInsertVideoResult Failed.") + } +} + +func TestDeleteVideo(t *testing.T) { + res, err := CLIENT.DeleteVideo(VIDEO_LIB, VIDEO_SOURCE) + if err != nil { + t.Fatalf("TestDeleteVideo failed: %s", err) + } + if res == nil { + t.Fatal("TestDeleteVideo Failed.") + } +} + +func TestDeleteVideoById(t *testing.T) { + res, err := CLIENT.DeleteVideoById(VIDEO_LIB_ID, VIDEO_ID) + if err != nil { + t.Fatalf("DeleteVideoById failed: %s", err) + } + if res == nil { + t.Fatal("DeleteVideoById Failed.") + } +} + +func TestInsertImage(t *testing.T) { + args := &api.BaseRequest{Source: IMAGE_SOURCE, Notification: "test", Description: "..."} + res, err := CLIENT.InsertImage(IMAGE_LIB, args) + if err != nil { + t.Fatalf("TestInsertImage failed: %s", err) + } + if res == nil { + t.Fatal("TestInsertImage Failed. ") + } +} + +func TestDeleteImage(t *testing.T) { + res, err := CLIENT.DeleteVideo(IMAGE_LIB, IMAGE_SOURCE) + if err != nil { + t.Fatalf("TestDeleteImage failed: %s", err) + } + if res == nil { + t.Fatal("TestDeleteImage Failed.") + } +} + +func TestDeleteImageById(t *testing.T) { + res, err := CLIENT.DeleteVideoById(IMAGE_LIB_ID, IMAGE_ID) + if err != nil { + t.Fatalf("TestDeleteImageById failed: %s", err) + } + if res == nil { + t.Fatal("TestDeleteImageById Failed.") + } +} + +func TestSearchImageByImage(t *testing.T) { + args := &api.BaseRequest{Source: IMAGE_SOURCE, Notification: "test", Description: "..."} + res, err := CLIENT.SearchImageByImage(IMAGE_LIB, args) + if err != nil { + t.Fatalf("TestSearchImageByImage failed: %s", err) + } + if res == nil { + t.Fatal(res) + } +} + +func TestSearchVideoByImage(t *testing.T) { + args := &api.BaseRequest{Source: IMAGE_SOURCE, Notification: "test", Description: "..."} + res, err := CLIENT.SearchVideoByImage(VIDEO_LIB, args) + if err != nil { + t.Fatalf("TestSearchVideoByImage failed: %s", err) + } + if res == nil { + t.Fatal(res) + } +} + +func TestSearchVideoByVideo(t *testing.T) { + args := &api.BaseRequest{Source: VIDEO_SOURCE, Notification: "test", Description: "..."} + res, err := CLIENT.SearchVideoByVideo(VIDEO_LIB, args) + if err != nil { + t.Fatalf("TestSearchVideoByVideo failed: %s", err) + } + if res == nil { + t.Fatal(res) + } +} + +func TestGetSearchVideoByVideoResult(t *testing.T) { + res, err := CLIENT.GetSearchVideoByVideoResult(VIDEO_LIB, VIDEO_SOURCE) + if err != nil { + t.Fatalf("TestGetSearchVideoByVideoResult failed: %s", err) + } + if res == nil { + t.Fatal(res) + } +} + +func TestGetSearchVideoByVideoResultById(t *testing.T) { + res, err := CLIENT.GetSearchVideoByVideoResultById(VIDEO_LIB, TASK_ID) + if err != nil { + t.Fatalf("TestGetSearchVideoByVideoResultById failed: %s", err) + } + if res == nil { + t.Fatal(res) + } +} diff --git a/bce-sdk-go/services/quotacenter/client.go b/bce-sdk-go/services/quotacenter/client.go new file mode 100644 index 0000000..a02dc4e --- /dev/null +++ b/bce-sdk-go/services/quotacenter/client.go @@ -0,0 +1,76 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for QuotaCenter service + +// Package quotacenter defines the QuotaCenter services of BCE. The supported APIs are all defined in sub-package +package quotacenter + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "quota-center.baidubce.com" + + BASE_QUOTA_CENTER_URL = "/quota_center" + + BASE_PRODUCT_URL = "/info/product" + + BASE_INFO_URL = "/info" + + BASE_REGION_URL = "/info/region" + + BASE_APPLY_URL = "/apply" +) + +// Client of QUOTA_CENTER service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getQuotaCenterUri() string { + return URI_PREFIX + BASE_QUOTA_CENTER_URL +} + +func getProductUri() string { + return getQuotaCenterUri() + BASE_PRODUCT_URL +} + +func getInfoUri() string { + return getQuotaCenterUri() + BASE_INFO_URL +} + +func getRegionUri() string { + return getQuotaCenterUri() + BASE_REGION_URL +} + +func getApplyUri() string { + return getQuotaCenterUri() + BASE_APPLY_URL +} + +func getApplyUriWithId(id string) string { + return getApplyUri() + bce.URI_PREFIX + id +} diff --git a/bce-sdk-go/services/quotacenter/client_test.go b/bce-sdk-go/services/quotacenter/client_test.go new file mode 100644 index 0000000..dd35bfb --- /dev/null +++ b/bce-sdk-go/services/quotacenter/client_test.go @@ -0,0 +1,135 @@ +package quotacenter + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + QUOTA_CENTER_CLIENT *Client +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + QUOTA_CENTER_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +func TestClient_ListProducts(t *testing.T) { + args := &ProductQueryArgs{} + result, err := QUOTA_CENTER_CLIENT.ListProducts(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } + +} + +func TestClient_ListRegions(t *testing.T) { + args := &RegionQueryArgs{ + ProductType: "EIP", + ServiceType: "EIP_BP", + Type: "QUOTA", + } + result, err := QUOTA_CENTER_CLIENT.ListRegions(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_QuotaCenterQuery(t *testing.T) { + args := &QuotaCenterQueryArgs{ + ServiceType: "EIP", + Type: "QUOTA", + Region: "su", + } + result, err := QUOTA_CENTER_CLIENT.QuotaCenterQuery(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_InfoQuery(t *testing.T) { + args := &InfoQueryArgs{ + Region: "bj", + } + result, err := QUOTA_CENTER_CLIENT.InfoQuery(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_Apply(t *testing.T) { + args := &ApplicationCreateModel{ + ProductType: "EIP", + ServiceType: "EIP", + Region: "bj", + Name: "eipInstanceQuota", + Value: "280", + Reason: "we need more again", + } + result, err := QUOTA_CENTER_CLIENT.Apply(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_ApplicationQuery(t *testing.T) { + args := &ApplicationQueryArgs{ + Status: "EFFECTED", + } + result, err := QUOTA_CENTER_CLIENT.ApplicationQuery(args) + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} + +func TestClient_ApplicationDetail(t *testing.T) { + result, err := QUOTA_CENTER_CLIENT.ApplicationDetail("app-uh4eaumggx4q") + if err != nil { + fmt.Println(err) + } else { + r, _ := json.Marshal(result) + fmt.Println(string(r)) + } +} diff --git a/bce-sdk-go/services/quotacenter/config.json b/bce-sdk-go/services/quotacenter/config.json new file mode 100644 index 0000000..2c90a99 --- /dev/null +++ b/bce-sdk-go/services/quotacenter/config.json @@ -0,0 +1,5 @@ +{ + "AK": "", + "SK": "", + "Endpoint": "" +} diff --git a/bce-sdk-go/services/quotacenter/model.go b/bce-sdk-go/services/quotacenter/model.go new file mode 100644 index 0000000..5e8a7d3 --- /dev/null +++ b/bce-sdk-go/services/quotacenter/model.go @@ -0,0 +1,148 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model +package quotacenter + +type QuotaCenterQueryArgs struct { + Type string `json:"type"` + ServiceType string `json:"serviceType"` + Region string `json:"region"` + Name string `json:"name,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListQuotaResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + Result []QuotaModel `json:"result"` +} + +type QuotaModel struct { + ProductType string `json:"productType"` + ServiceType string `json:"serviceType"` + Type string `json:"type"` + Region string `json:"region"` + Name string `json:"name"` + Description string `json:"description"` + Value string `json:"value"` + Used string `json:"used"` +} + +type ProductQueryArgs struct { + ProductType string `json:"productType,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListProductResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + Result []ProductModel `json:"result"` +} + +type ProductModel struct { + ProductType string `json:"productType"` + ServiceType string `json:"serviceType"` +} + +type RegionQueryArgs struct { + ProductType string `json:"productType"` + ServiceType string `json:"serviceType"` + Type string `json:"type"` +} + +type ListRegionResult struct { + Regions []string `json:"regions"` +} + +type InfoQueryArgs struct { + ServiceType string `json:"serviceType,omitempty"` + Region string `json:"region,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListInfoResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + Result []InfoModel `json:"result"` +} + +type InfoModel struct { + ProductType string `json:"productType"` + ServiceType string `json:"serviceType"` + Type string `json:"type"` + Region string `json:"region"` + Name string `json:"name"` + Description string `json:"description"` + Apply bool `json:"apply"` +} + +type ApplicationCreateModel struct { + ProductType string `json:"productType"` + ServiceType string `json:"serviceType"` + Type string `json:"type"` + Region string `json:"region"` + Name string `json:"name"` + Value string `json:"value"` + Reason string `json:"reason"` +} + +type IdModel struct { + id string `json:"id"` +} + +type ApplicationQueryArgs struct { + Id string `json:"id,omitempty"` + Name string `json:"name,omitempty"` + Status string `json:"status,omitempty"` + ProductType string `json:"status,productType"` + ServiceType string `json:"serviceType"` + Type string `json:"type"` + Region string `json:"region"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListApplicationResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + Result []ApplicationModel `json:"result"` +} + +type ApplicationModel struct { + Id string `json:"id"` + ProductType string `json:"productType"` + ServiceType string `json:"serviceType"` + Type string `json:"type"` + Region string `json:"region"` + Name string `json:"name"` + Value string `json:"value"` + Reason string `json:"reason"` + Status string `json:"status"` + Conclusion string `json:"conclusion"` + CreateTime string `json:"createTime"` + EffectTime string `json:"effectTime,omitempty"` + ApproveTime string `json:"approveTime,omitempty"` +} diff --git a/bce-sdk-go/services/quotacenter/quota_center.go b/bce-sdk-go/services/quotacenter/quota_center.go new file mode 100644 index 0000000..c73ec36 --- /dev/null +++ b/bce-sdk-go/services/quotacenter/quota_center.go @@ -0,0 +1,238 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// quota_center.go - the quota_center APIs definition supported by the QUOTA_CENTER service +package quotacenter + +import ( + "errors" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListProducts - list quota center support products. +// +// PARAMS: +// - args: the arguments to list products. +// +// RETURNS: +// - *ListProductResult: the result of list products. +// - error: nil if success otherwise the specific error +func (c *Client) ListProducts(args *ProductQueryArgs) (*ListProductResult, error) { + if args == nil { + args = &ProductQueryArgs{} + } + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + result := &ListProductResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getProductUri()). + WithQueryParamFilter("productType", args.ProductType). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// ListRegions - list quota center support regions with the specific parameters. +// +// PARAMS: +// - args: the arguments to list regions. +// +// RETURNS: +// - *ListRegionResult: the result of regions. +// - error: nil if success otherwise the specific error +func (c *Client) ListRegions(args *RegionQueryArgs) (*ListRegionResult, error) { + if args == nil { + args = &RegionQueryArgs{} + } + result := &ListRegionResult{} + if len(args.ProductType) == 0 { + return nil, errors.New("productType should not be empty") + } + if len(args.ServiceType) == 0 { + return nil, errors.New("serviceType should not be empty") + } + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRegionUri()). + WithQueryParamFilter("productType", args.ProductType). + WithQueryParamFilter("serviceType", args.ServiceType). + WithQueryParamFilter("type", args.Type). + WithResult(result). + Do() + + return result, err +} + +// QuotaCenterQuery - query from quota_center with the specific parameters +// +// PARAMS: +// - args: the arguments to query quota_center +// +// RETURNS: +// - *ListQuotaResult: the result of query from quota_center. +// - error: nil if success otherwise the specific error +func (c *Client) QuotaCenterQuery(args *QuotaCenterQueryArgs) (*ListQuotaResult, error) { + if args == nil { + args = &QuotaCenterQueryArgs{} + } + if len(args.ServiceType) == 0 { + return nil, errors.New("serviceType should not be empty") + } + if len(args.Region) == 0 { + return nil, errors.New("region should not be empty") + } + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + result := &ListQuotaResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getQuotaCenterUri()). + WithQueryParamFilter("type", args.Type). + WithQueryParamFilter("serviceType", args.ServiceType). + WithQueryParamFilter("region", args.Region). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// InfoQuery - query basic infos from quota_center with the specific parameters +// +// PARAMS: +// - args: the arguments to query infos. +// +// RETURNS: +// - *ListInfoResult: the result of infos from quota_center. +// - error: nil if success otherwise the specific error +func (c *Client) InfoQuery(args *InfoQueryArgs) (*ListInfoResult, error) { + if args == nil { + args = &InfoQueryArgs{} + } + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + result := &ListInfoResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInfoUri()). + WithQueryParamFilter("serviceType", args.ServiceType). + WithQueryParamFilter("region", args.Region). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// Apply - apply quota or whitelist with the specific parameters +// +// PARAMS: +// - args: the arguments to apply. +// RETURNS: +// - *IdModel: the id of application. +// - error: nil if success otherwise the specific error + +func (c *Client) Apply(args *ApplicationCreateModel) (*IdModel, error) { + if args == nil { + args = &ApplicationCreateModel{} + } + + result := &IdModel{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithURL(getApplyUri()). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ApplicationQuery - query applications from quota_center with the specific parameters +// +// PARAMS: +// - args: the arguments to query application. +// +// RETURNS: +// - *ListApplicationResult: the result of applications. +// - error: nil if success otherwise the specific error +func (c *Client) ApplicationQuery(args *ApplicationQueryArgs) (*ListApplicationResult, error) { + if args == nil { + args = &ApplicationQueryArgs{} + } + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + result := &ListApplicationResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getApplyUri()). + WithQueryParamFilter("id", args.Id). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("status", args.Status). + WithQueryParamFilter("productType", args.ProductType). + WithQueryParamFilter("serviceType", args.ServiceType). + WithQueryParamFilter("type", args.Type). + WithQueryParamFilter("region", args.Region). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// ApplicationDetail - query application detail from quota_center with id. +// +// PARAMS: +// - id: the application's id. +// +// RETURNS: +// - *ApplicationModel: the result of application. +// - error: nil if success otherwise the specific error +func (c *Client) ApplicationDetail(id string) (*ApplicationModel, error) { + if len(id) == 0 { + return nil, fmt.Errorf("please set id argment") + } + + result := &ApplicationModel{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getApplyUriWithId(id)). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/rds/client.go b/bce-sdk-go/services/rds/client.go new file mode 100644 index 0000000..2341568 --- /dev/null +++ b/bce-sdk-go/services/rds/client.go @@ -0,0 +1,50 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for RDS service + +// Package rds defines the RDS services of BCE. The supported APIs are all defined in sub-package +package rds + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + DEFAULT_ENDPOINT = "rds.bj.baidubce.com" + REQUEST_RDS_URL = "/instance" +) + +// Client of RDS service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getRdsUri() string { + return URI_PREFIX + REQUEST_RDS_URL +} + +func getRdsUriWithInstanceId(instanceId string) string { + return URI_PREFIX + REQUEST_RDS_URL + "/" + instanceId +} diff --git a/bce-sdk-go/services/rds/client_test.go b/bce-sdk-go/services/rds/client_test.go new file mode 100644 index 0000000..c60781f --- /dev/null +++ b/bce-sdk-go/services/rds/client_test.go @@ -0,0 +1,1179 @@ +package rds + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + RDS_CLIENT *Client + RDS_ID = "rds-W3NYp4m9" + ORDERID string + // set this value before start test + ACCOUNT_NAME = "baidu" + PASSWORD = "baidu@123" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +const ( + SDK_NAME_PREFIX = "sdk_rds_" +) + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 1; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + RDS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateRds(t *testing.T) { + id := strconv.FormatInt(time.Now().Unix(), 10) + args := &CreateRdsArgs{ + Engine: "mysql", + EngineVersion: "5.6", + Category: "Standard", + InstanceName: SDK_NAME_PREFIX + id, + CpuCount: 1, + DiskIoType: "normal_io", + MemoryCapacity: 1, + VolumeCapacity: 5, + VpcId: "vpc-it3v6qt3jhvj", + ZoneNames: []string{"cn-bj-d"}, + Subnets: []SubnetMap{ + { + ZoneName: "cn-bj-d", + SubnetId: "sbn-na4tmg4v11hs", + }, + }, + Billing: Billing{ + PaymentTiming: "Postpaid", + }, + ClientToken: getClientToken(), + IsDirectPay: true, + } + result, err := RDS_CLIENT.CreateRds(args) + + ExpectEqual(t.Errorf, nil, err) + + RDS_ID = result.InstanceIds[0] + ORDERID = result.OrderId + fmt.Println("RDS: ", RDS_ID) + fmt.Println("ORDERID: ", ORDERID) + // isAvailable(RDS_ID) +} + +func TestClient_ResizeRds(t *testing.T) { + args := &ResizeRdsArgs{ + CpuCount: 1, + MemoryCapacity: 2, + VolumeCapacity: 10, + } + err := RDS_CLIENT.ResizeRds(RDS_ID, args) + ExpectEqual(t.Errorf, nil, err) + time.Sleep(30 * time.Second) + isAvailable(RDS_ID) +} + +func TestClient_ListRds(t *testing.T) { + args := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(args) + ExpectEqual(t.Errorf, nil, err) + jsonData, err := json.Marshal(result) + fmt.Println(string(jsonData)) + for _, e := range result.Instances { + if e.InstanceId == RDS_ID { + ExpectEqual(t.Errorf, "MySQL", e.Engine) + ExpectEqual(t.Errorf, "5.6", e.EngineVersion) + } + } +} + +func TestClient_GetDetail(t *testing.T) { + result, err := RDS_CLIENT.GetDetail("rds-W3NYp4m9") + re, error := json.Marshal(result) + fmt.Print(error) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "MySQL", result.Engine) + ExpectEqual(t.Errorf, "5.6", result.EngineVersion) +} + +func TestClient_CreateAccount(t *testing.T) { + + args := &CreateAccountArgs{ + AccountName: ACCOUNT_NAME, + Password: PASSWORD, + ClientToken: getClientToken(), + } + + isAvailable(RDS_ID) + err := RDS_CLIENT.CreateAccount(RDS_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListAccount(t *testing.T) { + isAvailable(RDS_ID) + result, err := RDS_CLIENT.ListAccount(RDS_ID) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Accounts { + if e.AccountName == ACCOUNT_NAME { + ExpectEqual(t.Errorf, "Available", e.Status) + } + } +} + +func TestClient_GetAccount(t *testing.T) { + result, err := RDS_CLIENT.GetAccount(RDS_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Available", result.Status) +} + +func TestClient_ModifyAccountDesc(t *testing.T) { + args := &ModifyAccountDesc{ + Remark: "test", + } + err := RDS_CLIENT.ModifyAccountDesc(RDS_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteAccount(t *testing.T) { + err := RDS_CLIENT.DeleteAccount(RDS_ID, ACCOUNT_NAME) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateAccountPassword(t *testing.T) { + args := &UpdatePasswordArgs{ + Password: "test", + } + err := RDS_CLIENT.UpdateAccountPassword(RDS_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_UpdateAccountPrivileges(t *testing.T) { + args := &UpdateAccountPrivileges{ + DatabasePrivileges: []DatabasePrivilege{{ + DbName: "test_db", + AuthType: "ReadOnly", + }}, + } + err := RDS_CLIENT.UpdateAccountPrivileges(RDS_ID, ACCOUNT_NAME, args) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_CreateReadReplica(t *testing.T) { + args := &CreateReadReplicaArgs{ + SourceInstanceId: RDS_ID, + CpuCount: 1, + MemoryCapacity: 2, + VolumeCapacity: 10, + Billing: Billing{ + PaymentTiming: "Postpaid", + }, + ClientToken: getClientToken(), + } + time.Sleep(30 * time.Second) + isAvailable(RDS_ID) + _, err := RDS_CLIENT.CreateReadReplica(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateRdsProxy(t *testing.T) { + args := &CreateRdsProxyArgs{ + SourceInstanceId: RDS_ID, + NodeAmount: 2, + Billing: Billing{ + PaymentTiming: "Postpaid", + }, + ClientToken: getClientToken(), + } + isAvailable(RDS_ID) + _, err := RDS_CLIENT.CreateRdsProxy(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RebootInstance(t *testing.T) { + isAvailable(RDS_ID) + err := RDS_CLIENT.RebootInstance(RDS_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateInstanceName(t *testing.T) { + isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + args := &UpdateInstanceNameArgs{ + InstanceName: e.InstanceName + "_new", + } + err := RDS_CLIENT.UpdateInstanceName(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_ModifySyncMode(t *testing.T) { + isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + args := &ModifySyncModeArgs{ + SyncMode: "Async", + } + err := RDS_CLIENT.ModifySyncMode(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_ModifyEndpoint(t *testing.T) { + isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + args := &ModifyEndpointArgs{ + Address: "newsdkrds", + } + err := RDS_CLIENT.ModifyEndpoint(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_ModifyPublicAccess(t *testing.T) { + isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + args := &ModifyPublicAccessArgs{ + PublicAccess: false, + } + err := RDS_CLIENT.ModifyPublicAccess(e.InstanceId, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_ModifyBackupPolicy(t *testing.T) { + isAvailable(RDS_ID) + modifyBackupPolicyArgs := &ModifyBackupPolicyArgs{ + ExpireInDays: 10, + BackupDays: "0,1,2,3,4,5,6", + BackupTime: "17:00:00Z", + Persistent: true, + } + err := RDS_CLIENT.ModifyBackupPolicy(RDS_ID, modifyBackupPolicyArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBackupList(t *testing.T) { + isAvailable(RDS_ID) + getBackupListArgs := &GetBackupListArgs{ + Marker: RDS_ID, + MaxKeys: 100, + } + result, err := RDS_CLIENT.GetBackupList(RDS_ID, getBackupListArgs) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBackupDetail(t *testing.T) { + isAvailable(RDS_ID) + result, err := RDS_CLIENT.GetBackupDetail(RDS_ID, "1691679661534780403") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteBackup(t *testing.T) { + isAvailable(RDS_ID) + err := RDS_CLIENT.DeleteBackup(RDS_ID, "1691734023130272802") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBinlogList(t *testing.T) { + result, err := RDS_CLIENT.GetBinlogList(RDS_ID, "2022-07-12T23:59:59Z") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetBinlogInfo(t *testing.T) { + result, err := RDS_CLIENT.GetBinlogInfo(RDS_ID, "1691734023130272802", "1800") + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RecoveryToSourceInstanceByDatetime(t *testing.T) { + isAvailable(RDS_ID) + recoveryByDatetimeArgs := &RecoveryByDatetimeArgs{ + Datetime: "2022-01-11T16:05:52Z", + Data: []RecoveryData{ + { + DbName: "test_db", + NewDbname: "new_test_db", + RestoreMode: "database", + Tables: []TableData{ + { + TableName: "table_name", + NewTablename: "new_table_name", + }, + }, + }, + }, + } + err := RDS_CLIENT.RecoveryToSourceInstanceByDatetime(RDS_ID, recoveryByDatetimeArgs) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RecoveryToSourceInstanceBySnapshot(t *testing.T) { + isAvailable(RDS_ID) + recoveryBySnapshotArgs := &RecoveryBySnapshotArgs{ + SnapshotId: "1691734023130272802", + Data: []RecoveryData{ + { + DbName: "test_db", + NewDbname: "new_test_db", + RestoreMode: "database", + Tables: []TableData{ + { + TableName: "table_name", + NewTablename: "new_table_name", + }, + }, + }, + }, + } + err := RDS_CLIENT.RecoveryToSourceInstanceBySnapshot(RDS_ID, recoveryBySnapshotArgs) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_GetZoneList(t *testing.T) { + isAvailable(RDS_ID) + _, err := RDS_CLIENT.GetZoneList() + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListSubnets(t *testing.T) { + isAvailable(RDS_ID) + args := &ListSubnetsArgs{ + VpcId: "vpc-it3v6qt3jhvj", + ZoneName: "cn-bj-d", + } + _, err := RDS_CLIENT.ListSubnets(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSecurityIps(t *testing.T) { + //isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + res, err := RDS_CLIENT.GetSecurityIps(e.InstanceId) + fmt.Println(res.SecurityIps) + fmt.Println(res.Etag) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_SecurityIps(t *testing.T) { + //isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + res, err := RDS_CLIENT.GetSecurityIps(e.InstanceId) + ExpectEqual(t.Errorf, nil, err) + args := &UpdateSecurityIpsArgs{ + SecurityIps: []string{ + "%", + "192.0.0.1", + "192.0.0.2", + }, + } + er := RDS_CLIENT.UpdateSecurityIps(e.InstanceId, res.Etag, args) + ExpectEqual(t.Errorf, nil, er) + } + } +} + +func TestClient_ListParameters(t *testing.T) { + //isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{ + Marker: "0", + MaxKeys: 100, + } + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + res, err := RDS_CLIENT.ListParameters(e.InstanceId) + data, _ := json.Marshal(res) + fmt.Println(string(data)) + fmt.Println(res.Etag) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_UpdateParameter(t *testing.T) { + //isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + res, err := RDS_CLIENT.ListParameters(e.InstanceId) + ExpectEqual(t.Errorf, nil, err) + args := &UpdateParameterArgs{ + Parameters: []KVParameter{ + { + Name: "connect_timeout", + Value: "15", + }, + }, + } + er := RDS_CLIENT.UpdateParameter(e.InstanceId, res.Etag, args) + ExpectEqual(t.Errorf, nil, er) + } + } +} + +func TestClient_ParameterHistory(t *testing.T) { + result, err := RDS_CLIENT.ParameterHistory(RDS_ID) + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteRds(t *testing.T) { + time.Sleep(30 * time.Second) + isAvailable(RDS_ID) + listRdsArgs := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRds(listRdsArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Available" == e.InstanceStatus { + err := RDS_CLIENT.DeleteRds(e.InstanceId) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func getClientToken() string { + return util.NewUUID() +} + +func isAvailable(instanceId string) { + for { + result, err := RDS_CLIENT.GetDetail(instanceId) + if err == nil && result.InstanceStatus == "Available" { + break + } + } +} + +func TestClient_AutoRenew(t *testing.T) { + err := RDS_CLIENT.AutoRenew(&AutoRenewArgs{ + AutoRenewTimeUnit: "month", + AutoRenewTime: 1, + InstanceIds: []string{ + "rds-rbmh6gJl", + }, + }) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowLogDownloadTaskList(t *testing.T) { + res, err := RDS_CLIENT.GetSlowLogDownloadTaskList("rdsmv5aumcrpynd", "2022-11-14T16:00:00Z") + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowLogDownloadDetail(t *testing.T) { + res, err := RDS_CLIENT.GetSlowLogDownloadDetail("rds-qJG8sHPY", "slowlog.202211141158", "60") + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_newApi(t *testing.T) { + result, err := RDS_CLIENT.Request("GET", "/v1/instance/rds-TSIlv3Sd/performance/processlist", nil) + ExpectEqual(t.Errorf, nil, err) + if result != nil { + fmt.Println(result) + } +} + +func TestClient_UpdateMaintainTime(t *testing.T) { + err := RDS_CLIENT.UpdateMaintainTime(RDS_ID, &MaintainTimeArgs{ + MaintainStartTime: "14:00:00", + MaintainDuration: 2, + }) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ConfigDiskAutoResize(t *testing.T) { + err := RDS_CLIENT.ConfigDiskAutoResize(RDS_ID, "open", &DiskAutoResizeArgs{ + FreeSpaceThreshold: 10, + DiskMaxLimit: 2000, + }) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetAutoResizeConfig(t *testing.T) { + res, err := RDS_CLIENT.GetAutoResizeConfig(RDS_ID) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EnableAutoExpansion(t *testing.T) { + res, err := RDS_CLIENT.EnableAutoExpansion(RDS_ID) + fmt.Print(res) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_AzoneMigration(t *testing.T) { + err := RDS_CLIENT.AzoneMigration(RDS_ID, &AzoneMigration{ + MasterAzone: "cn-bj-d", + BackupAzone: "cn-bj-e", + ZoneNames: []string{"cn-bj-d", "cn-bj-e"}, + Subnets: []SubnetMap{ + { + ZoneName: "cn-bj-d", + SubnetId: "sbn-nedt51qre6r2", + }, + { + ZoneName: "cn-bj-e", + SubnetId: "sbn-hc20wss3idai", + }, + }, + EffectiveTime: "timewindow", + }) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateDatabasePort(t *testing.T) { + err := RDS_CLIENT.UpdateDatabasePort(RDS_ID, &UpdateDatabasePortArgs{ + EntryPort: 3309, + }) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListDatabases(t *testing.T) { + result, err := RDS_CLIENT.ListDatabases(RDS_ID) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ModifyDatabaseDesc(t *testing.T) { + args := &ModifyDatabaseDesc{ + Remark: "test", + } + err := RDS_CLIENT.ModifyDatabaseDesc(RDS_ID, "test_db", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteDatabase(t *testing.T) { + err := RDS_CLIENT.DeleteDatabase(RDS_ID, "test_db") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateDatabase(t *testing.T) { + + args := &CreateDatabaseArgs{ + CharacterSetName: "utf8", + DbName: "test_db", + Remark: "test_db", + AccountPrivileges: []AccountPrivilege{ + { + AccountName: "baidu", + AuthType: "ReadOnly", + }, + }, + } + + isAvailable(RDS_ID) + err := RDS_CLIENT.CreateDatabase(RDS_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_TaskList(t *testing.T) { + args := &TaskListArgs{ + InstanceId: RDS_ID, + } + result, err := RDS_CLIENT.TaskList(args) + re, _ := json.Marshal(result) + fmt.Println(string(re)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListRecyclerInstance(t *testing.T) { + args := &ListRdsArgs{} + result, err := RDS_CLIENT.ListRecyclerInstance(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RecyclerRecover(t *testing.T) { + args := &RecyclerRecoverArgs{ + InstanceIds: []string{RDS_ID}, + } + err := RDS_CLIENT.RecyclerRecover(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteRecyclerInstance(t *testing.T) { + err := RDS_CLIENT.DeleteRecyclerInstance(RDS_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateInstanceGroup(t *testing.T) { + args := &InstanceGroupArgs{ + Name: "test_group", + LeaderId: RDS_ID, + } + result, err := RDS_CLIENT.CreateInstanceGroup(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListInstanceGroup(t *testing.T) { + args := &ListInstanceGroupArgs{ + Manner: "page", + } + result, err := RDS_CLIENT.ListInstanceGroup(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupDetail(t *testing.T) { + result, err := RDS_CLIENT.InstanceGroupDetail("rdcg6034psv") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupCheckGtid(t *testing.T) { + args := &CheckGtidArgs{ + InstanceId: RDS_ID, + } + result, err := RDS_CLIENT.InstanceGroupCheckGtid(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupCheckPing(t *testing.T) { + args := &CheckPingArgs{ + SourceId: RDS_ID, + TargetId: RDS_ID, + } + result, err := RDS_CLIENT.InstanceGroupCheckPing(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupCheckData(t *testing.T) { + args := &CheckDataArgs{ + InstanceId: RDS_ID, + } + result, err := RDS_CLIENT.InstanceGroupCheckData(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupCheckVersion(t *testing.T) { + args := &CheckVersionArgs{ + LeaderId: RDS_ID, + FollowerId: RDS_ID, + } + result, err := RDS_CLIENT.InstanceGroupCheckVersion(args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateInstanceGroupName(t *testing.T) { + args := &InstanceGroupNameArgs{ + Name: "test_group_name", + } + err := RDS_CLIENT.UpdateInstanceGroupName("rdcg6034psv", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupAdd(t *testing.T) { + args := &InstanceGroupAddArgs{ + FollowerId: RDS_ID, + } + err := RDS_CLIENT.InstanceGroupAdd("rdcg6034psv", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupBatchAdd(t *testing.T) { + args := &InstanceGroupBatchAddArgs{ + FollowerIds: []string{RDS_ID}, + Name: "test_group_name", + LeaderId: RDS_ID, + } + err := RDS_CLIENT.InstanceGroupBatchAdd(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupForceChange(t *testing.T) { + args := &ForceChangeArgs{ + LeaderId: RDS_ID, + Force: 0, + } + result, err := RDS_CLIENT.InstanceGroupForceChange("rdcg6034psv", args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupLeaderChange(t *testing.T) { + args := &GroupLeaderChangeArgs{ + LeaderId: RDS_ID, + } + err := RDS_CLIENT.InstanceGroupLeaderChange("rdcg6034psv", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceGroupRemove(t *testing.T) { + err := RDS_CLIENT.InstanceGroupRemove("rdcg6034psv", RDS_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteInstanceGroup(t *testing.T) { + err := RDS_CLIENT.DeleteInstanceGroup("rdcg6034psv") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceMinorVersionList(t *testing.T) { + result, err := RDS_CLIENT.InstanceMinorVersionList(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InstanceUpgradeMinorVersion(t *testing.T) { + args := &UpgradeMinorVersionArgs{ + TargetMinorVersion: "5.7.38", + EffectiveTime: "immediate", + } + err := RDS_CLIENT.InstanceUpgradeMinorVersion(RDS_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_SlowSqlFlowStatus(t *testing.T) { + result, err := RDS_CLIENT.SlowSqlFlowStatus(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EnableSlowSqlFlow(t *testing.T) { + err := RDS_CLIENT.EnableSlowSqlFlow(RDS_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DisableSlowSqlFlow(t *testing.T) { + err := RDS_CLIENT.DisableSlowSqlFlow(RDS_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlList(t *testing.T) { + args := &GetSlowSqlArgs{} + result, err := RDS_CLIENT.GetSlowSqlList(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlBySqlId(t *testing.T) { + result, err := RDS_CLIENT.GetSlowSqlBySqlId(RDS_ID, "sqlidxxx") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlExplain(t *testing.T) { + result, err := RDS_CLIENT.GetSlowSqlExplain(RDS_ID, "sqlidxxx", "db1") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlStatsDigest(t *testing.T) { + args := &GetSlowSqlArgs{} + result, err := RDS_CLIENT.GetSlowSqlStatsDigest(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlDuration(t *testing.T) { + args := &GetSlowSqlDurationArgs{} + result, err := RDS_CLIENT.GetSlowSqlDuration(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlSource(t *testing.T) { + args := &GetSlowSqlSourceArgs{} + result, err := RDS_CLIENT.GetSlowSqlSource(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlSchema(t *testing.T) { + result, err := RDS_CLIENT.GetSlowSqlSchema(RDS_ID, "sqlidxxx", "db1") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlTable(t *testing.T) { + result, err := RDS_CLIENT.GetSlowSqlTable(RDS_ID, "sqlidxxx", "db1", "table1") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlIndex(t *testing.T) { + args := &GetSlowSqlIndexArgs{ + SqlId: "e9fa9802-0d0e-41b4-b3ba-6496466b6cad", + Schema: "db1", + Table: "table1", + } + result, err := RDS_CLIENT.GetSlowSqlIndex(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlTrend(t *testing.T) { + args := &GetSlowSqlTrendArgs{ + Start: "2023-05-05T05:30:13.000Z", + End: "2023-05-06T05:30:13.000Z", + } + result, err := RDS_CLIENT.GetSlowSqlTrend(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSlowSqlAdvice(t *testing.T) { + result, err := RDS_CLIENT.GetSlowSqlAdvice(RDS_ID, "sqlidxxx", "db1") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetDiskInfo(t *testing.T) { + result, err := RDS_CLIENT.GetDiskInfo(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetDbListSize(t *testing.T) { + result, err := RDS_CLIENT.GetDbListSize(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetTableListInfo(t *testing.T) { + args := &GetTableListArgs{ + DbName: "db1", + } + result, err := RDS_CLIENT.GetTableListInfo(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetKillSessionTypes(t *testing.T) { + result, err := RDS_CLIENT.GetKillSessionTypes(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSessionSummary(t *testing.T) { + result, err := RDS_CLIENT.GetSessionSummary(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSessionDetail(t *testing.T) { + args := &SessionDetailArgs{} + result, err := RDS_CLIENT.GetSessionDetail(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CheckKillSessionAuth(t *testing.T) { + args := &KillSessionAuthArgs{} + result, err := RDS_CLIENT.CheckKillSessionAuth(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetKillSessionHistory(t *testing.T) { + args := &KillSessionHistory{} + result, err := RDS_CLIENT.GetKillSessionHistory(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_KillSession(t *testing.T) { + args := &KillSessionArgs{} + result, err := RDS_CLIENT.KillSession(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSessionStatistics(t *testing.T) { + result, err := RDS_CLIENT.GetSessionStatistics(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetErrorLogStatus(t *testing.T) { + result, err := RDS_CLIENT.GetErrorLogStatus(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_EnableErrorLog(t *testing.T) { + result, err := RDS_CLIENT.EnableErrorLog(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DisableErrorLog(t *testing.T) { + result, err := RDS_CLIENT.DisableErrorLog(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetErrorLogList(t *testing.T) { + args := &ErrorLogListArgs{} + result, err := RDS_CLIENT.GetErrorLogList(RDS_ID, args) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSqlFilterList(t *testing.T) { + result, err := RDS_CLIENT.GetSqlFilterList(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetSqlFilterDetail(t *testing.T) { + result, err := RDS_CLIENT.GetSqlFilterDetail(RDS_ID, "83") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_AddSqlFilter(t *testing.T) { + args := &SqlFilterArgs{ + FilterType: "SELECT", + FilterKey: "123", + FilterLimit: 0, + } + err := RDS_CLIENT.AddSqlFilter(RDS_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateSqlFilter(t *testing.T) { + args := &SqlFilterArgs{ + FilterType: "SELECT", + FilterKey: "1234", + FilterLimit: 0, + } + err := RDS_CLIENT.UpdateSqlFilter(RDS_ID, "83", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_StartOrStopSqlFilter(t *testing.T) { + args := &StartOrStopSqlFilterArgs{ + Action: "OFF", + } + err := RDS_CLIENT.StartOrStopSqlFilter(RDS_ID, "83", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteSqlFilter(t *testing.T) { + err := RDS_CLIENT.DeleteSqlFilter(RDS_ID, "83") + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_IsAllowedSqlFilter(t *testing.T) { + result, err := RDS_CLIENT.IsAllowedSqlFilter(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ProcessKill(t *testing.T) { + args := &ProcessArgs{ + Ids: []int64{123}, + } + err := RDS_CLIENT.ProcessKill(RDS_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_InnodbStatus(t *testing.T) { + result, err := RDS_CLIENT.InnodbStatus(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ProcessList(t *testing.T) { + result, err := RDS_CLIENT.ProcessList(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_TransactionList(t *testing.T) { + result, err := RDS_CLIENT.TransactionList(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ConnectionList(t *testing.T) { + result, err := RDS_CLIENT.ConnectionList(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_FailInjectWhiteList(t *testing.T) { + result, err := RDS_CLIENT.FailInjectWhiteList() + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_AddToFailInjectWhiteList(t *testing.T) { + args := &FailInjectArgs{ + AppList: []string{RDS_ID}, + } + err := RDS_CLIENT.AddToFailInjectWhiteList(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RemoveFailInjectWhiteList(t *testing.T) { + args := &FailInjectArgs{ + AppList: []string{RDS_ID}, + } + err := RDS_CLIENT.RemoveFailInjectWhiteList(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_FailInjectStart(t *testing.T) { + result, err := RDS_CLIENT.FailInjectStart(RDS_ID) + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetOrderStatus(t *testing.T) { + result, err := RDS_CLIENT.GetOrderStatus("xxx") + jsonData, _ := json.Marshal(result) + fmt.Println(string(jsonData)) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/rds/model.go b/bce-sdk-go/services/rds/model.go new file mode 100644 index 0000000..c5347ef --- /dev/null +++ b/bce-sdk-go/services/rds/model.go @@ -0,0 +1,1212 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package rds + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type CreateRdsArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing"` + PurchaseCount int `json:"purchaseCount,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + Category string `json:"category,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + DiskIoType string `json:"diskIoType"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + BgwGroupId string `json:"bgwGroupId,omitempty"` + BgwGroupExclusive bool `json:"bgwGroupExclusive,omitempty"` + CharacterSetName string `json:"characterSetName,omitempty"` + LowerCaseTableNames int `json:"lowerCaseTableNames,omitempty"` + ParameterTemplateId string `json:"parameterTemplateId,omitempty"` + Ovip string `json:"ovip,omitempty"` + EntryPort string `json:"entryPort,omitempty"` + ReplicationType string `json:"replicationType,omitempty"` + ResourceGroupId string `json:"resourceGroupId,omitempty"` + InitialDataReference *InitialData `json:"initialDataReference,omitempty"` + Data []RecoveryToSourceInstanceModel `json:"data,omitempty"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation Reservation `json:"reservation,omitempty"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength,omitempty"` + ReservationTimeUnit string `json:"reservationTimeUnit,omitempty"` +} + +type SubnetMap struct { + ZoneName string `json:"zoneName"` + SubnetId string `json:"subnetId"` +} + +type InitialData struct { + InstanceId string `json:"instanceId,omitempty"` + ReferenceType string `json:"referenceType,omitempty"` + Datetime string `json:"datetime,omitempty"` + SnapshotId string `json:"snapshotId,omitempty"` +} + +type RecoveryToSourceInstanceModel struct { + RestoreMode string `json:"restoreMode,omitempty"` + DbName string `json:"dbName,omitempty"` + NewDbname string `json:"newDbname,omitempty"` + Tables []Table `json:"tables,omitempty"` +} + +type Table struct { + TableName string `json:"tableName,omitempty"` + NewTablename string `json:"newTablename,omitempty"` +} +type CreateResult struct { + InstanceIds []string `json:"instanceIds"` + OrderId string `json:"orderId"` +} + +type CreateReadReplicaArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing"` + PurchaseCount int `json:"purchaseCount,omitempty"` + SourceInstanceId string `json:"sourceInstanceId"` + InstanceName string `json:"instanceName,omitempty"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + DiskIoType string `json:"diskIoType,omitempty"` + Ovip string `json:"ovip,omitempty"` + EntryPort string `json:"entryPort,omitempty"` + ResourceGroupId string `json:"resourceGroupId,omitempty"` +} + +type CreateRdsProxyArgs struct { + ClientToken string `json:"-"` + Billing Billing `json:"billing"` + SourceInstanceId string `json:"sourceInstanceId"` + InstanceName string `json:"instanceName,omitempty"` + NodeAmount int `json:"nodeAmount"` + ZoneNames []string `json:"zoneNames,omitempty"` + VpcId string `json:"vpcId,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` + Ovip string `json:"ovip,omitempty"` + EntryPort string `json:"entryPort,omitempty"` + ResourceGroupId string `json:"resourceGroupId,omitempty"` +} + +type ListRdsArgs struct { + Marker string + MaxKeys int +} + +type Instance struct { + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + RdsMinorVersion string `json:"rdsMinorVersion"` + CharacterSetName string `json:"characterSetName"` + InstanceClass string `json:"instanceClass"` + AllocatedMemoryInMB int `json:"allocatedMemoryInMB"` + AllocatedMemoryInGB float64 `json:"allocatedMemoryInGB"` + AllocatedStorageInGB int `json:"allocatedStorageInGB"` + Category string `json:"category"` + InstanceStatus string `json:"instanceStatus"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + TotalStorageInGB int `json:"totalStorageInGB"` + NodeAmount int `json:"nodeAmount"` + UsedStorage float64 `json:"usedStorage"` + PublicAccessStatus string `json:"publicAccessStatus"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + Endpoint Endpoint `json:"endpoint"` + SyncMode string `json:"syncMode"` + BackupPolicy BackupPolicy `json:"backupPolicy"` + Region string `json:"region"` + InstanceType string `json:"instanceType"` + SourceInstanceId string `json:"sourceInstanceId"` + SourceRegion string `json:"sourceRegion"` + ZoneNames []string `json:"zoneNames"` + VpcId string `json:"vpcId"` + Subnets []Subnet `json:"subnets"` + Topology Topology `json:"topology"` + Task string `json:"task"` + PaymentTiming string `json:"paymentTiming"` + BgwGroupId string `json:"bgwGroupId"` + ReadReplicaNum int `json:"readReplicaNum"` + ReadReplica []string `json:"readReplica"` + LockMode string `json:"lockMode"` + EipStatus string `json:"eipStatus"` + SuperUserFlag string `json:"superUserFlag"` + ReplicationType string `json:"replicationType"` + Azone string `json:"azone"` + ApplicationType string `json:"applicationType"` + OnlineStatus int `json:"onlineStatus"` + IsSingle bool `json:"isSingle"` + NodeType string `json:"nodeType"` + DiskIoType string `json:"diskIoType"` + GroupId string `json:"groupId"` + GroupName string `json:"groupName"` + DiskType string `json:"diskType"` + CdsType string `json:"cdsType"` + MaintainStartTime string `json:"maintainStartTime"` + MaintainDuration int `json:"maintainDuration"` + HaStrategy int `json:"haStrategy"` + VpcName string `json:"vpcName"` + Tag []model.TagModel `json:"tag"` +} + +type ListRdsResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Instances []Instance `json:"instances"` +} + +type Subnet struct { + Name string `json:"name"` + SubnetId string `json:"subnetId"` + ZoneName string `json:"zoneName"` + Cidr string `json:"cidr"` + VpcId string `json:"vpcId"` +} + +type Endpoint struct { + Address string `json:"address"` + Port int `json:"port"` + VnetIp string `json:"vnetIp"` + InetIp string `json:"inetIp"` +} + +type BackupPolicy struct { + BackupDays string `json:"backupDays"` + BackupTime string `json:"backupTime"` + Persistent bool `json:"persistent"` + ExpireInDays int `json:"expireInDays"` + FreeSpaceInGB int `json:"freeSpaceInGb"` +} + +type Topology struct { + Rdsproxy []string `json:"rdsproxy"` + Master []string `json:"master"` + ReadReplica []string `json:"readReplica"` +} + +type ResizeRdsArgs struct { + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + NodeAmount int `json:"nodeAmount,omitempty"` + IsDirectPay bool `json:"isDirectPay,omitempty"` + AllocatedMemoryInMB string `json:"allocatedMemoryInMB,omitempty"` + IsEnhanced bool `json:"isEnhanced,omitempty"` + EffectiveTime string `json:"effectiveTime,omitempty"` + MasterAzone string `json:"masterAzone,omitempty"` + BackupAzone string `json:"backupAzone,omitempty"` + DiskIoType string `json:"diskIoType,omitempty"` + SubnetId string `json:"subnetId,omitempty"` + EdgeSubnetId string `json:"edgeSubnetId,omitempty"` + Subnets []SubnetMap `json:"subnets,omitempty"` +} + +type CreateAccountArgs struct { + ClientToken string `json:"-"` + AccountName string `json:"accountName"` + Password string `json:"password"` + AccountType string `json:"accountType,omitempty"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges,omitempty"` + Desc string `json:"desc,omitempty"` + Type string `json:"type,omitempty"` +} + +type DatabasePrivilege struct { + DbName string `json:"dbName"` + AuthType string `json:"authType"` +} + +type Account struct { + AccountName string `json:"accountName"` + Status string `json:"status"` + Type string `json:"type"` + AccountType string `json:"accountType"` + DatabasePrivileges []DatabasePrivilege `json:"databasePrivileges"` + Desc string `json:"desc"` +} + +type ListAccountResult struct { + Accounts []Account `json:"accounts"` +} + +type ModifyAccountDesc struct { + Remark string `json:"remark"` +} + +type UpdateAccountPrivileges struct { + DatabasePrivileges []DatabasePrivilege `json:"privileges"` +} + +type UpdatePasswordArgs struct { + Password string `json:"password"` +} +type UpdateInstanceNameArgs struct { + InstanceName string `json:"instanceName"` +} + +type ModifySyncModeArgs struct { + SyncMode string `json:"syncMode"` +} + +type ModifyEndpointArgs struct { + Address string `json:"address"` +} + +type ModifyPublicAccessArgs struct { + PublicAccess bool `json:"publicAccess"` +} + +type ModifyBackupPolicyArgs struct { + BackupDays string `json:"backupDays"` + BackupTime string `json:"backupTime"` + Persistent bool `json:"persistent"` + ExpireInDays int `json:"expireInDays"` +} + +type GetBackupListArgs struct { + Marker string + MaxKeys int +} + +type Snapshot struct { + SnapshotId string `json:"backupId"` + SnapshotSizeInBytes int64 `json:"backupSize"` + SnapshotType string `json:"backupType"` + SnapshotStatus string `json:"backupStatus"` + SnapshotStartTime string `json:"backupStartTime"` + SnapshotEndTime string `json:"backupEndTime"` + DownloadUrl string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} + +type BackupDetail struct { + BackupSize int `json:"backupSize"` + BackupStatus string `json:"backupStatus"` + BackupId string `json:"backupId"` + BackupEndTime string `json:"backupEndTime"` + DownloadUrl string `json:"downloadUrl"` + BackupType string `json:"backupType"` + BackupStartTime string `json:"backupStartTime"` + DownloadExpires string `json:"downloadExpires"` +} + +type GetBackupListResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + Backups []BackupDetail `json:"backups"` +} + +type GetBinlogListResult struct { + Binlogs []Binlog `json:"binlogs"` +} + +type GetBinlogInfoResult struct { + Binlog BinlogInfo `json:"binlog"` +} + +type BinlogInfo struct { + DownloadUrl string `json:"downloadUrl"` + DownloadExpires string `json:"downloadExpires"` +} +type Binlog struct { + BinlogId string `json:"binlogId"` + BinlogSizeInBytes int64 `json:"binlogSize"` + BinlogStatus string `json:"binlogStatus"` + BinlogStartTime string `json:"binlogStartTime"` + BinlogEndTime string `json:"binlogEndTime"` +} + +type RecoveryByDatetimeArgs struct { + Datetime string `json:"dateTime"` + Data []RecoveryData `json:"data"` +} + +type RecoveryBySnapshotArgs struct { + SnapshotId string `json:"snapshotId"` + Data []RecoveryData `json:"data"` +} +type RecoveryData struct { + DbName string `json:"dbName"` + NewDbname string `json:"newDbname"` + RestoreMode string `json:"restoreMode"` + Tables []TableData `json:"tables"` +} + +type TableData struct { + TableName string `json:"tableName"` + NewTablename string `json:"newTablename"` +} +type GetZoneListResult struct { + Zones []ZoneName `json:"zones"` +} + +type ZoneName struct { + ZoneNames []string `json:"zoneNames"` +} + +type ListSubnetsArgs struct { + VpcId string `json:"vpcId"` + ZoneName string `json:"zoneName"` +} + +type ListSubnetsResult struct { + Subnets []Subnet `json:"subnets"` +} + +type GetSecurityIpsResult struct { + Etag string `json:"etag"` + SecurityIps []string `json:"securityIps"` +} + +type UpdateSecurityIpsArgs struct { + SecurityIps []string `json:"securityIps"` +} + +type ListParametersResult struct { + Etag string `json:"etag"` + Parameters []Parameter `json:"parameters"` +} + +type Parameter struct { + Name string `json:"name"` + DefaultValue string `json:"defaultValue"` + Value string `json:"value"` + PendingValue string `json:"pendingValue"` + Type string `json:"type"` + Dynamic string `json:"dynamic"` + Modifiable string `json:"modifiable"` + AllowedValues string `json:"allowedValues"` + Desc string `json:"desc"` +} + +type UpdateParameterArgs struct { + Parameters []KVParameter `json:"parameters"` +} + +type KVParameter struct { + Name string `json:"name"` + Value string `json:"value"` +} + +type ParameterHistoryResult struct { + Parameters []ParameterHistory `json:"parameters"` +} + +type ParameterHistory struct { + Name string `json:"name"` + BeforeValue string `json:"beforeValue"` + AfterValue string `json:"afterValue"` + Status string `json:"status"` + UpdateTime string `json:"updateTime"` +} +type AutoRenewArgs struct { + InstanceIds []string `json:"instanceIds"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` + AutoRenewTime int `json:"autoRenewTime"` +} + +type SlowLogDownloadTaskListResult struct { + Slowlogs []Slowlog `json:"slowlogs"` +} + +type SlowLogDownloadDetail struct { + Slowlogs []SlowlogDetail `json:"slowlogs"` +} +type Slowlog struct { + SlowlogId string `json:"slowlogId"` + SlowlogSizeInBytes int `json:"slowlogSizeInBytes"` + SlowlogStartTime string `json:"slowlogStartTime"` + SlowlogEndTime string `json:"slowlogEndTime"` +} + +type SlowlogDetail struct { + Url string `json:"url"` + DownloadExpires string `json:"downloadExpires"` +} + +type MaintainTimeArgs struct { + MaintainStartTime string `json:"maintainStartTime"` + MaintainDuration int `json:"maintainDuration"` +} + +type DiskAutoResizeArgs struct { + FreeSpaceThreshold int `json:"freeSpaceThreshold,omitempty"` + DiskMaxLimit int `json:"diskMaxLimit,omitempty"` +} + +type AutoResizeConfigResult struct { + AutoResizeDisk int `json:"autoResizeDisk"` + FreeSpaceThreshold int `json:"freeSpaceThreshold"` + DiskMaxLimit int `json:"diskMaxLimit"` + ExtendStepPercent int `json:"extendStepPercent"` +} + +type EnableAutoExpansionResult struct { + SupportEnableDiskAutoResize int `json:"supportEnableDiskAutoResize"` +} + +type AzoneMigration struct { + MasterAzone string `json:"master_azone"` + BackupAzone string `json:"backup_azone"` + ZoneNames []string `json:"zoneNames"` + Subnets []SubnetMap `json:"subnets"` + EffectiveTime string `json:"effectiveTime"` +} + +type UpdateDatabasePortArgs struct { + EntryPort int `json:"entryPort"` +} + +type ListDatabasesResult struct { + Databases []Database `json:"databases"` +} + +type Database struct { + DbName string `json:"dbName"` + CharacterSetName string `json:"characterSetName"` + Remark string `json:"remark"` + DbStatus string `json:"dbStatus"` + AccountPrivileges []AccountPrivilege `json:"accountPrivileges"` +} + +type AccountPrivilege struct { + AccountName string `json:"accountName"` + AuthType string `json:"authType"` +} + +type ModifyDatabaseDesc struct { + Remark string `json:"remark"` +} + +type CreateDatabaseArgs struct { + CharacterSetName string `json:"characterSetName"` + DbName string `json:"dbName"` + Remark string `json:"remark"` + AccountPrivileges []AccountPrivilege `json:"accountPrivileges"` +} + +type TaskListArgs struct { + PageSize string `json:"pageSize,omitempty"` + PageNo string `json:"pageNo,omitempty"` + InstanceId string `json:"instanceId,omitempty"` + InstanceName string `json:"instanceName,omitempty"` + TaskId int `json:"taskId,omitempty"` + TaskType string `json:"taskType,omitempty"` + TaskStatus string `json:"taskStatus,omitempty"` + StartTime string `json:"startTime,omitempty"` + EndTime string `json:"endTime,omitempty"` +} + +type TaskListResult struct { + Tasks []Task `json:"tasks"` + Count int `json:"count"` +} + +type Task struct { + TaskId int `json:"taskId"` + TaskType string `json:"taskType"` + TaskName string `json:"taskName"` + InstanceId string `json:"instanceId"` + InstanceName string `json:"instanceName"` + UserId string `json:"userId"` + Region string `json:"region"` + TaskStatus string `json:"taskStatus"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` + FinishTime string `json:"finishTime"` + CancelFlag int `json:"cancelFlag"` + Progress []ProgressItem `json:"progress"` +} + +type ProgressItem struct { + Step string `json:"step"` + Status string `json:"status"` + Description string `json:"description"` +} + +type RecyclerListResult struct { + NextMarker string `json:"nextMarker"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + IsTruncated bool `json:"isTruncated"` + Instances []Instance `json:"instances"` + InstanceType string `json:"instanceType"` + ZoneNames []string `json:"zoneNames"` + PaymentTiming string `json:"paymentTiming"` +} + +type RecyclerRecoverArgs struct { + InstanceIds []string `json:"instanceIds"` +} + +type InstanceGroupArgs struct { + Name string `json:"name"` + LeaderId string `json:"leaderId"` +} + +type CreateInstanceGroupResult struct { + Result int `json:"result"` +} + +type ListInstanceGroupArgs struct { + Manner string `json:"manner"` + Order string `json:"order,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` +} + +type InstanceGroupListResult struct { + Result []InstanceGroup `json:"result"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + TotalCount int `json:"totalCount"` +} + +type InstanceGroup struct { + GroupId string `json:"groupId"` + Name string `json:"name"` + Count int `json:"count"` + Leader GroupInstance `json:"leader"` +} + +type GroupInstance struct { + InstanceIdShort string `json:"instanceIdShort"` + Region string `json:"region"` + Azone string `json:"azone"` + Status string `json:"status"` + LockMode string `json:"lockMode"` + Name string `json:"name"` +} + +type InstanceGroupDetailResult struct { + Group InstanceGroupDetail `json:"group"` +} + +type InstanceGroupDetail struct { + InstanceGroup + Fllowers []GroupInstance `json:"fllowers"` +} + +type CheckGtidArgs struct { + InstanceId string `json:"instanceId"` +} + +type CheckGtidResult struct { + Result bool `json:"result"` +} + +type CheckPingArgs struct { + SourceId string `json:"sourceId"` + TargetId string `json:"targetId"` +} + +type CheckPingResult struct { + Result bool `json:"result"` +} + +type CheckDataArgs struct { + InstanceId string `json:"instanceId"` +} + +type CheckDataResult struct { + Result bool `json:"result"` +} + +type CheckVersionArgs struct { + LeaderId string `json:"leaderId"` + FollowerId string `json:"followerId"` +} + +type CheckVersionResult struct { + Result bool `json:"result"` +} + +type InstanceGroupNameArgs struct { + Name string `json:"name"` +} + +type InstanceGroupAddArgs struct { + FollowerId string `json:"followerId"` +} + +type InstanceGroupBatchAddArgs struct { + FollowerIds []string `json:"followerIds"` + Name string `json:"name"` + LeaderId string `json:"leaderId"` +} + +type ForceChangeArgs struct { + LeaderId string `json:"leaderId"` + Force int `json:"force,omitempty"` + MaxBehind int `json:"maxBehind,omitempty"` +} + +type ForceChangeResult struct { + BehindMaster int `json:"behind_master"` +} + +type GroupLeaderChangeArgs struct { + LeaderId string `json:"leaderId"` +} + +type MinorVersionListResult struct { + RdsMinorVersionList []RdsMinorVersion `json:"rdsMinorVersionList"` +} + +type RdsMinorVersion struct { + DbVersion string `json:"dbVersion"` + MinorVersion string `json:"minorVersion"` + RdsMinorVersion string `json:"rdsMinorVersion"` + FeatureDescription string `json:"featureDescription"` +} + +type UpgradeMinorVersionArgs struct { + TargetMinorVersion string `json:"targetMinorVersion"` + EffectiveTime string `json:"effectiveTime"` +} + +type SlowSqlFlowStatusResult struct { + Enabled int `json:"enabled"` +} + +type GetSlowSqlArgs struct { + Page int `json:"page,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Sort string `json:"sort,omitempty"` + Schema string `json:"schema,omitempty"` + Digest string `json:"digest,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +type SlowSqlListResult struct { + Items []SlowSqlItem `json:"items"` + TotalCount int `json:"totalCount"` +} + +type SlowSqlItem struct { + AffectedRows int64 `json:"affectedRows"` + ClientHost string `json:"clientHost"` + ClientIP string `json:"clientIP"` + Cluster string `json:"cluster"` + ConnectionId int64 `json:"connectionId"` + CurrentDB string `json:"currentDB"` + Digest string `json:"digest"` + Duration float32 `json:"duration"` + ExaminedRows int64 `json:"examinedRows"` + LockTime int64 `json:"lockTime"` + Node string `json:"node"` + NumRows int `json:"numRows"` + Sql string `json:"sql"` + SqlId string `json:"sqlId"` + Start string `json:"start"` + User string `json:"user"` +} + +type SlowSqlExplainResult struct { + List []SlowSqlExplainItem `json:"list"` +} + +type SlowSqlExplainItem struct { + ExplainId int64 `json:"explainId"` + Extra string `json:"extra"` + Filtered int64 `json:"filtered"` + Key string `json:"key"` + KeyLen string `json:"keyLen"` + Partitions string `json:"partitions"` + PossibleKeys string `json:"possibleKeys"` + Ref string `json:"ref"` + Rows int `json:"rows"` + SelectType string `json:"selectType"` + Table string `json:"table"` + Type string `json:"type"` +} + +type SlowSqlDigestResult struct { + Items []SlowSqlDigestItem `json:"items"` + Summary SlowSqlDigestItem `json:"summary"` + TotalCount int `json:"totalCount"` +} + +type SlowSqlDigestItem struct { + AvgExamRows int64 `json:"avgExamRows"` + AvgLockTime int64 `json:"avgLockTime"` + AvgNumRows int64 `json:"avgNumRows"` + AvgTime float64 `json:"avgTime"` + Digest string `json:"digest"` + ExecuteTimes int64 `json:"executeTimes"` + MaxExamRows int64 `json:"maxExamRows"` + MaxLockTime float64 `json:"maxLockTime"` + MaxNumRows int64 `json:"maxNumRows"` + MaxTime float64 `json:"maxTime"` + NormalSql string `json:"normalSql"` + Schema string `json:"schema"` + TotalExamRows int64 `json:"totalExamRows"` + TotalLockTime float64 `json:"totalLockTime"` + TotalNumRows int64 `json:"totalNumRows"` + TotalTime float64 `json:"totalTime"` +} + +type GetSlowSqlDurationArgs struct { + Schema string `json:"schema,omitempty"` + Digest string `json:"digest,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +type SlowSqlDurationResult struct { + List []SlowSqlDurationItem `json:"list"` +} + +type SlowSqlDurationItem struct { + End int64 `json:"end"` + Nums int64 `json:"nums"` + Percentage float64 `json:"percentage"` + Start int64 `json:"start"` + Title string `json:"title"` +} + +type GetSlowSqlSourceArgs struct { + Schema string `json:"schema,omitempty"` + Digest string `json:"digest,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +type SlowSqlSourceResult struct { + List []SlowSqlSourceItem `json:"list"` +} + +type SlowSqlSourceItem struct { + Nums int64 `json:"nums"` + Percentage float64 `json:"percentage"` + Host string `json:"host"` + Ip string `json:"ip"` +} + +type SlowSqlSchemaResult struct { + List []SlowSqlSchemaItem `json:"list"` +} + +type SlowSqlSchemaItem struct { + Schema string `json:"schema"` + Table string `json:"table"` +} + +type SlowSqlTableResult struct { + List []SlowSqlTableItem `json:"list"` +} + +type SlowSqlTableItem struct { + Schema string `json:"schema"` + Table string `json:"table"` + Charset string `json:"charset"` + Collation string `json:"collation"` + Column string `json:"column"` + Comment string `json:"comment"` + DefaultValue string `json:"defaultValue"` + Extra string `json:"extra"` + Key string `json:"key"` + Nullable string `json:"nullable"` + Position int64 `json:"position"` + Type string `json:"type"` +} + +type GetSlowSqlIndexArgs struct { + SqlId string `json:"sqlId"` + Schema string `json:"schema"` + Table string `json:"table"` + Index string `json:"index,omitempty"` +} + +type SlowSqlIndexResult struct { + List []SlowSqlIndexItem `json:"list"` +} + +type SlowSqlIndexItem struct { + Schema string `json:"schema"` + Table string `json:"table"` + Collation string `json:"collation"` + Column string `json:"column"` + Comment string `json:"comment"` + Nullable string `json:"nullable"` + Type string `json:"type"` + Cardinality int64 `json:"cardinality"` + Index string `json:"index"` + NonUnique string `json:"nonUnique"` + Sequence string `json:"sequence"` +} + +type GetSlowSqlTrendArgs struct { + Schema string `json:"schema,omitempty"` + Interval string `json:"interval,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +type SlowSqlTrendResult struct { + Interval int `json:"interval"` + Items []SlowSqlTrendItem `json:"items"` +} + +type SlowSqlTrendItem struct { + Datetime string `json:"datetime"` + Times int64 `json:"times"` +} + +type SlowSqlAdviceResult struct { + IndexAdvice []SlowSqlIndexAdviceItem `json:"indexAdvice"` + StatementAdvice []SlowSqlIndexAdviceItem `json:"statementAdvice"` +} + +type SlowSqlIndexAdviceItem struct { + Advice string `json:"advice"` + Level string `json:"level"` +} + +type DiskInfoResult struct { + Result DiskInfo `json:"result"` +} + +type DiskInfo struct { + Grow float64 `json:"grow"` + UseDay float64 `json:"useDay"` + DiskFree float64 `json:"diskFree"` + DiskUse float64 `json:"diskUse"` + DiskQuota float64 `json:"diskQuota"` +} + +type DbListResult struct { + Result DbInfo `json:"result"` +} + +type DbInfo struct { + DbInfoItems []DbInfoItem `json:"dbList"` +} + +type DbInfoItem struct { + Size string `json:"size"` + TableSchema string `json:"tableSchema"` +} + +type GetTableListArgs struct { + DbName string `json:"dbName"` + PageNo int `json:"pageNo,omitempty"` + PageSize int `json:"pageSize,omitempty"` + OrderBy string `json:"orderBy,omitempty"` + Sort string `json:"sort,omitempty"` + SearchKey string `json:"searchKey,omitempty"` +} + +type TableListResult struct { + Result TableInfo `json:"result"` +} +type TableInfo struct { + Data []TableInfoItem `json:"data"` + TotalCount int64 `json:"totalCount"` +} + +type TableInfoItem struct { + IndexLength string `json:"indexLength"` + TableSchema string `json:"tableSchema"` + TableName string `json:"tableName"` + DataLength string `json:"dataLength"` + Engine string `json:"engine"` + TableRows string `json:"tableRows"` + DataFree string `json:"dataFree"` + DataFreePer string `json:"dataFreePer"` + AvgRowLength string `json:"avgRowLength"` + TableLength string `json:"tableLength"` + TableLengthPer string `json:"tableLengthPer"` +} + +type KillSessionTypesResult struct { + Types Commands `json:"types"` +} +type Commands struct { + Command []string `json:"command"` +} + +type SessionSummaryResult struct { + ActiveTotalCount int64 `json:"activeTotalCount"` + CpuUtilizationRate float64 `json:"cpuUtilizationRate"` + MaxExecuteTime float64 `json:"maxExecuteTime"` + TotalCount int64 `json:"totalCount"` +} + +type SessionDetailArgs struct { + Page int `json:"page,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Sort string `json:"sort,omitempty"` + ExecuteTime int64 `json:"executeTime,omitempty"` + Operator string `json:"operator,omitempty"` + IsActive bool `json:"isActive,omitempty"` + SessionId string `json:"sessionId,omitempty"` + User string `json:"user,omitempty"` + Host string `json:"host,omitempty"` + Db string `json:"db,omitempty"` + Command string `json:"command,omitempty"` + State string `json:"state,omitempty"` + SqlStmt string `json:"sqlStmt,omitempty"` +} + +type SessionDetailResult struct { + Items []SessionDetailItem `json:"items"` + TotalCount int64 `json:"totalCount"` +} + +type SessionDetailItem struct { + Command string `json:"command"` + Db string `json:"db"` + Host string `json:"host"` + Id int64 `json:"id"` + Sqlstmt string `json:"sqlStmt"` + State string `json:"state"` + Time string `json:"time"` + User string `json:"user"` +} + +type KillSessionAuthArgs struct { + DbHost string `json:"dbHost,omitempty"` + DbPort int `json:"dbPort,omitempty"` + Items []string `json:"items,omitempty"` + DbUser string `json:"dbUser,omitempty"` + DbPassword string `json:"dbPassword,omitempty"` +} + +type KillSessionAuthResult struct { + Success bool `json:"success"` +} + +type KillSessionHistory struct { + Page int `json:"page,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` +} + +type KillSessionHistoryResult struct { + Items []KillSessionHistoryItem `json:"items"` + TotalCount int64 `json:"totalCount"` +} + +type KillSessionHistoryItem struct { + OperateDbUser string `json:"operateDbUser"` + OperateTime string `json:"operateTime"` + OperateUser string `json:"operateUser"` + SessionCommand string `json:"sessionCommand"` + SessionDb string `json:"sessionDb"` + SessionExecuteTime string `json:"sessionExecuteTime"` + SessionHost string `json:"sessionHost"` + SessionId int64 `json:"sessionId"` + SessionSql string `json:"sessionSql"` + SessionState string `json:"sessionState"` + SessionUser string `json:"sessionUser"` + Status int `json:"status"` + StatusDesc string `json:"statusDesc"` + StatusInfo string `json:"statusInfo"` +} + +type KillSessionArgs struct { + DbHost string `json:"dbHost,omitempty"` + DbPort int `json:"dbPort,omitempty"` + Items []string `json:"items,omitempty"` +} + +type KillSessionResult struct { + Success bool `json:"success"` +} + +type SessionStatisticsResult map[string][]SessionStatisticsItem + +type SessionStatisticsItem struct { + ActiveAverageExecuteTime int64 `json:"activeAverageExecuteTime"` + ActiveTotalCount int64 `json:"activeTotalCount"` + ActiveTotalExecuteTime int64 `json:"activeTotalExecuteTime"` + DimensionKey string `json:"dimensionKey"` + DimensionValue string `json:"dimensionValue"` + TotalCount int64 `json:"totalCount"` +} + +type ErrorLogStatusResult struct { + Enabled int `json:"enabled"` +} + +type ErrorLogResult struct { + Success bool `json:"success"` +} + +type ErrorLogListArgs struct { + Page int `json:"page,omitempty"` + PageSize int `json:"pageSize,omitempty"` + Start string `json:"start,omitempty"` + End string `json:"end,omitempty"` + Label string `json:"label,omitempty"` +} +type ErrorLogListResult struct { + Items []ErrorLogItem `json:"items"` + TotalCount int64 `json:"totalCount"` +} + +type ErrorLogItem struct { + ConnectionId string `json:"connectionId"` + ErrCode string `json:"errCode"` + ErrInfo string `json:"errInfo"` + Label string `json:"label"` + LogId string `json:"logId"` + Subsystem string `json:"subsystem"` + Time string `json:"time"` +} + +type SqlFilterListResult struct { + SqlFilterList []SqlFilterItem `json:"sqlFilterList"` +} +type SqlFilterItem struct { + Id int64 `json:"id"` + FilterType string `json:"filterType"` + FilterKey string `json:"filterKey"` + FilterLimit int64 `json:"filterLimit"` + FilterStatus string `json:"filterStatus"` + CreateTime string `json:"createTime"` + UpdateTime string `json:"updateTime"` +} + +type SqlFilterArgs struct { + FilterType string `json:"filterType"` + FilterKey string `json:"filterKey"` + FilterLimit int64 `json:"filterLimit"` +} + +type StartOrStopSqlFilterArgs struct { + Action string `json:"action"` +} + +type IsAllowedResult struct { + Allowed bool `json:"allowed"` +} + +type ProcessArgs struct { + Ids []int64 `json:"ids,omitempty"` +} + +type InnodbStatusResult struct { + Datatime string `json:"datatime"` + Name string `json:"name"` + Type string `json:"type"` + Status string `json:"status"` +} + +type ProcessListResult struct { + Datetime string `json:"datetime"` + ProcessList []ProcessItem `json:"processList"` +} + +type LockHold map[string][]int64 + +type LockWait struct { + LocakId string `json:"lockId"` + Id int64 `json:"id"` +} +type ProcessItem struct { + Sql string `json:"sql"` + Db string `json:"db"` + State string `json:"state"` + Host string `json:"host"` + Command string `json:"command"` + User string `json:"user"` + Time int64 `json:"time"` + ID int64 `json:"id"` + LockHold LockHold `json:"lockHold"` + LockWait []LockWait +} + +type TransactionListResult struct { + Datetime string `json:"datetime"` + InnodbTrxList []InnodbTrxItem `json:"innodbTrxList"` +} +type InnodbTrxItem struct { + TrxRequestedLockId string `json:"trxRequestedLockId"` + TrxStarted string `json:"trxStarted"` + TrxMysqlThreadId int64 `json:"trxMysqlThreadId"` + TrxRowsLocked int64 `json:"trxRowsLocked"` + TrxWaitStarted string `json:"trxWaitStarted"` + TrxState string `json:"trxState"` + TrxTablesInUse int64 `json:"trxTablesInUse"` + TrxId string `json:"trxId"` + TrxQuery string `json:"trxQuery"` + TrxTablesLocked int `json:"trxTablesLocked"` +} + +type ConnectionListResult struct { + Datetime string `json:"datetime"` + ConnectList []ConnectionItem `json:"connectList"` +} +type ConnectionItem struct { + LocalAddress string `json:"localAddress"` + Proto string `json:"proto"` + SendQ int `json:"sendQ"` + ForeignAddress string `json:"foreignAddress"` + RecvQ int `json:"recvQ"` +} + +type FailInjectWhiteListResult struct { + AppList []string `json:"appList"` +} + +type FailInjectArgs struct { + AppList []string `json:"appList"` +} + +type TaskResult struct { + TaskId int64 `json:"taskId"` +} + +type OrderStatusResult struct { + Status string `json:"status"` +} diff --git a/bce-sdk-go/services/rds/rds.go b/bce-sdk-go/services/rds/rds.go new file mode 100644 index 0000000..b8318d9 --- /dev/null +++ b/bce-sdk-go/services/rds/rds.go @@ -0,0 +1,2308 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// rds.go - the rds APIs definition supported by the RDS service +package rds + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + DEFAULT_PAGE_SIZE = 10 + DEFAULT_PAGE_NUM = 1 +) + +// CreateRds - create a RDS with the specific parameters +// +// PARAMS: +// - args: the arguments to create a rds +// +// RETURNS: +// - *InstanceIds: the result of create RDS, contains new RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateRds(args *CreateRdsArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.Engine == "" { + return nil, fmt.Errorf("unset Engine") + } + + if args.EngineVersion == "" { + return nil, fmt.Errorf("unset EngineVersion") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + + result := &CreateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateReadReplica - create a readReplica RDS with the specific parameters +// +// PARAMS: +// - args: the arguments to create a readReplica rds +// +// RETURNS: +// - *InstanceIds: the result of create a readReplica RDS, contains the readReplica RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateReadReplica(args *CreateReadReplicaArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.SourceInstanceId == "" { + return nil, fmt.Errorf("unset SourceInstanceId") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + + result := &CreateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("readReplica", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// CreateRdsProxy - create a proxy RDS with the specific parameters +// +// PARAMS: +// - args: the arguments to create a readReplica rds +// +// RETURNS: +// - *InstanceIds: the result of create a readReplica RDS, contains the readReplica RDS's instanceIds +// - error: nil if success otherwise the specific error +func (c *Client) CreateRdsProxy(args *CreateRdsProxyArgs) (*CreateResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + + if args.SourceInstanceId == "" { + return nil, fmt.Errorf("unset SourceInstanceId") + } + + if args.Billing.PaymentTiming == "" { + return nil, fmt.Errorf("unset PaymentTiming") + } + + result := &CreateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("rdsproxy", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListRds - list all RDS with the specific parameters +// +// PARAMS: +// - args: the arguments to list all RDS +// +// RETURNS: +// - *ListRdsResult: the result of list all RDS, contains all rds' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListRds(args *ListRdsArgs) (*ListRdsResult, error) { + if args == nil { + args = &ListRdsArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListRdsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUri()). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetDetail - get a specific rds Instance's detail +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *Instance: the specific rdsInstance's detail +// - error: nil if success otherwise the specific error +func (c *Client) GetDetail(instanceId string) (*Instance, error) { + result := &Instance{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithResult(result). + Do() + + return result, err +} + +// DeleteRds - delete a rds +// +// PARAMS: +// - instanceIds: the specific instanceIds +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRds(instanceIds string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUri()). + WithQueryParamFilter("instanceIds", instanceIds). + Do() +} + +// ResizeRds - resize an RDS with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to resize an RDS +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeRds(instanceId string, args *ResizeRdsArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("resize", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// CreateAccount - create a account with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a account +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateAccount(instanceId string, args *CreateAccountArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.AccountName == "" { + return fmt.Errorf("unset AccountName") + } + + if args.Password == "" { + return fmt.Errorf("unset Password") + } + + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.Password) + if err != nil { + return err + } + args.Password = cryptedPass + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUriWithInstanceId(instanceId)+"/account"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ListAccount - list all account of a RDS instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListAccountResult: the result of list all account, contains all accounts' meta +// - error: nil if success otherwise the specific error +func (c *Client) ListAccount(instanceId string) (*ListAccountResult, error) { + result := &ListAccountResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/account"). + WithResult(result). + Do() + + return result, err +} + +// GetAccount - get an account of a RDS instance with the specific parameters +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - accountName: the specific account's name +// +// RETURNS: +// - *Account: the account's meta +// - error: nil if success otherwise the specific error +func (c *Client) GetAccount(instanceId, accountName string) (*Account, error) { + result := &Account{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/account/" + accountName). + WithResult(result). + Do() + + return result, err +} + +// AccountDesc - modify account's description +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - accountName: the specific account's name +// - args: the arguments used to modify account's description +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyAccountDesc(instanceId, accountName string, args *ModifyAccountDesc) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/account/"+accountName+"/desc"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateAccountPrivileges - upate account's privileges +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - accountName: the specific account's name +// - args: the arguments used to modify account's privileges +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPrivileges(instanceId, accountName string, args *UpdateAccountPrivileges) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/account/"+accountName+"/privileges"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateAccountPassword - update account's password +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific account's name +// - args: the arguments to update account's password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAccountPassword(instanceId, accountName string, args *UpdatePasswordArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + + if args.Password == "" { + return fmt.Errorf("unset Password") + } + + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.Password) + if err != nil { + return err + } + args.Password = cryptedPass + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/account/"+accountName+"/password"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteAccount - delete an account of a RDS instance +// +// PARAMS: +// - instanceId: the specific instanceId +// - accountName: the specific account's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAccount(instanceId, accountName string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUriWithInstanceId(instanceId) + "/account/" + accountName). + Do() +} + +// RebootInstance - reboot a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be rebooted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RebootInstance(instanceId string) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("reboot", ""). + Do() +} + +// UpdateInstanceName - update name of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update instanceName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceName(instanceId string, args *UpdateInstanceNameArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("rename", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateSyncMode - update sync mode of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update syncMode +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifySyncMode(instanceId string, args *ModifySyncModeArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("modifySyncMode", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ModifyEndpoint - modify the prefix of endpoint +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to modify endpoint +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyEndpoint(instanceId string, args *ModifyEndpointArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("modifyEndpoint", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ModifyPublicAccess - modify public access +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to modify public access +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyPublicAccess(instanceId string, args *ModifyPublicAccessArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("modifyPublicAccess", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ModifyBackupPolicy - modify backup policy +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to modify public access +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyBackupPolicy(instanceId string, args *ModifyBackupPolicyArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)). + WithQueryParam("modifyBackupPolicy", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetBackupList - get backup list of the instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetBackupListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupList(instanceId string, args *GetBackupListArgs) (*GetBackupListResult, error) { + + if args == nil { + args = &GetBackupListArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &GetBackupListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId)+"/backup"). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetBackupDetail - get backup detail of the instance's backup +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - backupId: id of the backup +// +// RETURNS: +// - *Snapshot: result of the backup detail +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupDetail(instanceId string, backupId string) (*BackupDetail, error) { + result := &BackupDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/backup/" + backupId). + WithResult(result). + Do() + + return result, err +} + +// DeleteBackup - delete backup detail +// +// PARAMS: +// - instanceId: the specific instanceId +// - backupId: the specific backupId +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteBackup(instanceId, backupId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUriWithInstanceId(instanceId) + "/backup/" + backupId). + Do() +} + +// GetBinlogList - get binlog list of the instance +// +// PARAMS: +// - instanceId: the specific instanceId +// - datetime: datetime of the binlog +// +// RETURNS: +// - *BinlogResult: result of the binlog list +// - error: nil if success otherwise the specific error +func (c *Client) GetBinlogList(instanceId, dateTime string) (*GetBinlogListResult, error) { + result := &GetBinlogListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/binlogs/" + dateTime). + WithResult(result). + Do() + + return result, err +} + +// GetBinlogInfo - get binlog info of the instance +// +// PARAMS: +// - instanceId: the specific instanceId +// - logId: the specific logId +// - downloadValidTimeInSec: download valid time in seconds +// +// RETURNS: +// - *BinlogInfo: result of the binlog info +// - error: nil if success otherwise the specific error +func (c *Client) GetBinlogInfo(instanceId, logId string, downloadValidTimeInSec string) (*GetBinlogInfoResult, error) { + result := &GetBinlogInfoResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/binlogs/" + logId + "/" + downloadValidTimeInSec). + WithResult(result). + Do() + + return result, err +} + +// RecoveryToSourceInstanceByDatetime - recover by datetime +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to recover the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecoveryToSourceInstanceByDatetime(instanceId string, args *RecoveryByDatetimeArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/recoveryToSourceInstanceByDatetime"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// RecoveryToSourceInstanceBySnapshot - recover by snapshot +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to recover the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecoveryToSourceInstanceBySnapshot(instanceId string, args *RecoveryBySnapshotArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/recoveryToSourceInstanceBySnapshot"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetZoneList - list all zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *GetZoneListResult: result of the zone list +// - error: nil if success otherwise the specific error +func (c *Client) GetZoneList() (*GetZoneListResult, error) { + result := &GetZoneListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(URI_PREFIX + "/zone"). + WithResult(result). + Do() + + return result, err +} + +// ListsSubnet - list all Subnets +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list all subnets, not necessary +// +// RETURNS: +// - *ListSubnetsResult: result of the subnet list +// - error: nil if success otherwise the specific error +func (c *Client) ListSubnets(args *ListSubnetsArgs) (*ListSubnetsResult, error) { + if args == nil { + args = &ListSubnetsArgs{} + } + + result := &ListSubnetsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(URI_PREFIX+"/subnet"). + WithQueryParamFilter("vpcId", args.VpcId). + WithQueryParamFilter("zoneName", args.ZoneName). + WithResult(result). + Do() + + return result, err +} + +// GetSecurityIps - get all SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *GetSecurityIpsResult: all security IP +// - error: nil if success otherwise the specific error +func (c *Client) GetSecurityIps(instanceId string) (*GetSecurityIpsResult, error) { + result := &GetSecurityIpsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/securityIp"). + WithResult(result). + Do() + + return result, err +} + +// UpdateSecurityIps - update SecurityIps +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Etag: get latest etag by GetSecurityIps +// - Args: all SecurityIps +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSecurityIps(instanceId, Etag string, args *UpdateSecurityIpsArgs) error { + + headers := map[string]string{"x-bce-if-match": Etag} + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/securityIp"). + WithHeaders(headers). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ListParameters - list all parameters of a RDS instance +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ListParametersResult: the result of list all parameters +// - error: nil if success otherwise the specific error +func (c *Client) ListParameters(instanceId string) (*ListParametersResult, error) { + result := &ListParametersResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/parameter"). + WithResult(result). + Do() + + return result, err +} + +// UpdateParameter - update Parameter +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - Etag: get latest etag by ListParameters +// - Args: *UpdateParameterArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateParameter(instanceId, Etag string, args *UpdateParameterArgs) error { + + headers := map[string]string{"x-bce-if-match": Etag} + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/parameter"). + WithHeaders(headers). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ParameterHistory - list all parameter history +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *ParameterHistory: the result of paremeters history +// - error: nil if success otherwise the specific error +func (c *Client) ParameterHistory(instanceId string) (*ParameterHistoryResult, error) { + result := &ParameterHistoryResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/parameter/history"). + WithResult(result). + Do() + + return result, err +} + +// autoRenew - create autoRenew +// +// PARAMS: +// - Args: *autoRenewArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AutoRenew(args *AutoRenewArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUri()). + WithQueryParam("autoRenew", ""). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// getSlowLogDownloadTaskList +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - datetime: the log time. range(datetime, datetime + 24 hours) +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowLogDownloadTaskList(instanceId, datetime string) (*SlowLogDownloadTaskListResult, error) { + fmt.Println(getRdsUriWithInstanceId(instanceId) + "/slowlogs/logList/" + datetime) + result := &SlowLogDownloadTaskListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/slowlogs/logList/" + datetime). + WithResult(result). + Do() + fmt.Println(result, err) + return result, err +} + +// getSlowLogDownloadDetail +// +// PARAMS: +// - Args: *slowLogDownloadTaskListArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowLogDownloadDetail(instanceId, logId, downloadValidTimeInSec string) (*SlowLogDownloadDetail, error) { + result := &SlowLogDownloadDetail{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/slowlogs/download_url/" + logId + "/" + downloadValidTimeInSec). + WithResult(result). + Do() + return result, err +} + +// maintaintime - update maintaintime +// +// PARAMS: +// - Args: *maintainTimeArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateMaintainTime(instanceId string, args *MaintainTimeArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/maintaintime"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// diskAutoResizeConfig - config disk auto resize +// +// PARAMS: +// - Args: *diskAutoResizeArgs +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ConfigDiskAutoResize(instanceId, action string, args *DiskAutoResizeArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/diskAutoResize/config/"+action). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// AutoResizeConfig - show disk auto resize config +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *AutoResizeConfigResult: the result of autoResizeConfig +// - error: nil if success otherwise the specific error +func (c *Client) GetAutoResizeConfig(instanceId string) (*AutoResizeConfigResult, error) { + result := &AutoResizeConfigResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/autoResizeConfig"). + WithResult(result). + Do() + + return result, err +} + +// EnableAutoExpansion - is support auto expansion +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// +// RETURNS: +// - *supportEnableDiskAutoResize: the result of list all parameters +// - error: nil if success otherwise the specific error +func (c *Client) EnableAutoExpansion(instanceId string) (*EnableAutoExpansionResult, error) { + result := &EnableAutoExpansionResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/autoExpansion"). + WithResult(result). + Do() + + return result, err +} + +// AzoneMigration - azone migration +// +// PARAMS: +// - instanceId: the specific rds Instance's ID +// - args: the arguments to set azone migration +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AzoneMigration(instanceId string, args *AzoneMigration) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/azoneMigration"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// UpdateDatabasePort - update database port +// +// PARAMS: +// - instanceId: id of the instance +// - args: the arguments to update database port +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateDatabasePort(instanceId string, args *UpdateDatabasePortArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/port"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// ListDatabases - list all databases +// +// PARAMS: +// - instanceId: id of the instance +// +// RETURNS: +// - *ListDatabasesResult: result of the database list +// - error: nil if success otherwise the specific error +func (c *Client) ListDatabases(instanceId string) (*ListDatabasesResult, error) { + result := &ListDatabasesResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/databases"). + WithResult(result). + Do() + + return result, err +} + +// DatabaseRemark - update database's remark +// +// PARAMS: +// - instanceIds: the specific instanceIds +// - dbName: the specific database's name +// - args: the arguments used to modify database's description +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyDatabaseDesc(instanceId, dbName string, args *ModifyDatabaseDesc) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/databases/"+dbName+"/remark"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteDatabase - delete database of RDS instance +// +// PARAMS: +// - instanceId: the specific instanceId +// - dbName: the specific database's name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteDatabase(instanceId, dbName string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUriWithInstanceId(instanceId) + "/databases/" + dbName). + Do() +} + +// CreateDatabase - create a database with the specific parameters +// +// PARAMS: +// - instanceId: the specific instanceId +// - args: the arguments to create a database +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateDatabase(instanceId string, args *CreateDatabaseArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUriWithInstanceId(instanceId)+"/databases"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// TaskList - task list +// +// PARAMS: +// - args: the arguments to list tasks +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) TaskList(args *TaskListArgs) (*TaskListResult, error) { + result := &TaskListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/task"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListRecyclerInstance - list all recycler instance +// +// PARAMS: +// - marker: the specific marker +// - maxKeys: the specific max keys +// +// RETURNS: +// - *RecyclerListResult: the result of list all recycler instance +// - error: nil if success otherwise the specific error +func (c *Client) ListRecyclerInstance(args *ListRdsArgs) (*RecyclerListResult, error) { + result := &RecyclerListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUri()+"/recycler/list"). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// RecyclerRecover - recover recycler instance +// +// PARAMS: +// - args: the arguments used to recover recycler instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecyclerRecover(args *RecyclerRecoverArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUri()+"/recycler/recover"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteRecyclerInstance - delete recycler instance +// +// PARAMS: +// - instanceId: the specific instanceId +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecyclerInstance(instanceId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUri() + "/recycler/" + instanceId). + Do() +} + +// CreateInstanceGroup - create instance group +// +// PARAMS: +// - args: the arguments to group create +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstanceGroup(args *InstanceGroupArgs) (*CreateInstanceGroupResult, error) { + result := &CreateInstanceGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListInstanceGroup - list all instace group +// +// PARAMS: +// - manner: the specific manner +// - order: asc or desc +// - orderBy: the specific orderBy +// - pageNo: the specific pageNo +// - pageSize: the specific pageSize +// +// RETURNS: +// - *InstanceGroupResult: the result of list all instance group +// - error: nil if success otherwise the specific error +func (c *Client) ListInstanceGroup(args *ListInstanceGroupArgs) (*InstanceGroupListResult, error) { + result := &InstanceGroupListResult{} + if args.PageSize == 0 { + args.PageSize = DEFAULT_PAGE_SIZE + } + if args.PageNo == 0 { + args.PageNo = DEFAULT_PAGE_NUM + } + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUri()+"/group"). + WithQueryParamFilter("manner", args.Manner). + WithQueryParamFilter("order", args.Order). + WithQueryParamFilter("orderBy", args.OrderBy). + WithQueryParamFilter("pageNo", strconv.Itoa(args.PageNo)). + WithQueryParamFilter("pageSize", strconv.Itoa(args.PageSize)). + WithResult(result). + Do() + + return result, err +} + +// InstanceGroupDetail - show the detail of instance group +// +// PARAMS: +// +// RETURNS: +// - *InstanceGroupDetailResult: the result of instance group detail +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupDetail(groupId string) (*InstanceGroupDetailResult, error) { + result := &InstanceGroupDetailResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUri() + "/group/" + groupId). + WithResult(result). + Do() + + return result, err +} + +// InstanceGroupCheckGtid - check the gtid of instance group +// +// PARAMS: +// - args: the arguments to check gtid +// +// RETURNS: +// - *CheckGtidResult: the result of check gtid +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupCheckGtid(args *CheckGtidArgs) (*CheckGtidResult, error) { + result := &CheckGtidResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/checkGtid"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// InstanceGroupCheckPing - instance group connectivity check +// +// PARAMS: +// - args: the arguments of connectivity check +// +// RETURNS: +// - *CheckPingResult: the result of connectivity check +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupCheckPing(args *CheckPingArgs) (*CheckPingResult, error) { + result := &CheckPingResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/checkPing"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// InstanceGroupCheckData - instance group data check +// +// PARAMS: +// - args: the arguments of data check +// +// RETURNS: +// - *CheckDataResult: the result of data check +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupCheckData(args *CheckDataArgs) (*CheckDataResult, error) { + result := &CheckDataResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/checkData"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// InstanceGroupCheckVersion - instance group version check +// +// PARAMS: +// - args: the arguments of version check +// +// RETURNS: +// - *CheckVersionResult: the result of data check +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupCheckVersion(args *CheckVersionArgs) (*CheckVersionResult, error) { + result := &CheckVersionResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/checkVersion"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateInstanceGroupName - update instance group name +// +// PARAMS: +// - args: the arguments of update instance group name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceGroupName(groupId string, args *InstanceGroupNameArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/"+groupId+"/name"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// InstanceGroupAdd - add instance to instance group +// +// PARAMS: +// - args: the arguments of add instance to instance group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupAdd(groupId string, args *InstanceGroupAddArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/"+groupId+"/instance"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// InstanceGroupBatchAdd - batch add instance to instance group +// +// PARAMS: +// - args: the arguments of batch add instance to instance group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupBatchAdd(args *InstanceGroupBatchAddArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/batchjoin"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// InstanceGroupForceChange - force change instance +// +// PARAMS: +// - args: the arguments used to force change instance +// +// RETURNS: +// - *ForceChangeResult: the result of force change +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupForceChange(groupId string, args *ForceChangeArgs) (*ForceChangeResult, error) { + result := &ForceChangeResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUri()+"/group/"+groupId+"/forceChange"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// InstanceGroupChangeLeader - change leader of instance group +// +// PARAMS: +// - args: the arguments used to change leader of instance group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupLeaderChange(groupId string, args *GroupLeaderChangeArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUri()+"/group/"+groupId+"/instance"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + + return err +} + +// InstanceGroupRemove - remove instance to instance group +// +// PARAMS: +// - args: the arguments of remove instance to instance group +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceGroupRemove(groupId, instanceId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUri()+"/group/"+groupId+"/instance/"+instanceId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// DeleteInstanceGroup - delete instance group +// +// PARAMS: +// - groupId: the instance group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstanceGroup(groupId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUri()+"/group/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// InstanceMinorVersionList - list minor versions available for instance +// +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *MinorVersionListResult: the result of list minor versions available for instance +// - error: nil if success otherwise the specific error +func (c *Client) InstanceMinorVersionList(instanceId string) (*MinorVersionListResult, error) { + result := &MinorVersionListResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL("/v1/rds/instance/" + instanceId + "/upgradeMinorVersionList"). + WithResult(result). + Do() + + return result, err +} + +// InstanceUpgradeMinorVersion - upgrade minor version +// +// PARAMS: +// - instanceId: the instance id +// - args: the arguments used to upgrade minor version +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) InstanceUpgradeMinorVersion(instanceId string, args *UpgradeMinorVersionArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL("/v1/rds/instance/"+instanceId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithQueryParam("upgradeMinorVersion", ""). + Do() + + return err +} + +// SlowSqlFlowStatus - get slow sql flow status +// +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *SlowSqlFlowStatusResult: the result of slow sql flow status +// - error: nil if success otherwise the specific error +func (c *Client) SlowSqlFlowStatus(instanceId string) (*SlowSqlFlowStatusResult, error) { + result := &SlowSqlFlowStatusResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsqlflow"). + WithResult(result). + Do() + + return result, err +} + +// EnableSlowSqlFlow - enable slow sql flow +// +// PARAMS: +// - instanceId: the instance id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) EnableSlowSqlFlow(instanceId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId)+"/smartdba/slowsqlflow"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// DisableSlowSqlFlow - disable slow sql flow +// +// PARAMS: +// - instanceId: the instance id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DisableSlowSqlFlow(instanceId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUriWithInstanceId(instanceId)+"/smartdba/slowsqlflow"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + + return err +} + +// GetSlowSqlList - get slow sql list +// +// PARAMS: +// - InstanceId: instance id +// - *GetSlowSqlArgs: the arguments of slow sql list +// +// RETURNS: +// - *SlowSqlListResult: the result of slow sql list +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlList(instanceId string, args *GetSlowSqlArgs) (*SlowSqlListResult, error) { + result := &SlowSqlListResult{} + if args.PageSize == 0 { + args.PageSize = DEFAULT_PAGE_SIZE + } + if args.Page == 0 { + args.Page = DEFAULT_PAGE_NUM + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/list"). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlBySqlId - get slow sql by sql id +// PARAMS: +// - InstanceId: instance id +// - SqlId: the sql id +// +// RETURNS: +// - *SlowSqlItem: the result of slow sql detail +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlBySqlId(instanceId, sqlId string) (*SlowSqlItem, error) { + result := &SlowSqlItem{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/" + sqlId). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlExplain - get slow sql explain +// PARAMS: +// - InstanceId: instance id +// - SqlId: the sql id +// - Schema: the schema +// +// RETURNS: +// - *SlowSqlExplainResult: the result of slow sql explain +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlExplain(instanceId, sqlId, schema string) (*SlowSqlExplainResult, error) { + result := &SlowSqlExplainResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/explain/" + sqlId + "/" + schema). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlStatsDigest - get slow sql stats digest +// +// PARAMS: +// - InstanceId: instance id +// - *GetSlowSqlArgs: the arguments of slow sql +// +// RETURNS: +// - *SlowSqlDigestResult: the result of slow sql stats digest +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlStatsDigest(instanceId string, args *GetSlowSqlArgs) (*SlowSqlDigestResult, error) { + result := &SlowSqlDigestResult{} + if args.PageSize == 0 { + args.PageSize = DEFAULT_PAGE_SIZE + } + if args.Page == 0 { + args.Page = DEFAULT_PAGE_NUM + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/stats/digest"). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlDuration - get slow sql duration +// +// PARAMS: +// - InstanceId: instance id +// - *GetSlowSqlDurationArgs: gs query arguments of slow sql duration +// +// RETURNS: +// - *SlowSqlDurationResult: the result of slow sql duration +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlDuration(instanceId string, args *GetSlowSqlDurationArgs) (*SlowSqlDurationResult, error) { + result := &SlowSqlDurationResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/stats/duration"). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlSource - get slow sql source +// +// PARAMS: +// - InstanceId: instance id +// - *GetSlowSqlSourceArgs: gs query arguments of slow sql srouce +// +// RETURNS: +// - *SlowSqlSourceResult: the result of slow sql souce +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlSource(instanceId string, args *GetSlowSqlSourceArgs) (*SlowSqlSourceResult, error) { + result := &SlowSqlSourceResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/stats/source"). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlSchema - get slow sql schema +// PARAMS: +// - InstanceId: instance id +// - SqlId: the sql id +// - Schema: the schema +// +// RETURNS: +// - *SlowSqlSchemaResult: the result of slow sql schema +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlSchema(instanceId, sqlId, schema string) (*SlowSqlSchemaResult, error) { + result := &SlowSqlSchemaResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/" + sqlId + "/" + schema). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlTable - get slow sql table +// PARAMS: +// - InstanceId: instance id +// - SqlId: the sql id +// - Schema: the schema +// - Table: the table +// +// RETURNS: +// - *SlowSqlTableResult: the result of slow sql table +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlTable(instanceId, sqlId, schema, table string) (*SlowSqlTableResult, error) { + result := &SlowSqlTableResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/" + sqlId + "/" + schema + "/" + table). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlIndex - get slow sql index +// PARAMS: +// - InstanceId: instance id +// - *GetSlowSqlIndexArgs: the arguments of slow sql index +// +// RETURNS: +// - *SlowSqlIndexResult: the result of slow sql index +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlIndex(instanceId string, args *GetSlowSqlIndexArgs) (*SlowSqlIndexResult, error) { + result := &SlowSqlIndexResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/table/index"). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlTrend - get slow sql trend +// PARAMS: +// - InstanceId: instance id +// - *GetSlowSqlTrendArgs: the arguments of slow sql trend +// +// RETURNS: +// - *SlowSqlTrendResult: the result of slow sql trend +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlTrend(instanceId string, args *GetSlowSqlTrendArgs) (*SlowSqlTrendResult, error) { + result := &SlowSqlTrendResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/trend"). + WithResult(result). + Do() + + return result, err +} + +// GetSlowSqlAdvice - get slow sql advice +// PARAMS: +// - InstanceId: instance id +// - SqlId: the sql id +// - Schema: the schema +// +// RETURNS: +// - *SlowSqlAdviceResult: the result of slow sql advice +// - error: nil if success otherwise the specific error +func (c *Client) GetSlowSqlAdvice(instanceId, sqlId, schema string) (*SlowSqlAdviceResult, error) { + result := &SlowSqlAdviceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/slowsql/tuning/" + sqlId + "/" + schema). + WithResult(result). + Do() + + return result, err +} + +// GetDiskInfo - get disk info +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *DiskInfoResult: the result of disk info +// - error: nil if success otherwise the specific error +func (c *Client) GetDiskInfo(instanceId string) (*DiskInfoResult, error) { + result := &DiskInfoResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/disk/list"). + WithResult(result). + Do() + + return result, err +} + +// GetDbListSize - get database list size +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *DbListResult: the result of database list size +// - error: nil if success otherwise the specific error +func (c *Client) GetDbListSize(instanceId string) (*DbListResult, error) { + result := &DbListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/db/list"). + WithResult(result). + Do() + + return result, err +} + +// GetTableListInfo - get table list info +// PARAMS: +// - InstanceId: instance id +// - *GetTableListArgs: the arguments of table list info +// +// RETURNS: +// - *TableListResult: the result of table list info +// - error: nil if success otherwise the specific error +func (c *Client) GetTableListInfo(instanceId string, args *GetTableListArgs) (*TableListResult, error) { + result := &TableListResult{} + if args.PageSize == 0 { + args.PageSize = DEFAULT_PAGE_SIZE + } + if args.PageNo == 0 { + args.PageNo = DEFAULT_PAGE_NUM + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/tb/list"). + WithResult(result). + Do() + + return result, err +} + +// GetKillSessionTypes - get kill session types +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *KillSessionTypesResult: the result of the kill session types +// - error: nil if success otherwise the specific error +func (c *Client) GetKillSessionTypes(instanceId string) (*KillSessionTypesResult, error) { + result := &KillSessionTypesResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/kill/types"). + WithResult(result). + Do() + + return result, err +} + +// GetSessionSummary - get session summary +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *SessionSummaryResult: the result of the session summary +// - error: nil if success otherwise the specific error +func (c *Client) GetSessionSummary(instanceId string) (*SessionSummaryResult, error) { + result := &SessionSummaryResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/summary"). + WithResult(result). + Do() + + return result, err +} + +// GetSessionDetail - get session detail +// PARAMS: +// - InstanceId: instance id +// - *SessionDetailArgs: the arguments of session detail +// +// RETURNS: +// - *SessionDetailResult: the result of the session detail +// - error: nil if success otherwise the specific error +func (c *Client) GetSessionDetail(instanceId string, args *SessionDetailArgs) (*SessionDetailResult, error) { + result := &SessionDetailResult{} + if args.PageSize == 0 { + args.PageSize = DEFAULT_PAGE_SIZE + } + if args.Page == 0 { + args.Page = DEFAULT_PAGE_NUM + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/detail"). + WithResult(result). + Do() + + return result, err +} + +// CheckKillSessionAuth - check kill session auth +// PARAMS: +// - InstanceId: instance id +// - *KillSessionAuthArgs: the arguments of kill session auth +// +// RETURNS: +// - *KillSessionAuthResult: the result of kill session auth +// - error: nil if success otherwise the specific error +func (c *Client) CheckKillSessionAuth(instanceId string, args *KillSessionAuthArgs) (*KillSessionAuthResult, error) { + result := &KillSessionAuthResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/kill/authority"). + WithResult(result). + Do() + + return result, err +} + +// GetKillSessionHistory - get kill session history +// PARAMS: +// - InstanceId: instance id +// - *KillSessionHistory: the arguments of kill session history +// +// RETURNS: +// - *KillSessionHistoryResult: the result of kill session history +// - error: nil if success otherwise the specific error +func (c *Client) GetKillSessionHistory(instanceId string, args *KillSessionHistory) (*KillSessionHistoryResult, error) { + result := &KillSessionHistoryResult{} + if args.PageSize == 0 { + args.PageSize = DEFAULT_PAGE_SIZE + } + if args.Page == 0 { + args.Page = DEFAULT_PAGE_NUM + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/kill/history"). + WithResult(result). + Do() + + return result, err +} + +// KillSession - kill session +// PARAMS: +// - InstanceId: instance id +// - *KillSessionArgs: the arguments of kill session +// +// RETURNS: +// - *KillSessionResult: the result of kill session +// - error: nil if success otherwise the specific error +func (c *Client) KillSession(instanceId string, args *KillSessionArgs) (*KillSessionResult, error) { + result := &KillSessionResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/kill"). + WithResult(result). + Do() + + return result, err +} + +// GetSessionStatistics - get session statistics +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *SessionStatisticsResult: the result of the session statistics +// - error: nil if success otherwise the specific error +func (c *Client) GetSessionStatistics(instanceId string) (*SessionStatisticsResult, error) { + result := &SessionStatisticsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/session/statistics"). + WithResult(result). + Do() + + return result, err +} + +// GetErrorLogStatus - get error log status +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *ErrorLogStatusResult: the result of error log status +// - error: nil if success otherwise the specific error +func (c *Client) GetErrorLogStatus(instanceId string) (*ErrorLogStatusResult, error) { + result := &ErrorLogStatusResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/errorlogflow"). + WithResult(result). + Do() + + return result, err +} + +// EnableErrorLog - enable error log +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *ErrorLogResult: the result of enable error log +// - error: nil if success otherwise the specific error +func (c *Client) EnableErrorLog(instanceId string) (*ErrorLogResult, error) { + result := &ErrorLogResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/errorlogflow"). + WithResult(result). + Do() + + return result, err +} + +// DisableErrorLog - disable error log +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *ErrorLogResult: the result of disable error log +// - error: nil if success otherwise the specific error +func (c *Client) DisableErrorLog(instanceId string) (*ErrorLogResult, error) { + result := &ErrorLogResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/errorlogflow"). + WithResult(result). + Do() + + return result, err +} + +// GetErrorLogList - get error log list +// PARAMS: +// - InstanceId: instance id +// - *ErrorLogListArgs: error log list arguments +// +// RETURNS: +// - *ErrorLogListResult: the result of error log list +// - error: nil if success otherwise the specific error +func (c *Client) GetErrorLogList(instanceId string, args *ErrorLogListArgs) (*ErrorLogListResult, error) { + result := &ErrorLogListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/smartdba/errorlog/detail"). + WithResult(result). + Do() + + return result, err +} + +// GetSqlFilterList - get sql filter list +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *SqlFilterListResult: the result of sql filter list +// - error: nil if success otherwise the specific error +func (c *Client) GetSqlFilterList(instanceId string) (*SqlFilterListResult, error) { + result := &SqlFilterListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter"). + WithResult(result). + Do() + + return result, err +} + +// GetSqlFilterDetail - get sql filter detail +// PARAMS: +// - InstanceId: instance id +// - SqlFilterId: sql filter id +// +// RETURNS: +// - *SqlFilterDetailResult: the result of sql filter detail +// - error: nil if success otherwise the specific error +func (c *Client) GetSqlFilterDetail(instanceId, sqlFilterId string) (*SqlFilterItem, error) { + result := &SqlFilterItem{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter/" + sqlFilterId). + WithResult(result). + Do() + + return result, err +} + +// AddSqlFilter - add sql filter +// PARAMS: +// - InstanceId: instance id +// - *AddSqlFilterArgs: add sql filter arguments +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AddSqlFilter(instanceId string, args *SqlFilterArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter"). + Do() + + return err +} + +// UpdateSqlFilter - update sql filter +// PARAMS: +// - InstanceId: instance id +// - SqlFilterId: sql filter id +// - *AddSqlFilterArgs: add sql filter arguments +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSqlFilter(instanceId, sqlFilterId string, args *SqlFilterArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter/" + sqlFilterId). + Do() + + return err +} + +// StartOrStopSqlFilter - start or stop sql filter +// - InstanceId: instance id +// - SqlFilterId: sql filter id +// - *StartOrStopSqlFilterArgs: start or stop sql filter arguments +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) StartOrStopSqlFilter(instanceId, sqlFilterId string, args *StartOrStopSqlFilterArgs) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter/" + sqlFilterId). + Do() + + return err +} + +// DeleteSqlFilter - delete sql filter +// - InstanceId: instance id +// - SqlFilterId: sql filter id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSqlFilter(instanceId, sqlFilterId string) error { + + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter/" + sqlFilterId). + Do() + + return err +} + +// IsAllowedSqlFilter - check if sql filter is allowed +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *IsAllowedResult: the result of sql filter allowed +// - error: nil if success otherwise the specific error +func (c *Client) IsAllowedSqlFilter(instanceId string) (*IsAllowedResult, error) { + result := &IsAllowedResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/sqlfilter/allowed"). + WithResult(result). + Do() + + return result, err +} + +// ProcessKill - kill process +// PARAMS: +// - InstanceId: instance id +// - *ProcessArgs: process arguments +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ProcessKill(instanceId string, args *ProcessArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithBody(args). + WithURL(getRdsUriWithInstanceId(instanceId) + "/performance/process/kill"). + Do() + + return err +} + +// InnodbStatus - get innodb status +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *InnodbStatusResult: the result of innodb status +// - error: nil if success otherwise the specific error +func (c *Client) InnodbStatus(instanceId string) (*InnodbStatusResult, error) { + result := &InnodbStatusResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/performance/innodbstatus"). + WithResult(result). + Do() + + return result, err +} + +// ProcessList - get process list +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *ProcessListResult: the result of process list +// - error: nil if success otherwise the specific error +func (c *Client) ProcessList(instanceId string) (*ProcessListResult, error) { + result := &ProcessListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/performance/processlist"). + WithResult(result). + Do() + + return result, err +} + +// TransactionList - get transaction list +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *TransactionListResult: the result of transaction list +// - error: nil if success otherwise the specific error +func (c *Client) TransactionList(instanceId string) (*TransactionListResult, error) { + result := &TransactionListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/performance/transaction"). + WithResult(result). + Do() + + return result, err +} + +// ConnectionList - get connection list +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *ConnectionListResult: the result of transaction list +// - error: nil if success otherwise the specific error +func (c *Client) ConnectionList(instanceId string) (*ConnectionListResult, error) { + result := &ConnectionListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getRdsUriWithInstanceId(instanceId) + "/performance/connection"). + WithResult(result). + Do() + + return result, err +} + +// FailInjectWhiteList - get fail inject white list +// +// RETURNS: +// - *FailInjectWhiteListResult: the result of transaction list +// - error: nil if success otherwise the specific error +func (c *Client) FailInjectWhiteList() (*FailInjectWhiteListResult, error) { + result := &FailInjectWhiteListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL("/v1/failinject/whitelist"). + WithResult(result). + Do() + + return result, err +} + +// AddToFailInjectWhiteList - add instance to failinject whitelist +// PARAMS: +// - *AddFailInjectArgs: add failinject args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AddToFailInjectWhiteList(args *FailInjectArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithBody(args). + WithURL("/v1/failinject/whitelist"). + Do() + + return err +} + +// RemoveFailInjectWhiteList - remove instance to failinject whitelist +// PARAMS: +// - *RemoveFailInjectArgs: remove failinject args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RemoveFailInjectWhiteList(args *FailInjectArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithBody(args). + WithURL("/v1/failinject/whitelist/remove"). + Do() + + return err +} + +// FailInjectStart - start failinject instance +// PARAMS: +// - InstanceId: instance id +// +// RETURNS: +// - *TaskResult: the result of task +// - error: nil if success otherwise the specific error +func (c *Client) FailInjectStart(instanceId string) (*TaskResult, error) { + result := &TaskResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL("/v1/failinject/" + instanceId). + WithResult(result). + Do() + + return result, err +} + +// GetOrderStatus - get order status +// PARAMS: +// - OrderId: order id +// +// RETURNS: +// - *OrderStatusResult: the result of order status +// - error: nil if success otherwise the specific error +func (c *Client) GetOrderStatus(orderId string) (*OrderStatusResult, error) { + result := &OrderStatusResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL("/v1/instance/order/" + orderId). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) Request(method, uri string, body interface{}) (interface{}, error) { + res := struct{}{} + req := bce.NewRequestBuilder(c). + WithMethod(method). + WithURL(uri). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + var err error + if body != nil { + err = req. + WithBody(body). + WithResult(res). + Do() + } else { + err = req. + WithResult(res). + Do() + } + + return res, err +} diff --git a/bce-sdk-go/services/rds/util.go b/bce-sdk-go/services/rds/util.go new file mode 100644 index 0000000..4b0f618 --- /dev/null +++ b/bce-sdk-go/services/rds/util.go @@ -0,0 +1,35 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of RDS service +package rds + +import ( + "encoding/hex" + "fmt" + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} diff --git a/bce-sdk-go/services/scs/client.go b/bce-sdk-go/services/scs/client.go new file mode 100644 index 0000000..ded3609 --- /dev/null +++ b/bce-sdk-go/services/scs/client.go @@ -0,0 +1,40 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for SCS service + +// Package scs defines the SCS services of BCE. The supported APIs are all defined in sub-package +package scs + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + DEFAULT_ENDPOINT = "redis." + bce.DEFAULT_REGION + ".baidubce.com" +) + +// Client of SCS service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} diff --git a/bce-sdk-go/services/scs/client_test.go b/bce-sdk-go/services/scs/client_test.go new file mode 100644 index 0000000..e6ef83a --- /dev/null +++ b/bce-sdk-go/services/scs/client_test.go @@ -0,0 +1,1191 @@ +package scs + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strconv" + "strings" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/model" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + SCS_CLIENT *Client + SCS_TEST_ID string + client *Client +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +const ( + SDK_NAME_PREFIX = "sdk_scs_" +) + +var instanceId = SCS_TEST_ID + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 1; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + SCS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) + client = SCS_CLIENT + SCS_TEST_ID = "scs-bj-rlmhqtbehihj" + instanceId = SCS_TEST_ID +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateInstance(t *testing.T) { + id := strconv.FormatInt(time.Now().Unix(), 10) + args := &CreateInstanceArgs{ + Billing: Billing{ + PaymentTiming: "Postpaid", + Reservation: &Reservation{ + ReservationLength: 1, + }, + }, + ClientToken: getClientToken(), + PurchaseCount: 1, + InstanceName: SDK_NAME_PREFIX + id, + Port: 6379, + Engine: 3, + // EngineVersion: "5.0", + NodeType: "pega.g4s1.micro", + ClusterType: "cluster", + ReplicationNum: 2, + ShardNum: 1, + ProxyNum: 2, + DiskFlavor: 60, + DiskType: "essd", + BgwGroupId: "", + StoreType: 3, + EnableReadOnly: 1, + ClientAuth: "ABlockIs16Bytes!", + } + result, err := SCS_CLIENT.CreateInstance(args) + ExpectEqual(t.Errorf, nil, err) + + if len(result.InstanceIds) > 0 { + SCS_TEST_ID = result.InstanceIds[0] + } + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_ListInstances(t *testing.T) { + args := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(args) + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) + for _, e := range result.Instances { + if e.InstanceID == SCS_TEST_ID { + ExpectEqual(t.Errorf, "Postpaid", e.PaymentTiming) + } + } +} + +func TestClient_GetInstanceDetail(t *testing.T) { + result, err := SCS_CLIENT.GetInstanceDetail(SCS_TEST_ID) + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_UpdateInstanceName(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &UpdateInstanceNameArgs{ + InstanceName: e.InstanceName + "_new", + ClientToken: getClientToken(), + } + err := SCS_CLIENT.UpdateInstanceName(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_ResizeInstance(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &ResizeInstanceArgs{ + NodeType: "cache.n1.mirco", + ShardNum: 4, + ClientToken: getClientToken(), + IsDefer: true, + } + result, err := SCS_CLIENT.GetInstanceDetail(SCS_TEST_ID) + ExpectEqual(t.Errorf, nil, err) + if result.InstanceStatus == "Running" { + err := SCS_CLIENT.ResizeInstance(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) + } +} + +func TestClient_GetCreatePrice(t *testing.T) { + args := &CreatePriceArgs{ + Engine: 2, + Period: 1, + ChargeType: "prepay", + NodeType: "cache.n1.small", + ReplicationNum: 2, + ClusterType: "cluster", + } + result, err := SCS_CLIENT.GetCreatePrice(args) + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_GetResizePrice(t *testing.T) { + args := &ResizePriceArgs{ + ChangeType: "nodeModify", + ShardNum: 2, + ReplicationNum: 1, + NodeType: "cache.n1.small", + Period: 1, + } + result, err := SCS_CLIENT.GetResizePrice(instanceId, args) + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) + +} + +func TestClient_AddReplication(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &ReplicationArgs{ + ResizeType: "add", + ReplicationInfo: []Replication{ + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 1}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + }, + ClientToken: getClientToken(), + } + result, err := SCS_CLIENT.GetInstanceDetail(SCS_TEST_ID) + ExpectEqual(t.Errorf, nil, err) + if result.InstanceStatus == "Running" { + err := SCS_CLIENT.AddReplication(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) + } +} + +func TestClient_Deletelication(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &ReplicationArgs{ + ResizeType: "delete", + ReplicationInfo: []Replication{ + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 1}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + {AvailabilityZone: "cn-bj-a", SubnetId: "sbn-fh56wbtv1ycw", IsMaster: 0}, + }, + ClientToken: getClientToken(), + } + result, err := SCS_CLIENT.GetInstanceDetail(SCS_TEST_ID) + ExpectEqual(t.Errorf, nil, err) + if result.InstanceStatus == "Running" { + err := SCS_CLIENT.DeleteReplication(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) + } +} + +func TestClient_RestartInstance(t *testing.T) { + args := &RestartInstanceArgs{ + IsDefer: true, + } + err := SCS_CLIENT.RestartInstance(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetNodeTypeList(t *testing.T) { + _, err := SCS_CLIENT.GetNodeTypeList() + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} + +func TestClient_ListSubnets(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &ListSubnetsArgs{} + _, err := SCS_CLIENT.ListSubnets(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateInstanceDomainName(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &UpdateInstanceDomainNameArgs{ + Domain: "new" + e.Domain, + ClientToken: getClientToken(), + } + err := SCS_CLIENT.UpdateInstanceDomainName(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_GetZoneList(t *testing.T) { + //isAvailable(SCS_TEST_ID) + _, err := SCS_CLIENT.GetZoneList() + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ModifyPassword(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &ModifyPasswordArgs{ + Password: "1234qweR", + ClientToken: getClientToken(), + } + err := SCS_CLIENT.ModifyPassword(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_RenameDomain(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &RenameDomainArgs{ + Domain: "newDomain", + ClientToken: getClientToken(), + } + err := SCS_CLIENT.RenameDomain(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_SwapDomain(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &SwapDomainArgs{ + SourceInstanceId: SCS_TEST_ID, + TargetInstanceId: "scs-bj-xeelkkdsx", + ClientToken: getClientToken(), + } + err := SCS_CLIENT.SwapDomain(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_FlushInstance(t *testing.T) { + isAvailable(SCS_TEST_ID) + time.Sleep(30 * time.Second) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &FlushInstanceArgs{ + Password: "1234qweR", + ClientToken: getClientToken(), + } + err := SCS_CLIENT.FlushInstance(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_BindingTag(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &BindingTagArgs{ + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, + } + err := SCS_CLIENT.BindingTag(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_UnBindingTag(t *testing.T) { + isAvailable(SCS_TEST_ID) + time.Sleep(30 * time.Second) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &BindingTagArgs{ + ChangeTags: []model.TagModel{ + { + TagKey: "tag1", + TagValue: "var1", + }, + }, + } + err := SCS_CLIENT.UnBindingTag(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_SetAsMaster(t *testing.T) { + isAvailable(SCS_TEST_ID) + err := SCS_CLIENT.SetAsMaster(SCS_TEST_ID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_SetAsSlave(t *testing.T) { + isAvailable(SCS_TEST_ID) + args := &SetAsSlaveArgs{ + MasterDomain: "masterDomain", + MasterPort: 6379, + } + err := SCS_CLIENT.SetAsSlave(SCS_TEST_ID, args) + ExpectEqual(t.Errorf, nil, err) +} +func TestClient_GetSecurityIp(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + _, err := SCS_CLIENT.GetSecurityIp(e.InstanceID) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_AddSecurityIp(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &SecurityIpArgs{ + SecurityIps: []string{ + "192.0.0.1", + }, + ClientToken: getClientToken(), + } + err := SCS_CLIENT.AddSecurityIp(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_DeleteSecurityIp(t *testing.T) { + isAvailable(SCS_TEST_ID) + time.Sleep(30 * time.Second) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &SecurityIpArgs{ + SecurityIps: []string{ + "192.0.0.1", + }, + ClientToken: getClientToken(), + } + err := SCS_CLIENT.DeleteSecurityIp(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_GetParameters(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + _, err := SCS_CLIENT.GetParameters(e.InstanceID) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_ModifyParameters(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &ModifyParametersArgs{ + Parameter: InstanceParam{ + Name: "timeout", + Value: "0", + }, + ClientToken: getClientToken(), + } + err := SCS_CLIENT.ModifyParameters(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_GetBackupList(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + _, err := SCS_CLIENT.GetBackupList(e.InstanceID) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_GetBackupDetail(t *testing.T) { + isAvailable(SCS_TEST_ID) + result, err := SCS_CLIENT.GetBackupDetail(SCS_TEST_ID, "2587532") + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} +func TestClient_ModifyBackupPolicy(t *testing.T) { + isAvailable(SCS_TEST_ID) + listInstancesArgs := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(listInstancesArgs) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Running" == e.InstanceStatus { + args := &ModifyBackupPolicyArgs{ + BackupDays: "Sun,Mon,Tue,Wed,Thu,Fri,Sta", + BackupTime: "01:05:00", + ExpireDay: 7, + ClientToken: getClientToken(), + } + err := SCS_CLIENT.ModifyBackupPolicy(e.InstanceID, args) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func TestClient_DeleteInstance(t *testing.T) { + //isAvailable(SCS_TEST_ID) + //time.Sleep(50*time.Second) + args := &ListInstancesArgs{} + result, err := SCS_CLIENT.ListInstances(args) + ExpectEqual(t.Errorf, nil, err) + for _, e := range result.Instances { + if strings.HasPrefix(e.InstanceName, SDK_NAME_PREFIX) && "Run"+ + "ning" == e.InstanceStatus && "Postpaid" == e.PaymentTiming { + err := SCS_CLIENT.DeleteInstance(e.InstanceID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) + } + } +} + +func isAvailable(instanceId string) { + for { + result, err := SCS_CLIENT.GetInstanceDetail(instanceId) + fmt.Println(instanceId, " => ", result.InstanceStatus) + if err == nil && result.InstanceStatus == "Running" { + break + } + } +} + +func TestClient_ListSecurityGroupByVpcId(t *testing.T) { + vpcId := "vpc-t7yi6xyrapjz" + securityGroups, err := client.ListSecurityGroupByVpcId(vpcId) + if err != nil { + fmt.Printf("list security group by vpcId error: %+v\n", err) + return + } + for _, group := range securityGroups.Groups { + fmt.Println("+-------------------------------------------+") + fmt.Println("id: ", group.SecurityGroupID) + fmt.Println("name: ", group.Name) + fmt.Println("description: ", group.Description) + fmt.Println("associateNum: ", group.AssociateNum) + fmt.Println("createdTime: ", group.CreatedTime) + fmt.Println("version: ", group.Version) + fmt.Println("defaultSecurityGroup: ", group.DefaultSecurityGroup) + fmt.Println("vpc name: ", group.VpcName) + fmt.Println("vpc id: ", group.VpcShortID) + fmt.Println("tenantId: ", group.TenantID) + } + fmt.Println("list security group by vpcId success.") +} + +func TestClient_ListSecurityGroupByInstanceId(t *testing.T) { + instanceId := "scs-su-bbjhgxyqyddd" + result, err := client.ListSecurityGroupByInstanceId(instanceId) + if err != nil { + fmt.Printf("list security group by instanceId error: %+v\n", err) + return + } + for _, group := range result.Groups { + fmt.Println("+-------------------------------------------+") + fmt.Println("securityGroupId: ", group.SecurityGroupID) + fmt.Println("securityGroupName: ", group.SecurityGroupName) + fmt.Println("securityGroupRemark: ", group.SecurityGroupRemark) + fmt.Println("projectId: ", group.ProjectID) + fmt.Println("vpcId: ", group.VpcID) + fmt.Println("vpcName: ", group.VpcName) + fmt.Println("inbound: ", group.Inbound) + fmt.Println("outbound: ", group.Outbound) + } + fmt.Println("list security group by instanceId success.") +} + +func TestClient_BindSecurityGroups(t *testing.T) { + instanceIds := []string{ + "scs-su-bbjhgxyqyddd", + } + securityGroupIds := []string{ + "g-eun39daa38qf", + } + args := &SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, + } + + err := client.BindSecurityGroups(args) + if err != nil { + fmt.Printf("bind security groups to instances error: %+v\n", err) + return + } + fmt.Println("bind security groups to instances success.") +} + +func TestClient_UnBindSecurityGroups(t *testing.T) { + securityGroupIds := []string{ + "g-gtj7wknuw3h9", + } + args := &UnbindSecurityGroupArgs{ + InstanceId: "scs-su-bbjhgxyqyddd", + SecurityGroupIds: securityGroupIds, + } + + err := client.UnBindSecurityGroups(args) + if err != nil { + fmt.Printf("unbind security groups to instances error: %+v\n", err) + return + } + fmt.Println("unbind security groups to instances success.") +} + +func TestClient_ReplaceSecurityGroups(t *testing.T) { + instanceIds := []string{ + "scs-mjafcdu0", + } + securityGroupIds := []string{ + "g-iutg5rtcydsk", + } + args := &SecurityGroupArgs{ + InstanceIds: instanceIds, + SecurityGroupIds: securityGroupIds, + } + + err := client.ReplaceSecurityGroups(args) + if err != nil { + fmt.Printf("replace security groups to instances error: %+v\n", err) + return + } + fmt.Println("replace security groups to instances success.") +} + +func TestClient_ListRecycleInstances(t *testing.T) { + marker := &Marker{MaxKeys: 10} + instances, err := client.ListRecycleInstances(marker) + if err != nil { + fmt.Printf("list recycler instances error: %+v\n", err) + return + } + for _, instance := range instances.Result { + fmt.Println("+-------------------------------------------+") + fmt.Println("instanceId: ", instance.InstanceID) + fmt.Println("instanceName: ", instance.InstanceName) + fmt.Println("engine: ", instance.Engine) + fmt.Println("engineVersion: ", instance.EngineVersion) + fmt.Println("instanceStatus: ", instance.InstanceStatus) + fmt.Println("isolatedStatus: ", instance.IsolatedStatus) + fmt.Println("PaymentTiming: ", instance.PaymentTiming) + fmt.Println("ClusterType: ", instance.ClusterType) + fmt.Println("Domain: ", instance.Domain) + fmt.Println("Port: ", instance.Port) + fmt.Println("VnetIP: ", instance.VnetIP) + fmt.Println("InstanceCreateTime: ", instance.InstanceCreateTime) + fmt.Println("UsedCapacity: ", instance.UsedCapacity) + fmt.Println("ZoneNames: ", instance.ZoneNames) + fmt.Println("tags: ", instance.Tags) + } +} + +func TestClient_RecoverRecyclerInstances(t *testing.T) { + instanceIds := []string{ + "scs-bj-xjgriqupoftn", + } + err := client.RecoverRecyclerInstances(instanceIds) + if err != nil { + fmt.Printf("recover recycler instances error: %+v\n", err) + return + } + fmt.Println("recover recycler instances success.") +} + +func TestClient_DeleteRecyclerInstances(t *testing.T) { + instanceIds := []string{ + "scs-bj-xuuasbccatzr", + } + err := client.DeleteRecyclerInstances(instanceIds) + if err != nil { + fmt.Printf("delete recycler instances error: %+v\n", err) + return + } + fmt.Println("delete recycler instances success.") +} + +func TestClient_RenewInstances(t *testing.T) { + instanceIds := []string{ + "scs-bj-xuuasbccatzr", + } + args := &RenewInstanceArgs{ + // 实例Id列表 + InstanceIds: instanceIds, + // 续费周期,单位为月 + Duration: 1, + } + result, err := client.RenewInstances(args) + if err != nil { + fmt.Printf("renew instances error: %+v\n", err) + return + } + fmt.Println("renew instances success. orderId:" + result.OrderId) +} +func TestClient_ListLogByInstanceId(t *testing.T) { + // 一天前 + date := time.Now(). + AddDate(0, 0, -1). + Format("2006-01-02 03:04:05") + fmt.Println(date) + args := &ListLogArgs{ + // 运行日志 runlog 慢日志 slowlog + FileType: "runlog", + // 开始时间格式 "yyyy-MM-dd hh:mm:ss" + StartTime: date, + // 结束时间,可选,默认返回开始时间+24小时内的日志 + // EndTime: date, + } + listLogResult, err := client.ListLogByInstanceId(instanceId, args) + if err != nil { + fmt.Printf("list logs of instance error: %+v\n", err) + return + } + fmt.Println("list logs of instance success.") + for _, shardLog := range listLogResult.LogList { + fmt.Println("+-------------------------------------------+") + fmt.Println("shard id: ", shardLog.ShardID) + fmt.Println("logs size: ", shardLog.TotalNum) + for _, log := range shardLog.LogItem { + fmt.Println("log id: ", log.LogID) + fmt.Println("size: ", log.LogSizeInBytes) + fmt.Println("start time: ", log.LogStartTime) + fmt.Println("end time: ", log.LogEndTime) + fmt.Println("download url: ", log.DownloadURL) + fmt.Println("download url expires: ", log.DownloadExpires) + } + } +} + +func TestClient_GetLogById(t *testing.T) { + args := &GetLogArgs{ + // 下载链接有效时间,单位为秒,可选,默认为1800秒 + ValidSeconds: 60, + } + logId := "scs-bj-mktaypucksot_8742_slowlog_202104160330" + log, err := client.GetLogById(instanceId, logId, args) + if err != nil { + fmt.Printf("get log detail of instance error: %+v\n", err) + return + } + fmt.Println("get log detail success.") + fmt.Println("+-------------------------------------------+") + fmt.Println("id: ", log.LogID) + fmt.Println("download url: ", log.DownloadURL) + fmt.Println("download url expires: ", log.DownloadExpires) +} + +func TestClient_GetMaintainTime(t *testing.T) { + resp, err := client.GetMaintainTime(instanceId) + if err != nil { + fmt.Printf("get maintainTime of instance error: %+v\n", err) + return + } + fmt.Println("get maintainTime success.") + fmt.Println("+-------------------------------------------+") + fmt.Println("start time: ", resp.MaintainTime.StartTime) + fmt.Println("dutation: ", resp.MaintainTime.Duration) + fmt.Println("period: ", resp.MaintainTime.Period) +} + +func TestClient_ModifyMaintainTime(t *testing.T) { + newMaintainTime := &MaintainTime{ + StartTime: "16:00", + Duration: 1, + Period: []int{1, 2, 3}, + } + err := client.ModifyMaintainTime(instanceId, newMaintainTime) + if err != nil { + fmt.Printf("modify maintainTime of instance error: %+v\n", err) + return + } + fmt.Println("modify maintainTime success.") +} + +func TestClient_GroupPreCheck(t *testing.T) { + args := &GroupPreCheckArgs{ + Leader: GroupLeader{ + LeaderRegion: "bj", + LeaderId: SCS_TEST_ID, + }, + Followers: []GroupFollower{ + { + FollowerId: "scs-bdbl-dzkqigawuhzy", + FollowerRegion: "bd", + }, + }, + } + result, err := client.GroupPreCheck(args) + if err != nil { + fmt.Printf("group pre check error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_CreateGroup(t *testing.T) { + args := &CreateGroupArgs{ + Leader: CreateGroupLeader{ + GroupName: "test_create", + LeaderRegion: "bj", + LeaderId: SCS_TEST_ID, + }, + } + result, err := client.CreateGroup(args) + if err != nil { + fmt.Printf("group create error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_GetGroupList(t *testing.T) { + args := &GetGroupListArgs{ + PageNo: 1, + PageSize: 10, + } + result, err := client.GetGroupList(args) + if err != nil { + fmt.Printf("get group list error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_GetGroupDetail(t *testing.T) { + result, err := client.GetGroupDetail("scs-group-vobpzinoqadm") + if err != nil { + fmt.Printf("get group detail error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_DeleteGroup(t *testing.T) { + err := client.DeleteGroup("scs-group-ekeveqhmekvd") + if err != nil { + fmt.Printf("delete group error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupAddFollower(t *testing.T) { + args := &FollowerInfo{ + FollowerId: "scs-bdbl-dzkqigawuhzy", + FollowerRegion: "bd", + SyncMaster: "sync", + } + err := client.GroupAddFollower("scs-group-ekeveqhmekvd", args) + if err != nil { + fmt.Printf("join group error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupRemoveFollower(t *testing.T) { + err := client.GroupRemoveFollower("scs-group-ekeveqhmekvd", SCS_TEST_ID) + if err != nil { + fmt.Printf("quit group error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateGroupName(t *testing.T) { + args := &GroupNameArgs{ + GroupName: "test_group", + } + err := client.UpdateGroupName("scs-group-nqkkmbdjlacx", args) + if err != nil { + fmt.Printf("update group name error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_SetAsLeader(t *testing.T) { + err := client.SetAsLeader("scs-group-nqkkmbdjlacx", SCS_TEST_ID) + if err != nil { + fmt.Printf("set as leader error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupForbidWrite(t *testing.T) { + args := &ForbidWriteArgs{ + ForbidWriteFlag: true, + } + err := client.GroupForbidWrite("scs-group-nqkkmbdjlacx", args) + if err != nil { + fmt.Printf("forbid write error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupSetQps(t *testing.T) { + args := &GroupSetQpsArgs{ + ClusterShowId: "scs-bj-bftgjzjxbmex", + QpsWrite: 10, + QpsRead: 20, + } + err := client.GroupSetQps("scs-group-nqkkmbdjlacx", args) + if err != nil { + fmt.Printf("group set qps error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupSyncStatus(t *testing.T) { + result, err := client.GroupSyncStatus("scs-group-szqbjupjjhpl") + if err != nil { + fmt.Printf("group sync status error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_GroupWhiteList(t *testing.T) { + result, err := client.GroupWhiteList("scs-group-szqbjupjjhpl") + if err != nil { + fmt.Printf("get group white list error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) + data, _ := json.Marshal(result) + fmt.Println(string(data)) +} + +func TestClient_GroupWhiteListAdd(t *testing.T) { + args := &GroupWhiteList{ + WhiteLists: []string{"127.0.0.1"}, + } + err := client.GroupWhiteListAdd("scs-group-szqbjupjjhpl", args) + if err != nil { + fmt.Printf("group white list add error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupWhiteListDelete(t *testing.T) { + args := &GroupWhiteList{ + WhiteLists: []string{"127.0.0.1"}, + } + err := client.GroupWhiteListDelete("scs-group-szqbjupjjhpl", args) + if err != nil { + fmt.Printf("group white list delete error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GroupStaleReadable(t *testing.T) { + args := &StaleReadableArgs{ + FollowerId: SCS_TEST_ID, + StaleReadable: true, + } + err := client.GroupStaleReadable("scs-group-szqbjupjjhpl", args) + if err != nil { + fmt.Printf("group stale readable error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateParamsTemplate(t *testing.T) { + args := &CreateTemplateArgs{ + EngineVersion: "5.0", + TemplateType: 1, + ClusterType: "master_slave", + Engine: "redis", + Name: "test_template", + Comment: "test template", + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, + } + result, err := client.CreateParamsTemplate(args) + if err != nil { + fmt.Printf("create params template error: %+v\n", err) + return + } + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetParamsTemplateList(t *testing.T) { + args := &Marker{ + Marker: "-1", + MaxKeys: 1000, + } + result, err := client.GetParamsTemplateList(args) + if err != nil { + fmt.Printf("get params template error: %+v\n", err) + return + } + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetParamsTemplateDetail(t *testing.T) { + + result, err := client.GetParamsTemplateDetail("scs-tmpl-kctbndsfdhya") + if err != nil { + fmt.Printf("get params template detail error: %+v\n", err) + return + } + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteParamsTemplate(t *testing.T) { + err := client.DeleteParamsTemplate("scs-tmpl-vxslemqppzuz") + if err != nil { + fmt.Printf("delete params template error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_RenameParamsTemplate(t *testing.T) { + args := &RenameTemplateArgs{ + Name: "scs-test-template", + } + err := client.RenameParamsTemplate("scs-tmpl-kctbndsfdhya", args) + if err != nil { + fmt.Printf("rename params template error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ApplyParamsTemplate(t *testing.T) { + args := &ApplyTemplateArgs{ + RebootType: 0, + Extra: "0", + CacheClusterShowIdItem: []CacheClusterShowId{ + { + CacheClusterShowId: SCS_TEST_ID, + Region: "bj", + }, + }, + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, + } + err := client.ApplyParamsTemplate("scs-tmpl-kctbndsfdhya", args) + if err != nil { + fmt.Printf("apply params template error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_TemplateAddParams(t *testing.T) { + args := &AddParamsArgs{ + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, + } + err := client.TemplateAddParams("scs-tmpl-kctbndsfdhya", args) + if err != nil { + fmt.Printf("add params template error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_TemplateModifyParams(t *testing.T) { + args := &ModifyParamsArgs{ + Parameters: []ParameterItem{ + { + ConfName: "disable_commands", + ConfModule: 1, + ConfValue: "flushall,flushdb", + ConfType: 3, + }, + }, + } + err := client.TemplateModifyParams("scs-tmpl-kctbndsfdhya", args) + if err != nil { + fmt.Printf("modify params template error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_TemplateDeleteParams(t *testing.T) { + args := &DeleteParamsArgs{ + Parameters: []string{"appendonly"}, + } + err := client.TemplateDeleteParams("scs-tmpl-kctbndsfdhya", args) + if err != nil { + fmt.Printf("delete params template error: %+v\n", err) + return + } + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetapplyTemplate(t *testing.T) { + args := &GetSystemTemplateArgs{ + Engine: "redis", + EngineVersion: "5.0", + ClusterType: "master_slave", + } + result, err := client.GetSystemTemplate(args) + if err != nil { + fmt.Printf("get system template error: %+v\n", err) + return + } + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetApplyRecords(t *testing.T) { + args := &Marker{ + Marker: "-1", + MaxKeys: 100, + } + result, err := client.GetApplyRecords("scs-tmpl-kctbndsfdhya", args) + if err != nil { + fmt.Printf("get apply record error: %+v\n", err) + return + } + data, _ := json.Marshal(result) + fmt.Println(string(data)) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/scs/model.go b/bce-sdk-go/services/scs/model.go new file mode 100644 index 0000000..4cde1eb --- /dev/null +++ b/bce-sdk-go/services/scs/model.go @@ -0,0 +1,786 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package scs + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type Reservation struct { + ReservationLength int `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} + +type Billing struct { + PaymentTiming string `json:"paymentTiming"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +type Subnet struct { + ZoneName string `json:"zoneName"` + SubnetID string `json:"subnetId"` +} + +type CreateInstanceArgs struct { + Billing Billing `json:"billing"` + PurchaseCount int `json:"purchaseCount"` + InstanceName string `json:"instanceName"` + NodeType string `json:"nodeType"` + ShardNum int `json:"shardNum"` + ProxyNum int `json:"proxyNum"` + ClusterType string `json:"clusterType"` + ReplicationNum int `json:"replicationNum"` + ReplicationInfo []Replication `json:"replicationInfo"` + Port int `json:"port"` + Engine int `json:"engine,omitempty"` + EngineVersion string `json:"engineVersion"` + DiskFlavor int `json:"diskFlavor,omitempty"` + DiskType string `json:"diskType,omitempty"` + VpcID string `json:"vpcId"` + Subnets []Subnet `json:"subnets,omitempty"` + AutoRenewTimeUnit string `json:"autoRenewTimeUnit,omitempty"` + AutoRenewTime int `json:"autoRenewTime,omitempty"` + BgwGroupId string `json:"bgwGroupId,omitempty"` + ClientToken string `json:"-"` + ClientAuth string `json:"clientAuth"` + StoreType int `json:"storeType"` + EnableReadOnly int `json:"enableReadOnly,omitempty"` + Tags []model.TagModel `json:"tags"` +} + +type CreateInstanceResult struct { + InstanceIds []string `json:"instanceIds"` +} + +type InstanceModel struct { + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + InstanceStatus string `json:"instanceStatus"` + InstanceExpireTime string `json:"instanceExpireTime"` + ShardNum int `json:"shardNum"` + ReplicationNum int `json:"replicationNum"` + ClusterType string `json:"clusterType"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + VnetIP string `json:"vnetIp"` + Domain string `json:"domain"` + Port int `json:"port"` + InstanceCreateTime string `json:"instanceCreateTime"` + Capacity float64 `json:"capacity"` + UsedCapacity float64 `json:"usedCapacity"` + PaymentTiming string `json:"paymentTiming"` + ZoneNames []string `json:"zoneNames"` + Tags []model.TagModel `json:"tags"` +} + +type ListInstancesArgs struct { + Marker string + MaxKeys int +} + +type ListInstancesResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Instances []InstanceModel `json:"instances"` +} + +type ResizeInstanceArgs struct { + NodeType string `json:"nodeType"` + ShardNum int `json:"shardNum"` + IsDefer bool `json:"isDefer"` + ClientToken string `json:"-"` + DiskFlavor int `json:"diskFlavor"` + DiskType string `json:"diskType"` +} + +type ReplicationArgs struct { + ResizeType string `json:"resizeType"` + ReplicationInfo []Replication `json:"replicationInfo"` + ClientToken string `json:"-"` +} + +type Replication struct { + AvailabilityZone string `json:"availabilityZone"` + SubnetId string `json:"subnetId"` + IsMaster int `json:"isMaster"` +} +type RestartInstanceArgs struct { + IsDefer bool `json:"isDefer"` +} + +type GetInstanceDetailResult struct { + InstanceID string `json:"instanceId"` + InstanceName string `json:"instanceName"` + InstanceStatus string `json:"instanceStatus"` + ClusterType string `json:"clusterType"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + VnetIP string `json:"vnetIp"` + Domain string `json:"domain"` + Port int `json:"port"` + InstanceCreateTime string `json:"instanceCreateTime"` + InstanceExpireTime string `json:"instanceExpireTime"` + Capacity float64 `json:"capacity"` + UsedCapacity float64 `json:"usedCapacity"` + PaymentTiming string `json:"paymentTiming"` + VpcID string `json:"vpcId"` + ZoneNames []string `json:"zoneNames"` + Subnets []Subnet `json:"subnets"` + AutoRenew string `json:"autoRenew"` + Tags []model.TagModel `json:"tags"` + ShardNum int `json:"shardNum"` + ReplicationNum int `json:"replicationNum"` + NodeType string `json:"nodeType"` + DiskFlavor int `json:"diskFlavor"` + DiskType string `json:"diskType"` + StoreType int `json:"storeType"` + Eip string `json:"eip"` + PublicDomain string `json:"publicDomain"` + EnableReadOnly int `json:"enableReadOnly"` + ReplicationInfo []Replication `json:"replicationInfo"` + BnsGroup string `json:"bnsGroup"` +} + +type UpdateInstanceNameArgs struct { + InstanceName string `json:"instanceName"` + ClientToken string `json:"-"` +} + +type NodeType struct { + InstanceFlavor int `json:"instanceFlavor"` + NodeType string `json:"nodeType"` + CPUNum int `json:"cpuNum"` + NetworkThroughputInGbps float64 `json:"networkThroughputInGbps"` + PeakQPS int `json:"peakQps"` + MaxConnections int `json:"maxConnections"` + AllowedNodeNumList []int `json:"allowedNodeNumList"` +} + +type GetNodeTypeListResult struct { + ClusterNodeTypeList []NodeType `json:"clusterNodeTypeList"` + DefaultNodeTypeList []NodeType `json:"defaultNodeTypeList"` + HsdbNodeTypeList []NodeType `json:"hsdbNodeTypeList"` +} + +type ListSubnetsArgs struct { + VpcID string `json:"vpcId"` + ZoneName string `json:"zoneName"` +} + +type ListSubnetsResult struct { + SubnetOriginals []SubnetOriginal `json:"subnets"` +} + +type SubnetOriginal struct { + Name string `json:"name"` + SubnetID string `json:"subnetId"` + ZoneName string `json:"zoneName"` + Cidr string `json:"cidr"` + VpcID string `json:"vpcId"` +} + +type UpdateInstanceDomainNameArgs struct { + Domain string `json:"domain"` + ClientToken string `json:"-"` +} + +type GetZoneListResult struct { + Zones []ZoneNames `json:"zones"` +} + +type ZoneNames struct { + ZoneNames []string `json:"zoneNames"` +} + +type FlushInstanceArgs struct { + Password string `json:"password"` + ClientToken string `json:"-"` +} + +type BindingTagArgs struct { + ChangeTags []model.TagModel `json:"changeTags"` +} + +type GetSecurityIpResult struct { + SecurityIps []string `json:"securityIps"` +} + +type SecurityIpArgs struct { + SecurityIps []string `json:"securityIps"` + ClientToken string `json:"-"` +} + +type ModifyPasswordArgs struct { + Password string `json:"password"` + ClientToken string `json:"-"` +} + +type GetParametersResult struct { + Parameters []Parameter `json:"parameters"` +} + +type Parameter struct { + Default string `json:"default"` + ForceRestart string `json:"forceRestart"` + Name string `json:"name"` + Value string `json:"value"` +} + +type ModifyParametersArgs struct { + Parameter InstanceParam `json:"parameter"` + ClientToken string `json:"-"` +} + +type InstanceParam struct { + Name string `json:"name"` + Value string `json:"value"` +} + +type GetBackupListResult struct { + TotalCount string `json:"totalCount"` + Backups []BackupInfo `json:"backups"` +} + +type BackupInfo struct { + BackupType string `json:"backupType"` + Comment string `json:"comment"` + StartTime string `json:"startTime"` + Records []BackupRecord `json:"records"` +} + +type BackupRecord struct { + BackupRecordId string `json:"backupRecordId"` + BackupStatus string `json:"backupStatus"` + Duration string `json:"duration"` + ObjectSize string `json:"objectSize"` + ShardName string `json:"shardName"` + StartTime string `json:"startTime"` +} + +type ModifyBackupPolicyArgs struct { + BackupDays string `json:"backupDays"` + BackupTime string `json:"backupTime"` + ClientToken string `json:"clientToken"` + ExpireDay int `json:"expireDay"` +} + +type ListVpcSecurityGroupsResult struct { + Groups []SecurityGroup `json:"groups"` +} + +type SecurityGroup struct { + Name string `json:"name"` + SecurityGroupID string `json:"securityGroupId"` + Description string `json:"description"` + TenantID string `json:"tenantId"` + AssociateNum int `json:"associateNum"` + VpcID string `json:"vpcId"` + VpcShortID string `json:"vpcShortId"` + VpcName string `json:"vpcName"` + CreatedTime string `json:"createdTime"` + Version int `json:"version"` + DefaultSecurityGroup int `json:"defaultSecurityGroup"` +} + +type SecurityGroupArgs struct { + InstanceIds []string `json:"instanceIds"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type UnbindSecurityGroupArgs struct { + InstanceId string `json:"instanceId"` + SecurityGroupIds []string `json:"securityGroupIds"` +} + +type ListSecurityGroupResult struct { + Groups []SecurityGroupDetail `json:"groups"` +} + +type SecurityGroupRule struct { + PortRange string `json:"portRange"` + Protocol string `json:"protocol"` + RemoteGroupID string `json:"remoteGroupId"` + RemoteIP string `json:"remoteIP"` + Ethertype string `json:"ethertype"` + TenantID string `json:"tenantId"` + Name string `json:"name"` + ID string `json:"id"` + SecurityGroupRuleID string `json:"securityGroupRuleId"` + Direction string `json:"direction"` +} + +type SecurityGroupDetail struct { + SecurityGroupName string `json:"securityGroupName"` + SecurityGroupID string `json:"securityGroupId"` + SecurityGroupRemark string `json:"securityGroupRemark"` + Inbound []SecurityGroupRule `json:"inbound"` + Outbound []SecurityGroupRule `json:"outbound"` + VpcName string `json:"vpcName"` + VpcID string `json:"vpcId"` + ProjectID string `json:"projectId"` +} + +type RequestBuilder struct { +} + +type GetPriceRequest struct { + Engine string `json:"engine,omitempty"` + ShardNum int `json:"shardNum,omitempty"` + Period int `json:"period,omitempty"` + ChargeType string `json:"chargeType,omitempty"` + NodeType string `json:"nodeType,omitempty"` + ReplicationNum int `json:"replicationNum,omitempty"` + ClusterType string `json:"clusterType,omitempty"` +} + +type GetPriceResult struct { + Price float64 `json:"price,omitempty"` +} + +type Marker struct { + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ListResultWithMarker struct { + IsTruncated bool `json:"isTruncated"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` +} + +type RecycleInstance struct { + InstanceID string `json:"cacheClusterShowId"` + InstanceName string `json:"instanceName"` + InstanceStatus string `json:"instanceStatus"` + IsolatedStatus string `json:"isolatedStatus"` + ClusterType string `json:"clusterType"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + VnetIP string `json:"vnetIp"` + Domain string `json:"domain"` + Port string `json:"port"` + InstanceCreateTime string `json:"instanceCreateTime"` + Capacity float64 `json:"capacity"` + UsedCapacity float64 `json:"usedCapacity"` + PaymentTiming string `json:"paymentTiming"` + ZoneNames []string `json:"zoneNames"` + Tags []model.TagModel `json:"tags"` +} + +type RecyclerInstanceList struct { + ListResultWithMarker + Result []RecycleInstance `json:"result"` +} + +type BatchInstanceIds struct { + InstanceIds []string `json:"cacheClusterShowIds,omitempty"` +} + +type RenewInstanceArgs struct { + Duration int `json:"duration,omitempty"` + InstanceIds []string `json:"instanceIds,omitempty"` +} + +type OrderIdResult struct { + OrderId string `json:"orderId"` +} + +type ListLogArgs struct { + FileType string `json:"fileType"` + StartTime string `json:"startTime"` + EndTime string `json:"endTime"` +} + +type ListLogResult struct { + LogList []ShardLog `json:"logList"` +} +type LogItem struct { + LogStartTime string `json:"logStartTime"` + LogEndTime string `json:"logEndTime"` + DownloadURL string `json:"downloadUrl"` + LogID string `json:"logId"` + LogSizeInBytes int `json:"logSizeInBytes"` + DownloadExpires string `json:"downloadExpires"` +} +type ShardLog struct { + ShardShowID string `json:"shardShowId"` + TotalNum int `json:"totalNum"` + ShardID int `json:"shardId"` + LogItem []LogItem `json:"logItem"` +} + +type GetLogArgs struct { + ValidSeconds int `json:"validSeconds"` +} +type GetMaintainTimeResult struct { + CacheClusterShowId string `json:"cacheClusterShowId"` + MaintainTime MaintainTime `json:"maintainTime"` +} +type MaintainTime struct { + StartTime string `json:"startTime"` + Duration int `json:"duration"` + Period []int `json:"period"` +} + +type CreatePriceArgs struct { + Engine int `json:"engine,omitempty"` + ClusterType string `json:"clusterType,omitempty"` + NodeType string `json:"nodeType,omitempty"` + ShardNum int `json:"shardNum,omitempty"` + ReplicationNum int `json:"replicationNum,omitempty"` + InstanceNum int `json:"instanceNum,omitempty"` + DiskType int `json:"diskType,omitempty"` + DiskFlavor int `json:"diskFlavor,omitempty"` + ChargeType string `json:"chargeType,omitempty"` + Period int `json:"period,omitempty"` +} +type CreatePriceResult struct { + Price float64 `json:"price,omitempty"` +} + +type ResizePriceArgs struct { + NodeType string `json:"nodeType"` + ShardNum int `json:"shardNum,omitempty"` + ReplicationNum int `json:"replicationNum,omitempty"` + DiskFlavor int `json:"diskFlavor,omitempty"` + ChargeType string `json:"chargeType,omitempty"` + Period int `json:"period,omitempty"` + ChangeType string `json:"changeType,omitempty"` +} +type ResizePriceResult struct { + Price float64 `json:"price,omitempty"` +} + +type SetAsSlaveArgs struct { + MasterDomain string `json:"masterDomain"` + MasterPort int `json:"masterPort"` +} + +type RenameDomainArgs struct { + Domain string `json:"domain"` + ClientToken string `json:"clientToken,omitempty"` +} + +type SwapDomainArgs struct { + SourceInstanceId string `json:"sourceInstanceId"` + TargetInstanceId string `json:"targetInstanceId"` + ClientToken string `json:"clientToken,omitempty"` +} + +type GetBackupDetailResult struct { + Url string `json:"url"` + UrlExpiration string `json:"urlExpiration"` +} + +type GroupPreCheckArgs struct { + Leader GroupLeader `json:"leader"` + Followers []GroupFollower `json:"followers"` +} +type GroupLeader struct { + LeaderRegion string `json:"leaderRegion"` + LeaderId string `json:"leaderId"` +} +type GroupFollower struct { + FollowerId string `json:"followerId"` + FollowerRegion string `json:"followerRegion"` +} +type GroupPreCheckResult struct { + LeaderResult GroupLeaderResult `json:"leaderResult"` + FollowerResult []GroupFollowerResult `json:"followerResult"` + ConnectionResults []GroupConnectionResult `json:"connectionResults"` +} +type GroupLeaderResult struct { + Version bool `json:"version"` + ClusterStatus bool `json:"clusterStatus"` + ReplicationNum bool `json:"replicationNum"` + Flavor bool `json:"flavor"` + Joined bool `json:"joined"` + NoPasswd bool `json:"noPasswd"` + NoSecurityGroup bool `json:"noSecurityGroup"` + IsHitX1 bool `json:"isHitX1"` +} +type GroupFollowerResult struct { + FollowerId string `json:"followerId"` + NoData bool `json:"noData"` + Version bool `json:"version"` + EngineVersion bool `json:"engineVersion"` + ClusterStatus bool `json:"clusterStatus"` + ShardNum bool `json:"shardNum"` + ReplicationNum bool `json:"replicationNum"` + Flavor bool `json:"flavor"` + Joined bool `json:"joined"` + NoPasswd bool `json:"noPasswd"` + NoSecurityGroup bool `json:"noSecurityGroup"` + IsHitX1 bool `json:"isHitX1"` +} +type GroupConnectionResult struct { + SourceId string `json:"sourceId"` + SourceRole string `json:"sourceRole"` + TargetId string `json:"targetId"` + TargetRole string `json:"targetRole"` + Connectable bool `json:"connectable"` +} + +type CreateGroupArgs struct { + Leader CreateGroupLeader `json:"leader"` +} +type CreateGroupLeader struct { + GroupName string `json:"groupName"` + LeaderRegion string `json:"leaderRegion"` + LeaderId string `json:"leaderId"` +} +type CreateGroupResult struct { + GroupId string `json:"groupId"` +} +type GroupListResult struct { + TotalCount int `json:"totalCount"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + Result []GroupResult `json:"result"` +} +type GroupResult struct { + GroupId string `json:"groupId"` + GroupName string `json:"groupName"` + GroupStatus string `json:"groupStatus"` + ClusterNum int `json:"clusterNum"` + GroupCreateTime string `json:"groupCreateTime"` + ForbidWrite int `json:"forbidWrite"` + GroupType string `json:"groupType"` + LeaderName string `json:"leaderName"` + LeaderShowId string `json:"leaderShowId"` + LeaderRegion string `json:"leaderRegion"` +} +type GetGroupListArgs struct { + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` +} + +type GroupDetailResult struct { + GroupId string `json:"groupId"` + GroupName string `json:"groupName"` + GroupStatus string `json:"groupStatus"` + ClusterNum int `json:"clusterNum"` + GroupCreateTime string `json:"groupCreateTime"` + ForbidWrite int `json:"forbidWrite"` + GroupType string `json:"groupType"` + Leader GroupLeaderInfo `json:"leader"` + Followers []GroupFollowerInfo `json:"followers"` +} +type GroupLeaderInfo struct { + ClusterName string `json:"clusterName"` + ClusterShowId string `json:"clusterShowId"` + Region string `json:"region"` + Status string `json:"status"` + TotalCapacityInGB float64 `json:"totalCapacityInGB"` + UsedCapacityInGB int `json:"usedCapacityInGB"` + ShardNum int `json:"shardNum"` + Flavor int `json:"flavor"` + QpsWrite int64 `json:"qpsWrite"` + QpsRead int64 `json:"qpsRead"` + StableReadable bool `json:"stableReadable"` + ForbidWrite int `json:"forbidWrite"` + AvailabilityZone string `json:"availabilityZone"` + ExpiredTime string `json:"expiredTime"` +} +type GroupFollowerInfo struct { + ClusterName string `json:"clusterName"` + ClusterShowId string `json:"clusterShowId"` + Region string `json:"region"` + Status string `json:"status"` + TotalCapacityInGB float64 `json:"totalCapacityInGB"` + UsedCapacityInGB int `json:"usedCapacityInGB"` + ShardNum int `json:"shardNum"` + Flavor int `json:"flavor"` + QpsWrite int64 `json:"qpsWrite"` + QpsRead int64 `json:"qpsRead"` + StableReadable bool `json:"stableReadable"` + ForbidWrite int `json:"forbidWrite"` + AvailabilityZone string `json:"availabilityZone"` + ExpiredTime string `json:"expiredTime"` +} + +type FollowerInfo struct { + FollowerId string `json:"followerId"` + FollowerRegion string `json:"followerRegion"` + SyncMaster string `json:"syncMaster"` +} + +type GroupNameArgs struct { + GroupName string `json:"groupName"` +} + +type ForbidWriteArgs struct { + ForbidWriteFlag bool `json:"forbidWriteFlag"` +} + +type GroupSetQpsArgs struct { + ClusterShowId string `json:"clusterShowId"` + QpsWrite int `json:"qpsWrite"` + QpsRead int `json:"qpsRead"` +} + +type GroupSyncStatusResult struct { + Followers []FollowerSyncInfo `json:"followers"` +} + +type FollowerSyncInfo struct { + ClusterShowId string `json:"clusterShowId"` + SyncStatus string `json:"syncStatus"` + MaxOffset int `json:"maxOffset"` + Lag int `json:"lag"` +} + +type GroupWhiteList struct { + WhiteLists []string `json:"whiteLists"` +} + +type StaleReadableArgs struct { + FollowerId string `json:"followerId"` + StaleReadable bool `json:"staleReadable"` +} + +type CreateTemplateArgs struct { + EngineVersion string `json:"engineVersion"` + TemplateType int `json:"templateType"` + ClusterType string `json:"clusterType"` + Engine string `json:"engine"` + Name string `json:"name"` + Comment string `json:"comment"` + Parameters []ParameterItem `json:"parameters"` +} +type ParameterItem struct { + ConfName string `json:"confName"` + ConfModule int `json:"confModule"` + ConfValue string `json:"confValue"` + ConfType int `json:"confType"` +} +type CreateParamsTemplateResult struct { + TemplateId int `json:"templateId"` + TemplateShowId string `json:"templateShowId"` +} + +type ParamsTemplateListResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + Result []ResultItem `json:"result"` +} +type ResultItem struct { + EngineVersion string `json:"engineVersion"` + TemplateType int `json:"templateType"` + ClusterType string `json:"clusterType"` + NeedReboot int `json:"needReboot"` + TemplateShowId string `json:"templateShowId"` + UpdateTime string `json:"updateTime"` + TemplateId int `json:"templateId"` + ParameterNum int `json:"parameterNum"` + TemplateName string `json:"templateName"` + Engine string `json:"engine"` + CreateTime string `json:"createTime"` + Comment string `json:"comment"` + Parameters []ParamItem `json:"parameters"` +} + +type ParamItem struct { + ConfName string `json:"confName"` + ConfModule int `json:"confModule"` + ConfCacheVersion int `json:"confCacheVersion"` + ConfValue string `json:"confValue"` + NeedReboot int `json:"needReboot"` + ConfRedisVersion string `json:"confRedisVersion"` + ConfDefault string `json:"confDefault"` + ConfType int `json:"confType"` + ConfRange string `json:"confRange"` + ConfDesc string `json:"confDesc"` + ConfUserVisible int `json:"confUserVisible"` +} + +type RenameTemplateArgs struct { + Name string `json:"name"` +} + +type ApplyTemplateArgs struct { + RebootType int `json:"rebootType"` + Extra string `json:"extra"` + CacheClusterShowIdItem []CacheClusterShowId `json:"cacheClusterShowId"` + Parameters []ParameterItem `json:"parameters"` +} +type CacheClusterShowId struct { + CacheClusterShowId string `json:"cacheClusterShowId"` + Region string `json:"region"` +} + +type AddParamsArgs struct { + Parameters []ParameterItem `json:"parameters"` +} + +type ModifyParamsArgs struct { + Parameters []ParameterItem `json:"parameters"` +} + +type DeleteParamsArgs struct { + Parameters []string `json:"parameters"` +} + +type GetSystemTemplateArgs struct { + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + ClusterType string `json:"clusterType"` +} + +type SystemTemplateResult struct { + Success bool `json:"success"` + Result []SystemTemplate `json:"result"` +} + +type SystemTemplate struct { + ConfName string `json:"confName"` + ConfDefault string `json:"confDefault"` + ConfValue string `json:"confValue"` + ConfType int `json:"confType"` + ConfRange string `json:"confRange"` + ConfModule int `json:"confModule"` + ConfDesc string `json:"confDesc"` + NeedReboot int `json:"needReboot"` + ConfRedisVersion string `json:"confRedisVersion"` + ConfCacheVersion int `json:"confCacheVersion"` +} + +type GetApplyRecordsResult struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + NextMarker string `json:"nextMarker"` + IsTruncated bool `json:"isTruncated"` + Result []ApplyRecord `json:"result"` +} + +type ApplyRecord struct { + CacheClusterShowId string `json:"cacheClusterShowId"` + CacheClusterName string `json:"cacheClusterName"` + AvailabilityZone string `json:"availabilityZone"` + Version int `json:"version"` + Status string `json:"status"` + Engine string `json:"engine"` + EngineVersion string `json:"engineVersion"` + ClusterType string `json:"clusterType"` + CreateTime string `json:"createTime"` + ApplyTime string `json:"applyTime"` +} diff --git a/bce-sdk-go/services/scs/scs.go b/bce-sdk-go/services/scs/scs.go new file mode 100644 index 0000000..367885b --- /dev/null +++ b/bce-sdk-go/services/scs/scs.go @@ -0,0 +1,1632 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// scs.go - the SCS for Redis APIs definition supported by the redis service +package scs + +import ( + "encoding/json" + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + KEY_MARKER = "marker" + KEY_MAX_KEYS = "maxKeys" + INSTANCE_URL_V1 = bce.URI_PREFIX + "v1" + "/instance" + INSTANCE_URL_V2 = bce.URI_PREFIX + "v2" + "/instance" + URI_PREFIX_V2 = bce.URI_PREFIX + "v2" + URI_PREFIX_V1 = bce.URI_PREFIX + "v1" + REQUEST_SECURITYGROUP_URL = "/security" + REQUEST_RECYCLER_URL = "/recycler" +) + +func (c *Client) request(method, url string, result, body interface{}) (interface{}, error) { + var err error + if result != nil { + err = bce.NewRequestBuilder(c). + WithMethod(method). + WithURL(url). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(body). + WithResult(result). + Do() + } else { + err = bce.NewRequestBuilder(c). + WithMethod(method). + WithURL(url). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(body). + Do() + } + // fmt.Println(Json(result)) + return result, err +} + +func getInstanceUrlWithId(instanceId string) string { + return INSTANCE_URL_V1 + "/" + instanceId +} + +// List Security Group By Vpc URL +func getSecurityGroupWithVpcIdUrl(vpcId string) string { + return URI_PREFIX_V2 + REQUEST_SECURITYGROUP_URL + "/vpc/" + vpcId +} + +// List Security Group By Instance URL +func getSecurityGroupWithInstanceIdUrl(instanceId string) string { + return URI_PREFIX_V2 + REQUEST_SECURITYGROUP_URL + "/instance/" + instanceId +} + +// Bind Security Group To Instance URL +func getBindSecurityGroupWithUrl() string { + return URI_PREFIX_V2 + REQUEST_SECURITYGROUP_URL + "/bind" +} + +// UnBind Security Group To Instance URL +func getUnBindSecurityGroupWithUrl() string { + return URI_PREFIX_V2 + REQUEST_SECURITYGROUP_URL + "/unbind" +} + +// Batch Replace Security Group URL +func getReplaceSecurityGroupWithUrl() string { + return URI_PREFIX_V2 + REQUEST_SECURITYGROUP_URL + "/update" +} + +// Recycler URL +func getRecyclerUrl() string { + return URI_PREFIX_V2 + REQUEST_RECYCLER_URL + "/list" +} + +// Recycler Recover URL +func getRecyclerRecoverUrl() string { + return URI_PREFIX_V2 + REQUEST_RECYCLER_URL + "/recover" +} + +// Recycler Recover URL +func getRecyclerDeleteUrl() string { + return URI_PREFIX_V2 + REQUEST_RECYCLER_URL + "/delete" +} + +// Renew Instance URL +func getRenewUrl() string { + return INSTANCE_URL_V2 + "/renew" +} + +func getLogsUrlWithInstanceId(instanceId string) string { + return INSTANCE_URL_V1 + "/" + instanceId + "/log" +} + +func getLogsUrlWithLogId(instanceId, logId string) string { + return INSTANCE_URL_V1 + "/" + instanceId + "/log/" + logId +} + +func getGroupUrl() string { + return "/v2/group" +} +func getTemplateUrl() string { + return "/v2/template" +} + +func Json(v interface{}) string { + jsonStr, err := json.Marshal(v) + if err != nil { + panic("convert to json faild") + } + return string(jsonStr) +} + +// Convert marker to request params +func getMarkerParams(marker *Marker) map[string]string { + if marker == nil { + marker = &Marker{Marker: "-1"} + } + params := make(map[string]string, 2) + params[KEY_MARKER] = marker.Marker + if marker.MaxKeys > 0 { + params[KEY_MAX_KEYS] = strconv.Itoa(marker.MaxKeys) + } + return params +} + +// Convert struct to request params +func getQueryParams(val interface{}) (map[string]string, error) { + var params map[string]string + if val != nil { + err := json.Unmarshal([]byte(Json(val)), ¶ms) + if err != nil { + return nil, err + } + } + return params, nil +} + +// CreateInstance - create an instance with specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to create instance +// +// RETURNS: +// - *CreateInstanceResult: result of the instance ids newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateInstance(args *CreateInstanceArgs) (*CreateInstanceResult, error) { + if args == nil { + return nil, fmt.Errorf("please set create scs argments") + } + if len(args.ClientAuth) != 0 { + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.ClientAuth) + if err != nil { + return nil, err + } + args.ClientAuth = cryptedPass + } + result := &CreateInstanceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(INSTANCE_URL_V2). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// ListInstances - list all instances with the specified parameters +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list instances +// +// RETURNS: +// - *ListInstanceResult: result of the instance list +// - error: nil if success otherwise the specific error +func (c *Client) ListInstances(args *ListInstancesArgs) (*ListInstancesResult, error) { + if args == nil { + args = &ListInstancesArgs{} + } + + if args.MaxKeys <= 0 || args.MaxKeys > 1000 { + args.MaxKeys = 1000 + } + + result := &ListInstancesResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(INSTANCE_URL_V2). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetInstanceDetail - get details of the specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetInstanceDetailResult: result of the instance details +// - error: nil if success otherwise the specific error +func (c *Client) GetInstanceDetail(instanceId string) (*GetInstanceDetailResult, error) { + result := &GetInstanceDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(INSTANCE_URL_V2 + "/" + instanceId). + WithResult(result). + Do() + + return result, err +} + +// ResizeInstance - resize a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be resized +// - reqBody: the request body to resize instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeInstance(instanceId string, args *ResizeInstanceArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/change"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// GetCreatePrice - get create price +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - reqBody: the request body to get price +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetCreatePriceResult: result of the create price +func (c *Client) GetCreatePrice(args *CreatePriceArgs) (*CreatePriceResult, error) { + result := &CreatePriceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL("/v2/price"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// GetResizePrice - get resize price +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be resized +// - reqBody: the request body to get resize price +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetResizePriceResult: result of the resize price +func (c *Client) GetResizePrice(instanceId string, args *ResizePriceArgs) (*ResizePriceResult, error) { + result := &ResizePriceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(INSTANCE_URL_V2+"/"+instanceId+"/price"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// AddReplication - add replications +// +// PARAMS: +// - instanceId: id of the instance to be resized +// - args: replicationInfo +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AddReplication(instanceId string, args *ReplicationArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(INSTANCE_URL_V2+"/"+instanceId+"/resizeReplication"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteReplication - delete replications +// +// PARAMS: +// - instanceId: id of the instance to be resized +// - args: replicationInfo +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteReplication(instanceId string, args *ReplicationArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(INSTANCE_URL_V2+"/"+instanceId+"/resizeReplication"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// RestartInstance - restart a specified instance +// +// PARAMS: +// - instanceId: id of the instance to be resized +// - args: specify restart immediately or postpone restart to time window +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RestartInstance(instanceId string, args *RestartInstanceArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceUrlWithId(instanceId)+"/restart"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() +} + +// DeleteInstance - delete a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteInstance(instanceId string, clientToken string) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(INSTANCE_URL_V1+"/"+instanceId). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// UpdateInstanceName - update name of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// - args: the arguments to Update instanceName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceName(instanceId string, args *UpdateInstanceNameArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/rename"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// GetNodeTypeList - list all nodetype +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance to be deleted +// - args: the arguments to Update instanceName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GetNodeTypeList() (*GetNodeTypeListResult, error) { + getNodeTypeListResult := &GetNodeTypeListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL("/v2/nodetypes"). + WithResult(getNodeTypeListResult). + Do() + + return getNodeTypeListResult, err +} + +// ListsSubnet - list all Subnets +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to list all subnets, not necessary +// +// RETURNS: +// - *ListSubnetsResult: result of the subnet list +// - error: nil if success otherwise the specific error +func (c *Client) ListSubnets(args *ListSubnetsArgs) (*ListSubnetsResult, error) { + if args == nil { + args = &ListSubnetsArgs{} + } + + result := &ListSubnetsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL("/v1/subnet"). + WithQueryParamFilter("vpcId", args.VpcID). + WithQueryParamFilter("zoneName", args.ZoneName). + WithResult(result). + Do() + + return result, err +} + +// UpdateInstanceDomainName - update name of a specified instance domain +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to update domainName +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateInstanceDomainName(instanceId string, args *UpdateInstanceDomainNameArgs) error { + + if args == nil || args.Domain == "" { + return fmt.Errorf("unset Domain") + } + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/renameDomain"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// GetZoneList - list all zone +// +// PARAMS: +// - cli: the client agent which can perform sending request +// +// RETURNS: +// - *GetZoneListResult: result of the zone list +// - error: nil if success otherwise the specific error +func (c *Client) GetZoneList() (*GetZoneListResult, error) { + result := &GetZoneListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL("/v1/zone"). + WithResult(result). + Do() + + return result, err +} + +// FlushInstance - flush a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to flush instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) FlushInstance(instanceId string, args *FlushInstanceArgs) error { + + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.Password) + if err != nil { + return err + } + args.Password = cryptedPass + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/flush"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// BindingTags - bind tags to a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to bind tags to instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindingTag(instanceId string, args *BindingTagArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1 + "/" + instanceId + "/bindTag"). + WithBody(args). + Do() +} + +// UnBindingTags - unbind tags to a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to unbind tags to instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindingTag(instanceId string, args *BindingTagArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1 + "/" + instanceId + "/unBindTag"). + WithBody(args). + Do() +} + +// SetAsMaster - set instance as master +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SetAsMaster(instanceId string) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V2 + "/" + instanceId + "/setAsMaster"). + Do() +} + +// SetAsSlave - set instance as master +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to set instance as slave +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SetAsSlave(instanceId string, args *SetAsSlaveArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithBody(args). + WithURL(INSTANCE_URL_V2 + "/" + instanceId + "/setAsSlave"). + Do() +} + +// GetSecurityIp - list all securityIps +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *ListSecurityIp: result of the security IP list +// - error: nil if success otherwise the specific error +func (c *Client) GetSecurityIp(instanceId string) (*GetSecurityIpResult, error) { + + result := &GetSecurityIpResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(INSTANCE_URL_V1 + "/" + instanceId + "/securityIp"). + WithResult(result). + Do() + + return result, err +} + +// AddSecurityIp - add securityIp to access a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to add securityIp +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AddSecurityIp(instanceId string, args *SecurityIpArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/securityIp"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// DeleteSecurityIp - delete securityIp to access a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to delete securityIp +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSecurityIp(instanceId string, args *SecurityIpArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/securityIp"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// ModifyPassword - modify the password of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to Modify Password +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyPassword(instanceId string, args *ModifyPasswordArgs) error { + + cryptedPass, err := Aes128EncryptUseSecreteKey(c.Config.Credentials.SecretAccessKey, args.Password) + if err != nil { + return err + } + args.Password = cryptedPass + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/modifyPassword"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// RenameDomain - rename domain +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to rename domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenameDomain(instanceId string, args *RenameDomainArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V2+"/"+instanceId+"/renameDomain"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// SwapDomain - swap domain +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to swap domain +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SwapDomain(instanceId string, args *SwapDomainArgs) error { + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(INSTANCE_URL_V2+"/"+instanceId+"/swapDomain"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// GetParameters - query the configuration parameters and running parameters of redis instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetParameterResult: result of the parameters +// - error: nil if success otherwise the specific error +func (c *Client) GetParameters(instanceId string) (*GetParametersResult, error) { + + result := &GetParametersResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(INSTANCE_URL_V1 + "/" + instanceId + "/parameter"). + WithResult(result). + Do() + + return result, err +} + +// ModifyParameters - modify the parameters of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to modify parameters +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyParameters(instanceId string, args *ModifyParametersArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/parameter"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// GetBackupList - get backup list of the instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - *GetBackupListResult: result of the backup list +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupList(instanceId string) (*GetBackupListResult, error) { + + result := &GetBackupListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(INSTANCE_URL_V1 + "/" + instanceId + "/backup"). + WithResult(result). + Do() + + return result, err +} + +// GetBackupDetail - get backup detail of the instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - backupRecordId: the backup record id +// +// RETURNS: +// - *GetBackupDetailResult: result of the backup detail +// - error: nil if success otherwise the specific error +func (c *Client) GetBackupDetail(instanceId, backupRecordId string) (*GetBackupDetailResult, error) { + + result := &GetBackupDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(INSTANCE_URL_V1 + "/" + instanceId + "/backup/" + backupRecordId). + WithResult(result). + Do() + + return result, err +} + +// ModifyBackupPolicy - modify the BackupPolicy of a specified instance +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// - args: the arguments to Modify BackupPolicy +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyBackupPolicy(instanceId string, args *ModifyBackupPolicyArgs) error { + + return bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(INSTANCE_URL_V1+"/"+instanceId+"/modifyBackupPolicy"). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// ListSecurityGroupByVpcId - list security groups by vpc id +// +// PARAMS: +// - vpcId: id of vpc +// +// RETURNS: +// - *[]SecurityGroup:security groups of vpc +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroupByVpcId(vpcId string) (*ListVpcSecurityGroupsResult, error) { + if len(vpcId) < 1 { + return nil, fmt.Errorf("unset vpcId") + } + result := &ListVpcSecurityGroupsResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupWithVpcIdUrl(vpcId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// ListSecurityGroupByInstanceId - list security groups by instance id +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *ListSecurityGroupResult: list secrity groups result of instance +// - error: nil if success otherwise the specific error +func (c *Client) ListSecurityGroupByInstanceId(instanceId string) (*ListSecurityGroupResult, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + result := &ListSecurityGroupResult{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getSecurityGroupWithInstanceIdUrl(instanceId)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// BindSecurityGroups - bind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(args.InstanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(args.SecurityGroupIds) < 1 { + return fmt.Errorf("unset securityGroupIds") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getBindSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// UnBindSecurityGroups - unbind SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindSecurityGroups(args *UnbindSecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(args.InstanceId) < 1 { + return fmt.Errorf("unset instanceId") + } + if len(args.SecurityGroupIds) < 1 { + return fmt.Errorf("unset securityGroupIds") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getUnBindSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ReplaceSecurityGroups - replace SecurityGroup to instances +// +// PARAMS: +// - args: http request body +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ReplaceSecurityGroups(args *SecurityGroupArgs) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(args.InstanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(args.SecurityGroupIds) < 1 { + return fmt.Errorf("unset securityGroupIds") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getReplaceSecurityGroupWithUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ListRecycleInstances - list all instances in recycler with marker +// +// PARAMS: +// - marker: marker page +// +// RETURNS: +// - *RecyclerInstanceList: the result of instances in recycler +// - error: nil if success otherwise the specific error +func (c *Client) ListRecycleInstances(marker *Marker) (*RecyclerInstanceList, error) { + result := &RecyclerInstanceList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithQueryParams(getMarkerParams(marker)). + WithURL(getRecyclerUrl()). + WithResult(result). + Do() + + return result, err +} + +// RecoverRecyclerInstances - batch recover instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to recover +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RecoverRecyclerInstances(instanceIds []string) error { + if instanceIds == nil || len(instanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return fmt.Errorf("the instanceIds length max value is 10") + } + + args := &BatchInstanceIds{ + InstanceIds: instanceIds, + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRecyclerRecoverUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// DeleteRecyclerInstances - batch delete instances that in recycler +// +// PARAMS: +// - instanceIds: instanceId list to delete +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRecyclerInstances(instanceIds []string) error { + if instanceIds == nil || len(instanceIds) < 1 { + return fmt.Errorf("unset instanceIds") + } + if len(instanceIds) > 10 { + return fmt.Errorf("the instanceIds length max value is 10") + } + + args := &BatchInstanceIds{ + InstanceIds: instanceIds, + } + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRecyclerDeleteUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// RenewInstances - batch renew instances +// +// PARAMS: +// - args: renew instanceIds and duration +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenewInstances(args *RenewInstanceArgs) (*OrderIdResult, error) { + if args == nil { + return nil, fmt.Errorf("unset args") + } + if args.InstanceIds == nil || len(args.InstanceIds) < 1 { + return nil, fmt.Errorf("unset instanceIds") + } + if len(args.InstanceIds) > 10 { + return nil, fmt.Errorf("the instanceIds length max value is 10") + } + result := &OrderIdResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getRenewUrl()). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// ListLogByInstanceId - list error or slow logs of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *[]Log:logs of instance +// - error: nil if success otherwise the specific error +func (c *Client) ListLogByInstanceId(instanceId string, args *ListLogArgs) (*ListLogResult, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if args == nil { + return nil, fmt.Errorf("unset list log args") + } + params, err2 := getQueryParams(args) + if err2 != nil { + return nil, err2 + } + result := &ListLogResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getLogsUrlWithInstanceId(instanceId)). + WithQueryParams(params). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetLogById - get log's detail of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *Log:log's detail of instance +// - error: nil if success otherwise the specific error +func (c *Client) GetLogById(instanceId, logId string, args *GetLogArgs) (*LogItem, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + if len(logId) < 1 { + return nil, fmt.Errorf("unset logId") + } + if args == nil { + return nil, fmt.Errorf("unset get log args") + } + + result := &LogItem{} + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getLogsUrlWithLogId(instanceId, logId)). + WithQueryParam("validSeconds", strconv.Itoa(args.ValidSeconds)). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetMaintainTime - get maintainTime of instance +// +// PARAMS: +// - instanceId: id of instance +// +// RETURNS: +// - *GetMaintainTimeResult:maintainTime of instance +// - error: nil if success otherwise the specific error +func (c *Client) GetMaintainTime(instanceId string) (*GetMaintainTimeResult, error) { + if len(instanceId) < 1 { + return nil, fmt.Errorf("unset instanceId") + } + + result := &GetMaintainTimeResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getInstanceUrlWithId(instanceId)+"/maintainTime"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// ModifyMaintainTime - modify MaintainTime of instance +// +// PARAMS: +// - args: new maintainTime +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ModifyMaintainTime(instanceId string, args *MaintainTime) error { + if args == nil { + return fmt.Errorf("unset args") + } + if len(instanceId) < 1 { + return fmt.Errorf("unset instanceIds") + } + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getInstanceUrlWithId(instanceId)+"/maintainTime"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + if err != nil { + return err + } + return nil +} + +// GroupPreCheck - group preCheck +// +// PARAMS: +// - args: the argumetns to group preCheck +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GroupPreCheckResult: the result of group preCheck +func (c *Client) GroupPreCheck(args *GroupPreCheckArgs) (*GroupPreCheckResult, error) { + result := &GroupPreCheckResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGroupUrl()+"/check"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// CreateGroup - create group +// +// PARAMS: +// - args: the argumetns to create group +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *CreateGroupResult: the result of create group +func (c *Client) CreateGroup(args *CreateGroupArgs) (*CreateGroupResult, error) { + result := &CreateGroupResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGroupUrl()+"/create"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// GetGroupList - get group list +// +// PARAMS: +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GroupListResult: the result of group list +func (c *Client) GetGroupList(args *GetGroupListArgs) (*GroupListResult, error) { + result := &GroupListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGroupUrl()+"/list"). + WithBody(args). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GetGroupDetail - get group detail +// +// PARAMS: +// - groupId: the group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GroupDetailResult: the result of group detail +func (c *Client) GetGroupDetail(groupId string) (*GroupDetailResult, error) { + result := &GroupDetailResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGroupUrl()+"/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// DeleteGroup - delete group +// +// PARAMS: +// - groupId: the group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteGroup(groupId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getGroupUrl()+"/"+groupId+"/release"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + return err +} + +// GroupAddFollower - add follower to a group +// +// PARAMS: +// - groupId: the group id +// - args: the arguments to add follower +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupAddFollower(groupId string, args *FollowerInfo) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGroupUrl()+"/"+groupId+"/join"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GroupRemoveFollower - remove follower to a group +// +// PARAMS: +// - groupId: the group id +// - instanceId: the instance id which to remove +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupRemoveFollower(groupId, instanceId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGroupUrl()+"/"+groupId+"/quit/"+instanceId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + return err +} + +// SetAsLeader - set instance as leader +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - instanceId: id of the instance +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SetAsLeader(groupId, instanceId string) error { + return bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getGroupUrl() + "/" + groupId + "/setAsLeader/" + instanceId). + Do() +} + +// UpdateGroupName - update group name +// +// PARAMS: +// - groupId: the group id +// - args: the arguments to update group name +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateGroupName(groupId string, args *GroupNameArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGroupUrl()+"/"+groupId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GroupForbidWrite - forbid write permission +// +// PARAMS: +// - groupId: the group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupForbidWrite(groupId string, args *ForbidWriteArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGroupUrl()+"/"+groupId+"/forbidWrite"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GroupSetQps - set group qps +// PARAMS: +// - groupId: the group id +// - args: the arguments to set group qps +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupSetQps(groupId string, args *GroupSetQpsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGroupUrl()+"/"+groupId+"/qps"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GroupSyncStatus - get group sync status +// +// PARAMS: +// - groupId: the group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GroupSyncStatusResult: the result of group sync status +func (c *Client) GroupSyncStatus(groupId string) (*GroupSyncStatusResult, error) { + result := &GroupSyncStatusResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGroupUrl()+"/"+groupId+"/syncStatus"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GroupWhiteList - get group white list +// +// PARAMS: +// - groupId: the group id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GroupWhiteListResult: the result of group sync status +func (c *Client) GroupWhiteList(groupId string) (*GroupWhiteList, error) { + result := &GroupWhiteList{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getGroupUrl()+"/"+groupId+"/white_list"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// GroupWhiteListAdd - add group white list +// +// PARAMS: +// - groupId: the group id +// - args: the arguments to add group white list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupWhiteListAdd(groupId string, args *GroupWhiteList) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGroupUrl()+"/"+groupId+"/white_list/add"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GroupWhiteListDelete - delete group white list +// +// PARAMS: +// - groupId: the group id +// - args: the arguments to delete group white list +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupWhiteListDelete(groupId string, args *GroupWhiteList) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGroupUrl()+"/"+groupId+"/white_list/delete"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GroupStaleReadable - set group follower stale readable +// +// PARAMS: +// - groupId: the group id +// - args: the arguments to set group follower stale readable +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) GroupStaleReadable(groupId string, args *StaleReadableArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getGroupUrl()+"/"+groupId+"/stale_readable"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// CreateParamsTemplate - create params template +// +// PARAMS: +// - args: the arguments to create params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *CreateParamsTemplateResult: the result of create params template +func (c *Client) CreateParamsTemplate(args *CreateTemplateArgs) (*CreateParamsTemplateResult, error) { + result := &CreateParamsTemplateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getTemplateUrl()+"/create"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// GetParamsTemplateList - get params template list +// +// PARAMS: +// - marker: pagination marker +// - maxkeys : max keys +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ParamsTemplateListResult: the result of get params template list +func (c *Client) GetParamsTemplateList(marker *Marker) (*ParamsTemplateListResult, error) { + result := &ParamsTemplateListResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTemplateUrl()+"/list"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParams(getMarkerParams(marker)). + WithResult(result). + Do() + return result, err +} + +// GetParamsTemplateDetail - get params template detail +// +// PARAMS: +// - templateId: the template id +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *ParamsTemplateDetailResult: the result of get params template detail +func (c *Client) GetParamsTemplateDetail(templateId string) (*ResultItem, error) { + result := &ResultItem{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTemplateUrl()+"/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithResult(result). + Do() + return result, err +} + +// DeleteParamsTemplate - delete params template +// +// PARAMS: +// - templateId: the template id +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteParamsTemplate(templateId string) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getTemplateUrl()+"/delete/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + Do() + return err +} + +// RenameParamsTemplate - rename params template +// +// PARAMS: +// - templateId: the template id +// - args : new template name args +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenameParamsTemplate(templateId string, args *RenameTemplateArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.PUT). + WithURL(getTemplateUrl()+"/rename/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// ApplyParamsTemplate - apply params template +// +// PARAMS: +// - templateId: the template id +// - args : the args to apply params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ApplyParamsTemplate(templateId string, args *ApplyTemplateArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getTemplateUrl()+"/apply/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// TemplateAddParams - add params to template +// +// PARAMS: +// - templateId: the template id +// - args : the args to add params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) TemplateAddParams(templateId string, args *AddParamsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getTemplateUrl()+"/addParams/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// TemplateModifyParams - modify params to template +// +// PARAMS: +// - templateId: the template id +// - args : the args to modify params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) TemplateModifyParams(templateId string, args *ModifyParamsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getTemplateUrl()+"/modifyParams/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// TemplateDeleteParams - delete params to template +// +// PARAMS: +// - templateId: the template id +// - args : the args to delete params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) TemplateDeleteParams(templateId string, args *DeleteParamsArgs) error { + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getTemplateUrl()+"/deleteParams/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + Do() + return err +} + +// GetSystemTemplate - get system template +// +// PARAMS: +// - args : the args to get system params template +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *SystemTemptaleResult: the result of get system template +func (c *Client) GetSystemTemplate(args *GetSystemTemplateArgs) (*SystemTemplateResult, error) { + result := &SystemTemplateResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTemplateUrl()+"/system"). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithBody(args). + WithQueryParamFilter("engine", args.Engine). + WithQueryParamFilter("engineVersion", args.EngineVersion). + WithQueryParamFilter("clusterType", args.ClusterType). + WithResult(result). + Do() + return result, err +} + +// GetApplyRecords - get template apply records +// +// PARAMS: +// - args : the args to get template apply records +// +// RETURNS: +// - error: nil if success otherwise the specific error +// - *GetApplyRecordsResult: the result of get template apply records +func (c *Client) GetApplyRecords(templateId string, marker *Marker) (*GetApplyRecordsResult, error) { + result := &GetApplyRecordsResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getTemplateUrl()+"/record/"+templateId). + WithHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE). + WithQueryParams(getMarkerParams(marker)). + WithResult(result). + Do() + return result, err +} diff --git a/bce-sdk-go/services/scs/util.go b/bce-sdk-go/services/scs/util.go new file mode 100644 index 0000000..c47739d --- /dev/null +++ b/bce-sdk-go/services/scs/util.go @@ -0,0 +1,36 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of SCS service +package scs + +import ( + "encoding/hex" + "fmt" + + "github.com/baidubce/bce-sdk-go/util/crypto" +) + +func Aes128EncryptUseSecreteKey(sk string, data string) (string, error) { + if len(sk) < 16 { + return "", fmt.Errorf("error secrete key") + } + + crypted, err := crypto.EBCEncrypto([]byte(sk[:16]), []byte(data)) + if err != nil { + return "", err + } + + return hex.EncodeToString(crypted), nil +} diff --git a/bce-sdk-go/services/sms/api/mobile_black.go b/bce-sdk-go/services/sms/api/mobile_black.go new file mode 100644 index 0000000..0fee006 --- /dev/null +++ b/bce-sdk-go/services/sms/api/mobile_black.go @@ -0,0 +1,157 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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. + */ + +// mobile_black.go - the sms MobileBlack APIs definition supported by the SMS service + +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateMobileBlack - create an sms MobileBlack +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create an sms mobileBlack +// +// RETURNS: +// - error: the return error if any occurs +func CreateMobileBlack(cli bce.Client, args *CreateMobileBlackArgs) error { + if err := CheckError(args != nil, "CreateMobileBlackArgs can not be nil"); err != nil { + return err + } + if err := CheckError(len(args.Type) > 0, "type can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.Phone) > 0, "phone can not be blank"); err != nil { + return err + } + if args.Type == "SignatureBlack" { + if err := CheckError(len(args.SmsType) > 0, + "smsType can not be blank, when 'type' is 'SignatureBlack'."); err != nil { + return err + } + if err := CheckError(len(args.SignatureIdStr) > 0, + "signatureIdStr can not be blank, when 'type' is 'SignatureBlack'."); err != nil { + return err + } + } + + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_BLACK) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// DeleteMobileBlack - delete sms mobileBlack by phones +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to delete sms mobileBlack +// +// RETURNS: +// - error: the return error if any occurs +func DeleteMobileBlack(cli bce.Client, args *DeleteMobileBlackArgs) error { + if err := CheckError(args != nil, "DeleteMobileBlackArgs can not be nil"); err != nil { + return err + } + if err := CheckError(len(args.Phones) > 0, "Phones can not be blank"); err != nil { + return err + } + return bce.NewRequestBuilder(cli). + WithMethod(http.DELETE). + WithURL(REQUEST_URI_BLACK+"/delete"). + WithQueryParam("phones", args.Phones). + Do() +} + +// GetMobileBlack - get sms mobileBlackList +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get sms mobileBlackList +// +// RETURNS: +// - error: the return error if any occurs +// - *api.GetMobileBlackResult: the result of get sms MobileBlackList +func GetMobileBlack(cli bce.Client, args *GetMobileBlackArgs) (*GetMobileBlackResult, error) { + if err := CheckError(args != nil, "GetMobileBlackArgs can not be nil"); err != nil { + return nil, err + } + + paramsMap := make(map[string]string) + if len(args.Phone) > 0 { + paramsMap["phone"] = args.Phone + } + if len(args.SmsType) > 0 { + paramsMap["smsType"] = args.SmsType + } + if len(args.SignatureIdStr) > 0 { + paramsMap["signatureIdStr"] = args.SignatureIdStr + } + if len(args.StartTime) > 0 { + paramsMap["startTime"] = args.StartTime + } + if len(args.EndTime) > 0 { + paramsMap["endTime"] = args.EndTime + } + if len(args.PageNo) > 0 { + paramsMap["pageNo"] = args.PageNo + } + if len(args.PageSize) > 0 { + paramsMap["pageSize"] = args.PageSize + } + + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_BLACK) + req.SetMethod(http.GET) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetParams(paramsMap) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + result := &GetMobileBlackResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/sms/api/model.go b/bce-sdk-go/services/sms/api/model.go new file mode 100644 index 0000000..79ef37f --- /dev/null +++ b/bce-sdk-go/services/sms/api/model.go @@ -0,0 +1,253 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package api + +// SendSmsArgs defines the data structure for sending a SMS request +type SendSmsArgs struct { + Mobile string `json:"mobile"` + Template string `json:"template"` + SignatureId string `json:"signatureId"` + ContentVar map[string]interface{} `json:"contentVar"` + Custom string `json:"custom,omitempty"` + UserExtId string `json:"userExtId,omitempty"` + CallbackUrlId string `json:"merchantUrlId,omitempty"` + ClientToken string `json:"clientToken,omitempty"` +} + +// SendSmsResult defines the data structure of the result of sending a SMS request +type SendSmsResult struct { + Code string `json:"code"` + RequestId string `json:"requestId"` + Message string `json:"message"` + Data []SendMessageItem `json:"data"` +} + +type SendMessageItem struct { + Code string `json:"code"` + Mobile string `json:"mobile"` + MessageId string `json:"messageId"` + Message string `json:"message"` +} + +// CreateSignatureArgs defines the data structure for creating a signature +type CreateSignatureArgs struct { + Content string `json:"content"` + ContentType string `json:"contentType"` + Description string `json:"description,omitempty"` + CountryType string `json:"countryType"` + SignatureFileBase64 string `json:"signatureFileBase64,omitempty"` + SignatureFileFormat string `json:"signatureFileFormat,omitempty"` +} + +// CreateSignatureResult defines the data structure of the result of creating a signature +type CreateSignatureResult struct { + SignatureId string `json:"signatureId"` + Status string `json:"status"` +} + +// DeleteSignatureArgs defines the input data structure for deleting a signature +type DeleteSignatureArgs struct { + SignatureId string `json:"signatureId"` +} + +// ModifySignatureArgs defines the input data structure for modifying parameters of a signature +type ModifySignatureArgs struct { + SignatureId string `json:"signatureId"` + Content string `json:"content"` + ContentType string `json:"contentType"` + Description string `json:"description,omitempty"` + CountryType string `json:"countryType"` + SignatureFileBase64 string `json:"signatureFileBase64,omitempty"` + SignatureFileFormat string `json:"signatureFileFormat,omitempty"` +} + +// GetSignatureArgs defines the input data structure for Getting a signature +type GetSignatureArgs struct { + SignatureId string `json:"signatureId"` +} + +// GetSignatureResult defines the data structure of the result of getting a signature +type GetSignatureResult struct { + SignatureId string `json:"signatureId"` + UserId string `json:"userId"` + Content string `json:"content"` + ContentType string `json:"contentType"` + Status string `json:"status"` + CountryType string `json:"countryType"` + Review string `json:"review"` +} + +// CreateTemplateArgs defines the data structure for creating a template +type CreateTemplateArgs struct { + Name string `json:"name"` + Content string `json:"content"` + SmsType string `json:"smsType"` + CountryType string `json:"countryType"` + Description string `json:"description,omitempty"` +} + +// CreateTemplateResult defines the data structure of the result of creating a template +type CreateTemplateResult struct { + TemplateId string `json:"templateId"` + Status string `json:"status"` +} + +// DeleteTemplateArgs defines the data structure for deleting a template +type DeleteTemplateArgs struct { + TemplateId string `json:"templateId"` +} + +// ModifyTemplateArgs defines the data structure for modifying a template +type ModifyTemplateArgs struct { + TemplateId string `json:"templateId"` + Name string `json:"name"` + Content string `json:"content"` + SmsType string `json:"smsType"` + CountryType string `json:"countryType"` + Description string `json:"description,omitempty"` +} + +// GetTemplateArgs defines the data structure for getting a template +type GetTemplateArgs struct { + TemplateId string `json:"templateId"` +} + +// GetTemplateResult defines the data structure of the result of getting a template +type GetTemplateResult struct { + TemplateId string `json:"templateId"` + UserId string `json:"userId"` + Name string `json:"name"` + Content string `json:"content"` + CountryType string `json:"countryType"` + SmsType string `json:"smsType"` + Status string `json:"status"` + Description string `json:"description"` + Review string `json:"review"` +} + +// UpdateQuotaRateArgs defines the data structure for updating quota and rate limit +type UpdateQuotaRateArgs struct { + QuotaPerDay int `json:"quotaPerDay"` + QuotaPerMonth int `json:"quotaPerMonth"` + RateLimitPerDay int `json:"rateLimitPerMobilePerSignByDay"` + RateLimitPerHour int `json:"rateLimitPerMobilePerSignByHour"` + RateLimitPerMinute int `json:"rateLimitPerMobilePerSignByMinute"` +} + +// QueryQuotaRateResult defines the data structure of querying the user's quota and rate limit +type QueryQuotaRateResult struct { + QuotaPerDay int `json:"quotaPerDay"` + QuotaRemainToday int `json:"quotaRemainToday"` + QuotaPerMonth int `json:"quotaPerMonth"` + QuotaRemainThisMonth int `json:"quotaRemainThisMonth"` + ApplyQuotaPerDay int `json:"applyQuotaPerDay"` + ApplyQuotaPerMonth int `json:"applyQuotaPerMonth"` + ApplyCheckStatus string `json:"applyCheckStatus"` + ApplyCheckReply string `json:"checkReply"` + RateLimitPerDay int `json:"rateLimitPerMobilePerSignByDay"` + RateLimitPerHour int `json:"rateLimitPerMobilePerSignByHour"` + RateLimitPerMinute int `json:"rateLimitPerMobilePerSignByMinute"` + RateLimitWhitelist bool `json:"rateLimitWhitelist"` +} + +// CreateMobileBlackArgs defines the data structure for creating a mobileBlack +type CreateMobileBlackArgs struct { + Type string `json:"type"` + SmsType string `json:"smsType"` + SignatureIdStr string `json:"signatureIdStr"` + Phone string `json:"phone"` +} + +// DeleteMobileBlackArgs defines the data structure for deleting mobileBlack by phones +type DeleteMobileBlackArgs struct { + Phones string `json:"phones"` +} + +// GetMobileBlackArgs defines the data structure for get mobileBlackList +// startTime、endTime format is yyyy-MM-dd +type GetMobileBlackArgs struct { + Phone string + SmsType string + SignatureIdStr string + StartTime string + EndTime string + PageNo string + PageSize string +} + +// GetMobileBlackResult defines the data structure for get mobileBlackList +type GetMobileBlackResult struct { + TotalCount int `json:"totalCount"` + PageNo int `json:"pageNo"` + PageSize int `json:"pageSize"` + BlackLists []MobileBlackDetail `json:"blacklists"` +} + +// MobileBlackDetail defines the data structure for mobileBlackList detail +type MobileBlackDetail struct { + Phone string `json:"phone"` + Type string `json:"type"` + SmsType string `json:"smsType"` + SignatureIdStr string `json:"signatureIdStr"` + UpdateDate string `json:"updateDate"` +} + +// ListStatisticsArgs defines the request data structure of ListStatistics +type ListStatisticsArgs struct { + SmsType string `json:"smsType"` + SignatureId string `json:"signatureId"` + TemplateCode string `json:"TemplateCode"` + CountryType string `json:"countryType"` // available values: "domestic", "international" + StartTime string `json:"startTime"` // format: "yyyy-MM-dd" + EndTime string `json:"endTime"` // format: "yyyy-MM-dd" +} + +// ListStatisticsResponse defines the response data structure of ListStatistics +type ListStatisticsResponse struct { + StatisticsResults []StatisticsResult `json:"statisticsResults"` +} + +// StatisticsResult defines the detail of ListStatisticsResponse +type StatisticsResult struct { + Datetime string `json:"datetime"` + CountryAlpha2Code string `json:"countryAlpha2Code"` + SubmitCount string `json:"submitCount"` + SubmitLongCount string `json:"submitLongCount"` + ResponseSuccessCount string `json:"responseSuccessCount"` + ResponseSuccessProportion string `json:"responseSuccessProportion"` + DeliverSuccessCount string `json:"deliverSuccessCount"` + DeliverSuccessLongCount string `json:"deliverSuccessLongCount"` + DeliverSuccessProportion string `json:"deliverSuccessProportion"` + DeliverFailureCount string `json:"deliverFailureCount"` + DeliverFailureProportion string `json:"deliverFailureProportion"` + ReceiptProportion string `json:"receiptProportion"` + UnknownCount string `json:"unknownCount"` + UnknownProportion string `json:"unknownProportion"` + ResponseTimeoutCount string `json:"responseTimeoutCount"` + UnknownErrorCount string `json:"unknownErrorCount"` + NotExistCount string `json:"notExistCount"` + SignatureOrTemplateCount string `json:"signatureOrTemplateCount"` + AbnormalCount string `json:"abnormalCount"` + OverclockingCount string `json:"overclockingCount"` + OtherErrorCount string `json:"otherErrorCount"` + BlacklistCount string `json:"blacklistCount"` + RouteErrorCount string `json:"routeErrorCount"` + IssueFailureCount string `json:"issueFailureCount"` + ParameterErrorCount string `json:"parameterErrorCount"` + IllegalWordCount string `json:"illegalWordCount"` + AnomalyCount string `json:"anomalyCount"` +} diff --git a/bce-sdk-go/services/sms/api/quota_rate.go b/bce-sdk-go/services/sms/api/quota_rate.go new file mode 100644 index 0000000..c4deafb --- /dev/null +++ b/bce-sdk-go/services/sms/api/quota_rate.go @@ -0,0 +1,81 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// quota_rate.go - the quota and rate limit APIs definition supported by the SMS service + +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// QueryQuotaRate - query the quota and rate limit detail of an user +// +// RETURNS: +// - *QueryQuotaRateResult: the result of the query +// - error: the return error if any occurs +func QueryQuotaRate(cli bce.Client) (*QueryQuotaRateResult, error) { + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_QUOTA) + req.SetMethod(http.GET) + req.SetParam("userQuery", "") + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &QueryQuotaRateResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// UpdateQuotaRate - update the quota and rate limit detail of an user +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to update the quota and rate limit +// +// RETURNS: +// - *ListBucketsResult: the result bucket list structure +// - error: nil if ok otherwise the specific error +func UpdateQuotaRate(cli bce.Client, args *UpdateQuotaRateArgs) error { + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_QUOTA) + req.SetMethod(http.PUT) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} diff --git a/bce-sdk-go/services/sms/api/send_sms.go b/bce-sdk-go/services/sms/api/send_sms.go new file mode 100644 index 0000000..50b64dd --- /dev/null +++ b/bce-sdk-go/services/sms/api/send_sms.go @@ -0,0 +1,77 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// send_sms.go - the send sms APIs definition supported by the SMS service + +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +// SendSms - send an sms message +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to send an sms message +// +// RETURNS: +// - *api.SendSmsResult: the result of sending an sms message +// - error: the return error if any occurs +func SendSms(cli bce.Client, args *SendSmsArgs) (*SendSmsResult, error) { + if err := CheckError(len(args.Mobile) > 0, "mobile can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.Template) > 0, "templateId can not be blank"); err != nil { + return nil, err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_SEND_SMS) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + if len(args.ClientToken) > 0 { + req.SetParam(CLIENT_TOKEN, args.ClientToken) + } else { + req.SetParam(CLIENT_TOKEN, util.NewUUID()) + } + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &SendSmsResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + + } + return result, nil +} diff --git a/bce-sdk-go/services/sms/api/signature.go b/bce-sdk-go/services/sms/api/signature.go new file mode 100644 index 0000000..cd34397 --- /dev/null +++ b/bce-sdk-go/services/sms/api/signature.go @@ -0,0 +1,177 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// signature.go - the sms signature APIs definition supported by the SMS service + +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +// CreateSignature - create an sms signature +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create an sms signature +// +// RETURNS: +// - *api.CreateSignatureResult: the result of creating an sms signature +// - error: the return error if any occurs +func CreateSignature(cli bce.Client, args *CreateSignatureArgs) (*CreateSignatureResult, error) { + if err := CheckError(args != nil, "CreateSignatureArgs can not be nil"); err != nil { + return nil, err + } + if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.ContentType) > 0, "contentType can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { + return nil, err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_SIGNATURE) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetParam(CLIENT_TOKEN, util.NewUUID()) + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CreateSignatureResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteSignature - delete an sms signature +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to delete an sms signature +// +// RETURNS: +// - error: the return error if any occurs +func DeleteSignature(cli bce.Client, args *DeleteSignatureArgs) error { + if err := CheckError(args != nil, "DeleteSignatureArgs can not be nil"); err != nil { + return err + } + if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { + return err + } + return bce.NewRequestBuilder(cli). + WithMethod(http.DELETE). + WithURL(REQUEST_URI_SIGNATURE + bce.URI_PREFIX + args.SignatureId). + Do() +} + +// ModifySignature - modify an sms signature +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to modify an sms signature +// +// RETURNS: +// - error: the return error if any occurs +func ModifySignature(cli bce.Client, args *ModifySignatureArgs) error { + if err := CheckError(args != nil, "ModifySignatureArgs can not be nil"); err != nil { + return err + } + if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.ContentType) > 0, "contentType can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { + return err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_SIGNATURE + bce.URI_PREFIX + args.SignatureId) + req.SetMethod(http.PUT) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetSignature - get the detail of an sms signature +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get the detail of an sms signature +// +// RETURNS: +// - *api.GetSignatureResult: the detail of an sms signature +// - error: the return error if any occurs +func GetSignature(cli bce.Client, args *GetSignatureArgs) (*GetSignatureResult, error) { + if err := CheckError(args != nil, "GetSignatureArgs can not be nil"); err != nil { + return nil, err + } + if err := CheckError(len(args.SignatureId) > 0, "signatureId can not be blank"); err != nil { + return nil, err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_SIGNATURE + bce.URI_PREFIX + args.SignatureId) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetSignatureResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/sms/api/statistics.go b/bce-sdk-go/services/sms/api/statistics.go new file mode 100644 index 0000000..8e6afb6 --- /dev/null +++ b/bce-sdk-go/services/sms/api/statistics.go @@ -0,0 +1,90 @@ +/* + * Copyright 2023 Baidu, Inc. + * + * 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. + */ + +// mobile_black.go - the sms MobileBlack APIs definition supported by the SMS service + +package api + +import ( + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListStatistics - get sms statistics data +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to get sms statistics data +// +// RETURNS: +// - error: the return error if any occurs +// - *api.ListStatisticsResponse: the result of get sms MobileBlackList +func ListStatistics(cli bce.Client, args *ListStatisticsArgs) (*ListStatisticsResponse, error) { + if err := CheckError(args != nil, "ListStatisticsArgs can not be nil"); err != nil { + return nil, err + } + + paramsMap := make(map[string]string) + + if err := CheckError(len(args.StartTime) > 0, + "ListStatistics query start time can not be nil"); err != nil { + return nil, err + } + + paramsMap["startTime"] = args.StartTime + " 00:00:00" + + if err := CheckError(len(args.EndTime) > 0, + "ListStatistics query end time can not be nil"); err != nil { + return nil, err + } + + paramsMap["endTime"] = args.EndTime + " 23:59:59" + + // default value + paramsMap["smsType"] = "all" + paramsMap["dimension"] = "day" + + if len(args.SmsType) > 0 { + paramsMap["smsType"] = args.SmsType + } + if len(args.CountryType) > 0 { + paramsMap["countryType"] = args.CountryType + } + if len(args.SignatureId) > 0 { + paramsMap["signatureId"] = args.SignatureId + } + if len(args.TemplateCode) > 0 { + paramsMap["templateCode"] = args.TemplateCode + } + + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_STATISTICS) + req.SetMethod(http.GET) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetParams(paramsMap) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + + result := &ListStatisticsResponse{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/sms/api/template.go b/bce-sdk-go/services/sms/api/template.go new file mode 100644 index 0000000..6441d21 --- /dev/null +++ b/bce-sdk-go/services/sms/api/template.go @@ -0,0 +1,182 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// template.go - the sms template APIs definition supported by the SMS service + +package api + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "github.com/baidubce/bce-sdk-go/util" +) + +// CreateTemplate - create an sms template +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to create an sms template +// +// RETURNS: +// - *api.CreateTemplateResult: the result of creating an sms template +// - error: the return error if any occurs +func CreateTemplate(cli bce.Client, args *CreateTemplateArgs) (*CreateTemplateResult, error) { + if err := CheckError(args != nil, "CreateTemplateArgs can not be nil"); err != nil { + return nil, err + } + if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.Name) > 0, "name can not be blank"); err != nil { + return nil, err + } + if err := CheckError(len(args.SmsType) > 0, "smsType can not be blank"); err != nil { + return nil, err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_TEMPLATE) + req.SetMethod(http.POST) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + req.SetParam(CLIENT_TOKEN, util.NewUUID()) + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &CreateTemplateResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} + +// DeleteTemplate - delete an sms template +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to delete an sms template +// +// RETURNS: +// - error: the return error if any occurs +func DeleteTemplate(cli bce.Client, args *DeleteTemplateArgs) error { + if err := CheckError(args != nil, "DeleteTemplateArgs can not be nil"); err != nil { + return err + } + if err := CheckError(len(args.TemplateId) > 0, "templateId can not be blank"); err != nil { + return err + } + return bce.NewRequestBuilder(cli). + WithMethod(http.DELETE). + WithURL(REQUEST_URI_TEMPLATE + bce.URI_PREFIX + args.TemplateId). + Do() +} + +// ModifyTemplate - modify an sms template +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to modify an sms template +// +// RETURNS: +// - error: the return error if any occurs +func ModifyTemplate(cli bce.Client, args *ModifyTemplateArgs) error { + if err := CheckError(args != nil, "ModifyTemplateArgs can not be nil"); err != nil { + return err + } + if err := CheckError(len(args.TemplateId) > 0, "templateId can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.Content) > 0, "content can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.CountryType) > 0, "countryType can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.Name) > 0, "name can not be blank"); err != nil { + return err + } + if err := CheckError(len(args.SmsType) > 0, "smsType can not be blank"); err != nil { + return err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_TEMPLATE + bce.URI_PREFIX + args.TemplateId) + req.SetMethod(http.PUT) + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(body) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +// GetTemplate - modify an sms template +// +// PARAMS: +// - cli: the client agent which can perform sending request +// - args: the arguments to modify an sms template +// +// RETURNS: +// - error: the return error if any occurs +func GetTemplate(cli bce.Client, args *GetTemplateArgs) (*GetTemplateResult, error) { + if err := CheckError(args != nil, "GetTemplateResult can not be nil"); err != nil { + return nil, err + } + if err := CheckError(len(args.TemplateId) > 0, "templateId can not be blank"); err != nil { + return nil, err + } + req := &bce.BceRequest{} + req.SetUri(REQUEST_URI_TEMPLATE + bce.URI_PREFIX + args.TemplateId) + req.SetMethod(http.GET) + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + result := &GetTemplateResult{} + if err := resp.ParseJsonBody(result); err != nil { + return nil, err + } + return result, nil +} diff --git a/bce-sdk-go/services/sms/api/util.go b/bce-sdk-go/services/sms/api/util.go new file mode 100644 index 0000000..286b0f2 --- /dev/null +++ b/bce-sdk-go/services/sms/api/util.go @@ -0,0 +1,38 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// util.go - define the utilities for api package of SMS service + +package api + +import ( + "fmt" +) + +const ( + REQUEST_URI_SEND_SMS = "/api/v3/sendsms" + REQUEST_URI_SIGNATURE = "/sms/v3/signatureApply" + REQUEST_URI_TEMPLATE = "/sms/v3/template" + REQUEST_URI_QUOTA = "/sms/v3/quota" + REQUEST_URI_BLACK = "/sms/v3/blacklist" + REQUEST_URI_STATISTICS = "/sms/v3/summary" + CLIENT_TOKEN = "clientToken" +) + +func CheckError(condition bool, errMessage string) error { + if !condition { + return fmt.Errorf(errMessage) + } + return nil +} diff --git a/bce-sdk-go/services/sms/client.go b/bce-sdk-go/services/sms/client.go new file mode 100644 index 0000000..197465c --- /dev/null +++ b/bce-sdk-go/services/sms/client.go @@ -0,0 +1,235 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for SMS service + +package sms + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/sms/api" +) + +const ( + REGION_BJ = "bj" + REGION_SU = "su" + DEFAULT_SERVICE_DOMAIN = "smsv3." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN +) + +// Client of SMS service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the SMS service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + var credentials *auth.BceCredentials + var err error + if len(ak) == 0 && len(sk) == 0 { // to support public-read-write request + credentials, err = nil, nil + } else { + credentials, err = auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +// SendSms - send an sms message +// +// PARAMS: +// - args: the arguments to send an sms message +// +// RETURNS: +// - *api.SendSmsResult: the result of sending an sms message +// - error: the return error if any occurs +func (c *Client) SendSms(args *api.SendSmsArgs) (*api.SendSmsResult, error) { + return api.SendSms(c, args) +} + +// CreateSignature - create an sms signature +// +// PARAMS: +// - args: the arguments to create an sms signature +// +// RETURNS: +// - *api.CreateSignatureResult: the result of creating an sms signature +// - error: the return error if any occurs +func (c *Client) CreateSignature(args *api.CreateSignatureArgs) (*api.CreateSignatureResult, error) { + return api.CreateSignature(c, args) +} + +// DeleteSignature - delete an sms signature +// +// PARAMS: +// - args: the arguments to delete an sms signature +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteSignature(args *api.DeleteSignatureArgs) error { + return api.DeleteSignature(c, args) +} + +// ModifySignature - modify an sms signature +// +// PARAMS: +// - args: the arguments to modify an sms signature +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) ModifySignature(args *api.ModifySignatureArgs) error { + return api.ModifySignature(c, args) +} + +// GetSignature - get the detail of an sms signature +// +// PARAMS: +// - args: the arguments to get the detail of an sms signature +// +// RETURNS: +// - *api.GetSignatureResult: the detail of an sms signature +// - error: the return error if any occurs +func (c *Client) GetSignature(args *api.GetSignatureArgs) (*api.GetSignatureResult, error) { + return api.GetSignature(c, args) +} + +// CreateTemplate - create an sms template +// +// PARAMS: +// - args: the arguments to create an sms template +// +// RETURNS: +// - *api.CreateTemplateResult: the result of creating an sms template +// - error: the return error if any occurs +func (c *Client) CreateTemplate(args *api.CreateTemplateArgs) (*api.CreateTemplateResult, error) { + return api.CreateTemplate(c, args) +} + +// DeleteTemplate - delete an sms template +// +// PARAMS: +// - args: the arguments to delete an sms template +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteTemplate(args *api.DeleteTemplateArgs) error { + return api.DeleteTemplate(c, args) +} + +// ModifyTemplate - modify an sms template +// +// PARAMS: +// - args: the arguments to modify an sms template +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) ModifyTemplate(args *api.ModifyTemplateArgs) error { + return api.ModifyTemplate(c, args) +} + +// GetTemplate - modify an sms template +// +// PARAMS: +// - args: the arguments to modify an sms template +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) GetTemplate(args *api.GetTemplateArgs) (*api.GetTemplateResult, error) { + return api.GetTemplate(c, args) +} + +// QueryQuotaAndRateLimit - query the quota and rate limit +// +// RETURNS: +// - QueryQuotaRateResult: the result of querying the quota and rate limit +// - error: the return error if any occurs +func (c *Client) QueryQuotaAndRateLimit() (*api.QueryQuotaRateResult, error) { + return api.QueryQuotaRate(c) +} + +// UpdateQuotaAndRateLimit - update the quota or rate limit +// PARAMS: +// - args: the arguments to update the quota or rate limit +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) UpdateQuotaAndRateLimit(args *api.UpdateQuotaRateArgs) error { + return api.UpdateQuotaRate(c, args) +} + +// CreateMobileBlack - create an sms mobileBlack +// +// PARAMS: +// - args: the arguments to create an sms mobileBlack +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) CreateMobileBlack(args *api.CreateMobileBlackArgs) error { + return api.CreateMobileBlack(c, args) +} + +// DeleteMobileBlack - delete sms mobileBlack by phones +// +// PARAMS: +// - args: the arguments to delete an sms mobileBlack +// +// RETURNS: +// - error: the return error if any occurs +func (c *Client) DeleteMobileBlack(args *api.DeleteMobileBlackArgs) error { + return api.DeleteMobileBlack(c, args) +} + +// GetMobileBlack - get a sms mobileBlack +// +// PARAMS: +// - args: the arguments to get sms mobileBlack +// +// RETURNS: +// - error: the return error if any occurs +// - *api.GetMobileBlackResult: the result of creating an sms mobileBlack +func (c *Client) GetMobileBlack(args *api.GetMobileBlackArgs) (*api.GetMobileBlackResult, error) { + return api.GetMobileBlack(c, args) +} + +// ListStatistics - get a list of sms statistics data +// +// PARAMS: +// - args: the arguments to get sms statistics list data +// +// RETURNS: +// - error: the return error if any occurs +// - *api.ListStatisticsResponse: the result of getting statistics list data +func (c *Client) ListStatistics(args *api.ListStatisticsArgs) (*api.ListStatisticsResponse, error) { + return api.ListStatistics(c, args) +} diff --git a/bce-sdk-go/services/sms/client_test.go b/bce-sdk-go/services/sms/client_test.go new file mode 100644 index 0000000..ff2f681 --- /dev/null +++ b/bce-sdk-go/services/sms/client_test.go @@ -0,0 +1,236 @@ +package sms + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/services/sms/api" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + SMS_CLIENT *Client + TEST_SIGNATURE_ID = "" + TEST_TEMPLATE_ID = "" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "/config.json") + fmt.Println(conf) + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + SMS_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) + //log.SetLogLevel(log.DEBUG) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestSendSms(t *testing.T) { + contentMap := make(map[string]interface{}) + contentMap["code"] = "123" + contentMap["minute"] = "1" + sendSmsArgs := &api.SendSmsArgs{ + Mobile: "13800138000", + Template: "your template id", + SignatureId: "your signature id", + ContentVar: contentMap, + } + result, err := SMS_CLIENT.SendSms(sendSmsArgs) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", result) +} + +func TestCreateSignature(t *testing.T) { + result, err := SMS_CLIENT.CreateSignature(&api.CreateSignatureArgs{ + Content: "测试", + ContentType: "Enterprise", + Description: "This is a test", + CountryType: "DOMESTIC", + }) + ExpectEqual(t.Errorf, err, nil) + TEST_SIGNATURE_ID = result.SignatureId + t.Logf("%v", result) +} + +func TestGetSignature(t *testing.T) { + _, err := SMS_CLIENT.GetSignature(&api.GetSignatureArgs{SignatureId: TEST_SIGNATURE_ID}) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifySignature(t *testing.T) { + err := SMS_CLIENT.ModifySignature(&api.ModifySignatureArgs{ + SignatureId: TEST_SIGNATURE_ID, + Content: "测试变更", + ContentType: "Enterprise", + Description: "This is a test", + CountryType: "INTERNATIONAL", + SignatureFileBase64: "", + SignatureFileFormat: "", + }) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteSignature(t *testing.T) { + err := SMS_CLIENT.DeleteSignature(&api.DeleteSignatureArgs{SignatureId: TEST_SIGNATURE_ID}) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateTemplate(t *testing.T) { + result, err := SMS_CLIENT.CreateTemplate(&api.CreateTemplateArgs{ + Name: "测试", + Content: "${content}", + SmsType: "CommonNotice", + CountryType: "DOMESTIC", + Description: "gogogo", + }) + ExpectEqual(t.Errorf, err, nil) + TEST_TEMPLATE_ID = result.TemplateId +} + +func TestGetTemplate(t *testing.T) { + _, err := SMS_CLIENT.GetTemplate(&api.GetTemplateArgs{TemplateId: TEST_TEMPLATE_ID}) + ExpectEqual(t.Errorf, err, nil) +} + +func TestModifyTemplate(t *testing.T) { + err := SMS_CLIENT.ModifyTemplate(&api.ModifyTemplateArgs{ + TemplateId: TEST_TEMPLATE_ID, + Name: "测试变更模板", + Content: "${code}", + SmsType: "CommonVcode", + CountryType: "GLOBAL", + Description: "this is a test", + }) + ExpectEqual(t.Errorf, err, nil) +} + +func TestDeleteTemplate(t *testing.T) { + err := SMS_CLIENT.DeleteTemplate(&api.DeleteTemplateArgs{ + TemplateId: TEST_TEMPLATE_ID, + }) + ExpectEqual(t.Errorf, err, nil) +} + +func TestCreateMobileBlack(t *testing.T) { + err := SMS_CLIENT.CreateMobileBlack(&api.CreateMobileBlackArgs{ + Type: "SignatureBlack", + Phone: "17600000000", + SmsType: "CommonNotice", + SignatureIdStr: "1234", + }) + ExpectEqual(t.Errorf, err, nil) +} + +func TestGetMobileBlack(t *testing.T) { + res, err := SMS_CLIENT.GetMobileBlack(&api.GetMobileBlackArgs{ + Phone: "17600000000", + SmsType: "CommonNotice", + SignatureIdStr: "1234", + StartTime: "2023-07-10", + EndTime: "2023-07-20", + PageSize: "10", + PageNo: "1", + }) + ExpectEqual(t.Errorf, err, nil) + t.Logf("%v", res) +} + +func TestDeleteMobileBlack(t *testing.T) { + err := SMS_CLIENT.DeleteMobileBlack(&api.DeleteMobileBlackArgs{ + Phones: "17600000000,17600000001", + }) + ExpectEqual(t.Errorf, err, nil) +} + +func TestListStatistics(t *testing.T) { + // normal case: necessary parameters, domestic + res, err := SMS_CLIENT.ListStatistics(&api.ListStatisticsArgs{ + StartTime: "2023-09-30", + EndTime: "2023-09-30", + CountryType: "domestic", + }) + ExpectEqual(t.Errorf, 2, len(res.StatisticsResults)) + t.Logf("test1: %#v", res) + + // normal case: necessary parameters, international + res, err = SMS_CLIENT.ListStatistics(&api.ListStatisticsArgs{ + StartTime: "2023-09-30", + EndTime: "2023-09-30", + CountryType: "international", + }) + ExpectEqual(t.Errorf, 6, len(res.StatisticsResults)) + t.Logf("test2: %#v", res) + + // normal case: select signature + res, err = SMS_CLIENT.ListStatistics(&api.ListStatisticsArgs{ + StartTime: "2023-09-30", + EndTime: "2023-09-30", + SignatureId: "114514", + }) + ExpectEqual(t.Errorf, 2, len(res.StatisticsResults)) + t.Logf("test2: %#v", res) + + // error case1: nil query end time + res, err = SMS_CLIENT.ListStatistics(&api.ListStatisticsArgs{ + StartTime: "2023-10-08", + }) + ExpectEqual(t.Errorf, nil, res) + t.Logf("test3: %v", err) + + // error case2: wrong format of time + res, err = SMS_CLIENT.ListStatistics(&api.ListStatisticsArgs{ + StartTime: "2023-10-08 00", + EndTime: "2023-10-09", + }) + ExpectEqual(t.Errorf, nil, res) + t.Logf("test4: %v", err) +} diff --git a/bce-sdk-go/services/sts/api/mode.go b/bce-sdk-go/services/sts/api/mode.go new file mode 100644 index 0000000..ef43330 --- /dev/null +++ b/bce-sdk-go/services/sts/api/mode.go @@ -0,0 +1,30 @@ +package api + +import "time" + +type GetSessionTokenResult struct { + AccessKeyId string + SecretAccessKey string + SessionToken string + CreateTime string + Expiration string + UserId string +} + +type AssumeRoleArgs struct { + DurationSeconds int + AccountId string + UserId string + RoleName string + Acl string +} + +type Credential struct { + AccessKeyId string + SecretAccessKey string + SessionToken string + CreateTime time.Time + Expiration time.Time + UserId string + RoleId string +} diff --git a/bce-sdk-go/services/sts/api/sts.go b/bce-sdk-go/services/sts/api/sts.go new file mode 100644 index 0000000..d849b7e --- /dev/null +++ b/bce-sdk-go/services/sts/api/sts.go @@ -0,0 +1,140 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// sts.go - define the response for STS service + +// Package api defines all APIs supported by the STS service of BCE. +package api + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +const ( + DEFAULT_DURATION_SECONDS = 43200 // default duration is 12 hours + URI_PREFIX = bce.URI_PREFIX + "v1" // sts service not support uri without prefix "v1" + REQUEST_URI = "/sessionToken" + + DEFAULT_ASSUMEROLE_DURATION_SECONDS = 7200 // default duration is 2 hours + REQUEST_ASSUMEROLE_URI = "/credential" +) + +// GetSessionToken - get the session token from the STS service +// +// PARAMS: +// - cli: the client object which can perform sending request +// - durationSec: the duration seconds of the token +// - acl: the acl string +// +// RETURNS: +// - *GetSessionTokenResult: result of this api +// - error: nil if ok otherwise the specific error +func GetSessionToken(cli bce.Client, durationSec int, acl string) (*GetSessionTokenResult, error) { + // If the duration seconds is not a positive, use the default value + if durationSec <= 0 { + durationSec = DEFAULT_DURATION_SECONDS + } + + // Build the request + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + REQUEST_URI) + req.SetMethod(http.POST) + req.SetParam("durationSeconds", strconv.Itoa(durationSec)) + if len(acl) > 0 { + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + body, err := bce.NewBodyFromString(acl) + if err != nil { + return nil, err + } + req.SetBody(body) + } + + // Send requet and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetSessionTokenResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +// AssumeRole - get the credential for the assume role from the STS service +// +// PARAMS: +// - cli: the client object which can perform sending request +// - args: the args for assumeRole +// +// RETURNS: +// - *Credential: result of this api +// - error: nil if ok otherwise the specific error +func AssumeRole(cli bce.Client, args *AssumeRoleArgs) (*Credential, error) { + // If the duration seconds is not a positive, use the default value + if args.DurationSeconds <= 0 { + args.DurationSeconds = DEFAULT_ASSUMEROLE_DURATION_SECONDS + } + + if args.AccountId == "" { + return nil, fmt.Errorf("please set accountId") + } + + if args.RoleName == "" { + return nil, fmt.Errorf("please set roleName") + } + + // Build the request + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + REQUEST_ASSUMEROLE_URI) + req.SetMethod(http.POST) + req.SetParam("assumeRole", "") + req.SetParam("durationSeconds", strconv.Itoa(args.DurationSeconds)) + req.SetParam("accountId", args.AccountId) + req.SetParam("roleName", args.RoleName) + + if args.UserId != "" { + req.SetParam("userId", args.UserId) + } + + if len(args.Acl) > 0 { + req.SetHeader(http.CONTENT_TYPE, bce.DEFAULT_CONTENT_TYPE) + body, err := bce.NewBodyFromString(args.Acl) + if err != nil { + return nil, err + } + req.SetBody(body) + } + + // Send requet and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &Credential{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/sts/client.go b/bce-sdk-go/services/sts/client.go new file mode 100644 index 0000000..de40c42 --- /dev/null +++ b/bce-sdk-go/services/sts/client.go @@ -0,0 +1,75 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for STS service which is derived from BceClient + +// Package sts defines the STS service of BCE. +// It contains the model sub package to implement the concrete request and response of the +// GetSessionToken API. +package sts + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/sts/api" + "github.com/baidubce/bce-sdk-go/util" +) + +const DEFAULT_SERVICE_DOMAIN = "sts." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN + +// Client of STS service is a kind of BceClient, so it derived from the BceClient and it only +// supports the GetSessionToken API. There is no other fields needed. +type Client struct { + *bce.BceClient +} + +func (c *Client) GetSessionToken(duration int, acl string) (*api.GetSessionTokenResult, error) { + return api.GetSessionToken(c, duration, acl) +} + +func (c *Client) AssumeRole(args *api.AssumeRoleArgs) (*api.Credential, error) { + return api.AssumeRole(c, args) +} + +// NewClient make the STS service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk string) (*Client, error) { + return NewStsClient(ak, sk, DEFAULT_SERVICE_DOMAIN) +} + +func NewStsClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + Timestamp: util.NowUTCSeconds(), + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} diff --git a/bce-sdk-go/services/sts/client_test.go b/bce-sdk-go/services/sts/client_test.go new file mode 100644 index 0000000..0f721e5 --- /dev/null +++ b/bce-sdk-go/services/sts/client_test.go @@ -0,0 +1,96 @@ +package sts + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var CLIENT *Client + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string +} + +func init() { + _, f, _, _ := runtime.Caller(0) + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + CLIENT, _ = NewClient(confObj.AK, confObj.SK) + //log.SetLogHandler(log.STDERR) + //log.SetLogLevel(log.INFO) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestGetSessionToken(t *testing.T) { + res, err := CLIENT.GetSessionToken(-1, "") + ExpectEqual(t.Errorf, err, nil) + t.Logf("%+v", res) + + acl := ` +{ + "id":"10eb6f5ff6ff4605bf044313e8f3ffa5", + "accessControlList": [ + { + "eid": "10eb6f5ff6ff4605bf044313e8f3ffa5-1", + "effect": "Deny", + "resource": ["bos-rd-ssy/*"], + "region": "bj", + "service": "bce:bos", + "permission": ["WRITE"] + } + ] +}` + res, err = CLIENT.GetSessionToken(10, acl) + ExpectEqual(t.Fatalf, err, nil) + t.Logf("ak: %v", res.AccessKeyId) + t.Logf("sk: %v", res.SecretAccessKey) + t.Logf("sessionToken: %v", res.SessionToken) + t.Logf("createTime: %v", res.CreateTime) + t.Logf("expiration: %v", res.Expiration) + t.Logf("userId: %v", res.UserId) +} diff --git a/bce-sdk-go/services/userservice/client.go b/bce-sdk-go/services/userservice/client.go new file mode 100644 index 0000000..43ed3a9 --- /dev/null +++ b/bce-sdk-go/services/userservice/client.go @@ -0,0 +1,84 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for User Service service + +// Package userservice defines the User Service services of BCE. The supported APIs are all defined in sub-package +package userservice + +import ( + "encoding/json" + + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "blb." + bce.DEFAULT_REGION + ".baidubce.com" + URI_PREFIX = bce.URI_PREFIX + "v1" + REQUEST_SERVICE_URL = "/service" +) + +type Client struct { + *bce.BceClient +} + +// NewClient 是一个函数,用于创建一个新的客户端对象 +func NewClient(ak, sk, endPoint string) (*Client, error) { + if endPoint == "" { + endPoint = DEFAULT_SERVICE_DOMAIN + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + + } + return &Client{client}, nil +} + +// userServiceRequest 发起用户服务请求 +func (c *Client) userServiceRequest(action, method, uri, clientToken string, args interface{}) error { + req := &bce.BceRequest{} + req.SetMethod(method) + req.SetUri(uri) + req.SetParam(action, "") + req.SetParam("clientToken", clientToken) + + jsonBytes, err := json.Marshal(args) + if err != nil { + return err + } + jsonBody, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + req.SetBody(jsonBody) + resp := &bce.BceResponse{} + if err := c.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + return nil +} + +// getUserServiceUri 函数返回用户服务的URI地址 +func getUserServiceUri() string { + return URI_PREFIX + REQUEST_SERVICE_URL +} + +// getUserServiceIdUri 返回指定服务的用户服务ID的URI +func getUserServiceIdUri(service string) string { + return URI_PREFIX + REQUEST_SERVICE_URL + "/" + service +} diff --git a/bce-sdk-go/services/userservice/client_test.go b/bce-sdk-go/services/userservice/client_test.go new file mode 100644 index 0000000..c206370 --- /dev/null +++ b/bce-sdk-go/services/userservice/client_test.go @@ -0,0 +1,206 @@ +package userservice + +import ( + "encoding/json" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + USER_SERVICE_CLIENT *Client + + // set these values before start test + VPC_TEST_ID = "" + SUBNET_TEST_ID = "" + INSTANCE_ID = "" + CERT_ID = "" + CLUSTER_ID = "" + CLUSTER_PROPERTY_TEST = "" + TEST_BLB_ID = "lb-xxxxxxxx" + SERVICE = "xxxxxxxxxx.beijing.baidubce.com" +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string + SK string + Endpoint string +} + +// init 函数用于初始化全局变量 +func init() { + _, f, _, _ := runtime.Caller(0) + conf := filepath.Join(filepath.Dir(f), "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + err = decoder.Decode(confObj) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + USER_SERVICE_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.Endpoint) + log.SetLogLevel(log.WARN) +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +// getClientToken 函数返回一个随机的UUID字符串 +func getClientToken() string { + return util.NewUUID() +} + +// TestClient_CreateUserService 用于测试创建用户服务的函数 +func TestClient_CreateUserService(t *testing.T) { + args := &CreateUserServiceArgs{ + ClientToken: getClientToken(), + InstanceId: TEST_BLB_ID, + Name: "test_name", + Description: "test_user_service_description", + ServiceName: "testUserServiceName", + } + + createResult, err := USER_SERVICE_CLIENT.CreateUserService(args) + ExpectEqual(t.Errorf, nil, err) + SERVICE = createResult.Service +} + +// TestClient_UpdateUserService 是一个用于测试客户端函数UpdateUserService的测试函数 +func TestClient_UpdateUserService(t *testing.T) { + + args := &UpdateServiceArgs{ + ClientToken: getClientToken(), + Name: "update_test_name", + Description: "update_test_user_service_description", + } + + err := USER_SERVICE_CLIENT.UpdateUserService(SERVICE, args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_UnBindInstance 测试客户端解绑实例函数 +func TestClient_UnBindInstance(t *testing.T) { + + args := &UserServiceUnBindArgs{ + ClientToken: getClientToken(), + } + + err := USER_SERVICE_CLIENT.UserServiceUnBindInstance(SERVICE, args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_BindInstance 测试绑定实例函数 +func TestClient_BindInstance(t *testing.T) { + + args := &UserServiceBindArgs{ + ClientToken: getClientToken(), + InstanceId: TEST_BLB_ID, + } + + err := USER_SERVICE_CLIENT.UserServiceBindInstance(SERVICE, args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_UserServiceRemoveAuth 测试用户服务移除授权 +func TestClient_UserServiceRemoveAuth(t *testing.T) { + + args := &UserServiceRemoveAuthArgs{ + ClientToken: getClientToken(), + UidList: []string{"7cc5aff841ff4b648028d80000000000"}, + } + + err := USER_SERVICE_CLIENT.UserServiceRemoveAuth(SERVICE, args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_UserServiceAddAuth 用于测试用户服务添加权限的方法 +func TestClient_UserServiceAddAuth(t *testing.T) { + + args := &UserServiceAuthArgs{ + ClientToken: getClientToken(), + AuthList: []UserServiceAuthModel{ + { + Uid: "7cc5aff841ff4b648028d80000000000", + Auth: ServiceAuthDeny, + }}, + } + + err := USER_SERVICE_CLIENT.UserServiceAddAuth(SERVICE, args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_UserServiceEditAuth 测试UserServiceEditAuth函数 +func TestClient_UserServiceEditAuth(t *testing.T) { + + args := &UserServiceAuthArgs{ + ClientToken: getClientToken(), + AuthList: []UserServiceAuthModel{ + { + Uid: "7cc5aff841ff4b648028d80000000000", + Auth: ServiceAuthAllow, + }}, + } + + err := USER_SERVICE_CLIENT.UserServiceEditAuth(SERVICE, args) + ExpectEqual(t.Errorf, nil, err) +} + +// TestClient_DescribeUserServices 是一个测试函数,用于测试客户端的DescribeUserServices方法 +func TestClient_DescribeUserServices(t *testing.T) { + + args := &DescribeUserServicesArgs{} + + result, err := USER_SERVICE_CLIENT.DescribeUserServices(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 1, len(result.Services)) +} + +// TestClient_DescribeUserServiceDetail 测试函数,用于测试客户端的DescribeUserServiceDetail方法 +func TestClient_DescribeUserServiceDetail(t *testing.T) { + + result, err := USER_SERVICE_CLIENT.DescribeUserServiceDetail(SERVICE) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "available", len(result.Status)) +} + +// TestClient_DeleteUserService 是一个测试函数,用于测试 DeleteUserService 方法是否能够成功删除用户服务。 +func TestClient_DeleteUserService(t *testing.T) { + + err := USER_SERVICE_CLIENT.DeleteUserService(SERVICE) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/userservice/model.go b/bce-sdk-go/services/userservice/model.go new file mode 100644 index 0000000..cd651b5 --- /dev/null +++ b/bce-sdk-go/services/userservice/model.go @@ -0,0 +1,105 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package userservice + +type AuthStatus string + +const ( + ServiceAuthAllow AuthStatus = "allow" + ServiceAuthDeny AuthStatus = "deny" +) + +type CreateUserServiceArgs struct { + ClientToken string `json:"-"` + InstanceId string `json:"instanceId"` + Name string `json:"name"` + Description string `json:"description"` + ServiceName string `json:"serviceName"` + AuthList []UserServiceAuthModel `json:"authList"` +} + +type CreateUserServiceResult struct { + Service string `json:"service"` +} + +type UserServiceAuthModel struct { + Uid string `json:"uid"` + Auth AuthStatus `json:"auth"` +} + +type UpdateServiceArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description"` +} + +type UserServiceBindArgs struct { + ClientToken string `json:"-"` + InstanceId string `json:"instanceId"` +} + +type UserServiceUnBindArgs struct { + ClientToken string `json:"-"` +} + +type UserServiceAuthArgs struct { + ClientToken string `json:"-"` + AuthList []UserServiceAuthModel `json:"authList"` +} + +type UserServiceRemoveAuthArgs struct { + ClientToken string `json:"-"` + UidList []string `json:"uidList"` +} + +type DescribeUserServicesArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type DescribeUserServicesResult struct { + Services []UserServiceModel `json:"services"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type UserServiceModel struct { + ServiceId string `json:"serviceId"` + Name string `json:"name"` + Description string `json:"description"` + ServiceName string `json:"serviceName"` + BindType string `json:"bindType"` + InstanceId string `json:"instanceId"` + Status string `json:"status"` + Service string `json:"service"` + CreateTime string `json:"createTime"` + EndpointCount int `json:"endpointCount"` + EndpointList []RelatedEndpointModel `json:"endpointList"` + AuthList []UserServiceAuthModel `json:"authList"` +} + +type RelatedEndpointModel struct { + EndpointId string `json:"endpointId"` + Uid string `json:"uid"` + AttachTime string `json:"attachTime"` +} + +type DescribeUserServiceDetailResult struct { + UserServiceModel +} diff --git a/bce-sdk-go/services/userservice/userservice.go b/bce-sdk-go/services/userservice/userservice.go new file mode 100644 index 0000000..9cb87d9 --- /dev/null +++ b/bce-sdk-go/services/userservice/userservice.go @@ -0,0 +1,306 @@ +/* + * Copyright 2024 Baidu, Inc. + * + * 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. + */ + +// userservice.go - the User Service APIs definition supported by the User Service service + +package userservice + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateUserService - create a User Service +// +// PARAMS: +// - args: parameters to create User Service +// +// RETURNS: +// - *CreateUserServiceResult: the result of create User Service, contains new Service Domain +// - error: nil if ok otherwise the specific error +func (c *Client) CreateUserService(args *CreateUserServiceArgs) (*CreateUserServiceResult, error) { + if args == nil || len(args.Name) == 0 { + return nil, fmt.Errorf("unset name") + } + + if len(args.ServiceName) == 0 { + return nil, fmt.Errorf("unset service name") + } + + if len(args.InstanceId) == 0 { + return nil, fmt.Errorf("unset instance id") + } + + if len(args.AuthList) > 0 { + for i := range args.AuthList { + authModel := args.AuthList[i] + if authModel.Uid == "" { + return nil, fmt.Errorf("unset uid") + } + if authModel.Auth != ServiceAuthAllow && authModel.Auth != ServiceAuthDeny { + return nil, fmt.Errorf("invalid auth") + } + } + } else { + args.AuthList = []UserServiceAuthModel{ + { + Uid: "*", + Auth: ServiceAuthDeny, + }} + } + + result := &CreateUserServiceResult{} + err := bce.NewRequestBuilder(c). + WithMethod(http.POST). + WithURL(getUserServiceUri()). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + + return result, err +} + +// UpdateUserService - update a User Service +// +// PARAMS: +// - service: Service Domain +// - args: parameters to update User Service +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UpdateUserService(service string, args *UpdateServiceArgs) error { + if args == nil { + args = &UpdateServiceArgs{} + } + + if len(service) == 0 { + return fmt.Errorf("unset service") + } + + return c.userServiceRequest("modifyAttribute", http.PUT, getUserServiceIdUri(service), args.ClientToken, args) +} + +// UserServiceBindInstance - User Service bind BLB instance +// +// PARAMS: +// - service: Service Domain +// - args: parameters to bind blb instance id +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UserServiceBindInstance(service string, args *UserServiceBindArgs) error { + if args == nil { + args = &UserServiceBindArgs{} + } + + if len(service) == 0 { + return fmt.Errorf("unset service") + } + + if len(args.InstanceId) == 0 { + return fmt.Errorf("unset instance id") + } + + return c.userServiceRequest("bind", http.PUT, getUserServiceIdUri(service), args.ClientToken, args) +} + +// UserServiceUnBindInstance - User Service unbind BLB instance +// +// PARAMS: +// - service: Service Domain +// - args: parameters to unbind blb instance id +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UserServiceUnBindInstance(service string, args *UserServiceUnBindArgs) error { + if args == nil { + args = &UserServiceUnBindArgs{} + } + + if len(service) == 0 { + return fmt.Errorf("unset service") + } + + return c.userServiceRequest("unbind", http.PUT, getUserServiceIdUri(service), args.ClientToken, args) +} + +// UserServiceAddAuth - add auth to User Service +// +// PARAMS: +// - service: Service Domain +// - args: parameters to add auth +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UserServiceAddAuth(service string, args *UserServiceAuthArgs) error { + if args == nil { + args = &UserServiceAuthArgs{} + } + + if len(args.AuthList) == 0 { + return fmt.Errorf("unset auth list") + } + + for i := range args.AuthList { + authModel := args.AuthList[i] + if authModel.Uid == "" { + return fmt.Errorf("unset uid") + } + if authModel.Auth != ServiceAuthAllow && authModel.Auth != ServiceAuthDeny { + return fmt.Errorf("invalid auth") + } + } + + return c.userServiceRequest("addAuth", http.PUT, getUserServiceIdUri(service), args.ClientToken, args) +} + +// UserServiceEditAuth - edit auth to User Service +// +// PARAMS: +// - service: Service Domain +// - args: parameters to edit auth +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UserServiceEditAuth(service string, args *UserServiceAuthArgs) error { + if args == nil { + args = &UserServiceAuthArgs{} + } + + if len(service) == 0 { + return fmt.Errorf("unset service") + } + + if len(args.AuthList) == 0 { + return fmt.Errorf("unset auth list") + } + + for i := range args.AuthList { + authModel := args.AuthList[i] + if authModel.Uid == "" { + return fmt.Errorf("unset uid") + } + if authModel.Auth != ServiceAuthAllow && authModel.Auth != ServiceAuthDeny { + return fmt.Errorf("invalid auth") + } + } + + return c.userServiceRequest("editAuth", http.PUT, getUserServiceIdUri(service), args.ClientToken, args) + +} + +// UserServiceRemoveAuth - Remove Auth to User Service +// +// PARAMS: +// - service: Service Domain +// - args: parameters to remove auth +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) UserServiceRemoveAuth(service string, args *UserServiceRemoveAuthArgs) error { + if args == nil { + args = &UserServiceRemoveAuthArgs{} + } + + if len(service) == 0 { + return fmt.Errorf("unset service") + } + + if len(args.UidList) == 0 { + return fmt.Errorf("unset auth list") + } + + for i := range args.UidList { + uid := args.UidList[i] + if uid == "" { + return fmt.Errorf("unset uid") + } + } + + return c.userServiceRequest("removeAuth", http.PUT, getUserServiceIdUri(service), args.ClientToken, args) +} + +// DescribeUserServices - describe all User Services +// +// PARAMS: +// - args: parameters to describe all User Services +// +// RETURNS: +// - *DescribeUserServicesResult: the result all User Services's detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeUserServices(args *DescribeUserServicesArgs) (*DescribeUserServicesResult, error) { + if args == nil { + args = &DescribeUserServicesArgs{} + } + + if args.MaxKeys > 1000 || args.MaxKeys <= 0 { + args.MaxKeys = 1000 + } + + result := &DescribeUserServicesResult{} + request := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getUserServiceUri()). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result) + + err := request.Do() + return result, err +} + +// DescribeUserServiceDetail - describe a User Service +// +// PARAMS: +// - service: describe Service Domain +// +// RETURNS: +// - *DescribeServiceDetailResult: the result Service detail +// - error: nil if ok otherwise the specific error +func (c *Client) DescribeUserServiceDetail(service string) (*DescribeUserServiceDetailResult, error) { + result := &DescribeUserServiceDetailResult{} + + if len(service) == 0 { + return nil, fmt.Errorf("unset service") + } + + err := bce.NewRequestBuilder(c). + WithMethod(http.GET). + WithURL(getUserServiceIdUri(service)). + WithResult(result). + Do() + + return result, err +} + +// DeleteUserService - delete a User Service +// +// PARAMS: +// - blbId: parameters to delete Service Domain +// +// RETURNS: +// - error: nil if ok otherwise the specific error +func (c *Client) DeleteUserService(service string) error { + if len(service) == 0 { + return fmt.Errorf("unset service") + } + return bce.NewRequestBuilder(c). + WithMethod(http.DELETE). + WithURL(getUserServiceIdUri(service)). + Do() +} diff --git a/bce-sdk-go/services/vca/api/media.go b/bce-sdk-go/services/vca/api/media.go new file mode 100644 index 0000000..36f496c --- /dev/null +++ b/bce-sdk-go/services/vca/api/media.go @@ -0,0 +1,74 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// media.go - the media APIs definition supported by the VCA service + +// Package api defines all APIs supported by the VCA service of BCE. +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func PutMedia(cli bce.Client, args *PutMediaArgs) (*GetMediaResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + MEDIA_URI) + req.SetMethod(http.PUT) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetMediaResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} + +func GetMedia(cli bce.Client, source string) (*GetMediaResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + MEDIA_URI) + req.SetMethod(http.GET) + req.SetParam("source", source) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetMediaResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/vca/api/model.go b/bce-sdk-go/services/vca/api/model.go new file mode 100644 index 0000000..0140859 --- /dev/null +++ b/bce-sdk-go/services/vca/api/model.go @@ -0,0 +1,71 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model for VCA + +package api + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + MEDIA_URI = "/media" +) + +type PutMediaArgs struct { + Source string `json:"source"` + Auth string `json:"auth"` + Title string `json:"title"` + Description string `json:"description"` + Preset string `json:"preset"` + Notification string `json:"notification"` +} + +type GetMediaResult struct { + Source string `json:"source"` + MediaId string `json:"mediaId"` + Title string `json:"title"` + Description string `json:"description"` + Preset string `json:"preset"` + Status string `json:"status"` + Percent int `json:"percent"` + Notification string `json:"notification"` + CreateTime string `json:"createTime"` + StartTime string `json:"startTime"` + PublishTime string `json:"publishTime"` + Results []AnalyzeResult `json:"results"` + Error AnalyzeError `json:"error"` +} + +type AnalyzeResult struct { + Type string `json:"type"` + Attributes []AnalyzeAttribute `json:"result"` +} + +type AnalyzeAttribute struct { + Attribute string `json:"attribute"` + Confidence float32 `json:"confidence"` + Source string `json:"source"` + AttributeTime []TimePeriod `json:"time"` +} + +type TimePeriod struct { + Start int `json:"start"` + End int `json:"end"` +} + +type AnalyzeError struct { + Code string `json:"code"` + Message string `json:"message"` +} diff --git a/bce-sdk-go/services/vca/client.go b/bce-sdk-go/services/vca/client.go new file mode 100644 index 0000000..89d97b1 --- /dev/null +++ b/bce-sdk-go/services/vca/client.go @@ -0,0 +1,68 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for VCA service + +// Package vca defines the VCA services of BCE. The supported APIs are all defined in sub-package +package vca + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/vca/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "vca." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN +) + +// Client of VCR service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the VCR service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +func (c *Client) PutMedia(args *api.PutMediaArgs) (*api.GetMediaResult, error) { + return api.PutMedia(c, args) +} + +func (c *Client) GetMedia(source string) (*api.GetMediaResult, error) { + return api.GetMedia(c, source) +} diff --git a/bce-sdk-go/services/vca/client_test.go b/bce-sdk-go/services/vca/client_test.go new file mode 100644 index 0000000..e7c8820 --- /dev/null +++ b/bce-sdk-go/services/vca/client_test.go @@ -0,0 +1,43 @@ +package vca + +import ( + "github.com/baidubce/bce-sdk-go/services/vca/api" + "github.com/baidubce/bce-sdk-go/util/log" + "testing" +) + +var CLIENT *Client + +const ( + AK = "YourAK" + SK = "YourSK" + MEDIA_SOURCE = "YourTestMedia" // e.g. "bos://YourBucket/dir/video.mp4 +) + +func init() { + CLIENT, _ = NewClient(AK, SK, "") + //log.SetLogHandler(log.STDERR | log.FILE) + //log.SetRotateType(log.ROTATE_SIZE) + //log.SetLogLevel(log.WARN) + + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) +} + +func TestPutMedia(t *testing.T) { + preset := "default" + args := &api.PutMediaArgs{Source: MEDIA_SOURCE, Preset: preset} + if res, err := CLIENT.PutMedia(args); err != nil { + t.Log("put media error") + } else { + t.Logf("%+v", res) + } +} + +func TestGetMedia(t *testing.T) { + if res, err := CLIENT.GetMedia(MEDIA_SOURCE); err != nil { + t.Log("get media error") + } else { + t.Logf("%+v", res) + } +} diff --git a/bce-sdk-go/services/vcr/api/image.go b/bce-sdk-go/services/vcr/api/image.go new file mode 100644 index 0000000..8617c5f --- /dev/null +++ b/bce-sdk-go/services/vcr/api/image.go @@ -0,0 +1,53 @@ +/* + * Copyright 2021 Baidu, Inc. + * + * 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. + */ + +// image.go - the image APIs definition supported by the VCR service + +// Package api defines all APIs supported by the VCR service of BCE. +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func PutImageSync(cli bce.Client, args *PutImageSyncArgs) (*PutImageSyncResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + IMAGE_URI) + req.SetMethod(http.PUT) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &PutImageSyncResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/vcr/api/media.go b/bce-sdk-go/services/vcr/api/media.go new file mode 100644 index 0000000..2e6e095 --- /dev/null +++ b/bce-sdk-go/services/vcr/api/media.go @@ -0,0 +1,71 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// media.go - the media APIs definition supported by the VCR service + +// Package api defines all APIs supported by the VCR service of BCE. +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func PutMedia(cli bce.Client, args *PutMediaArgs) error { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return err + } + + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + MEDIA_URI) + req.SetMethod(http.PUT) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return err + } + if resp.IsFail() { + return resp.ServiceError() + } + defer func() { resp.Body().Close() }() + return nil +} + +func GetMedia(cli bce.Client, source string) (*GetMediaResult, error) { + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + MEDIA_URI) + req.SetMethod(http.GET) + req.SetParam("source", source) + + // Send request and get response + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &GetMediaResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/vcr/api/model.go b/bce-sdk-go/services/vcr/api/model.go new file mode 100644 index 0000000..5ca6abe --- /dev/null +++ b/bce-sdk-go/services/vcr/api/model.go @@ -0,0 +1,106 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model for VCR + +package api + +import "github.com/baidubce/bce-sdk-go/bce" + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + MEDIA_URI = "/media" + TEXT_URI = "/text" + IMAGE_URI = "/image" +) + +type PutMediaArgs struct { + Source string `json:"source"` + Auth string `json:"auth"` + Description string `json:"description"` + Preset string `json:"preset"` + Notification string `json:"notification"` +} + +type GetMediaResult struct { + Source string `json:"source"` + MediaId string `json:"mediaId"` + Description string `json:"description"` + Preset string `json:"preset"` + Status string `json:"status"` + Percent int `json:"percent"` + Notification string `json:"notification"` + CreateTime string `json:"createTime"` + FinishTime string `json:"finishTime"` + Label string `json:"label"` + Results []CheckResult `json:"results"` + Error CheckError `json:"error"` +} + +type CheckResult struct { + Type string `json:"type"` + Items []ResultItem `json:"items"` +} + +type ResultItem struct { + SubType string `json:"subType"` + Target string `json:"target"` + TimeInSeconds int `json:"timeInSeconds"` + Confidence float32 `json:"confidence"` + Label string `json:"label"` + Extra string `json:"extra"` + Evidence Evidence `json:"evidence"` +} + +type Evidence struct { + Thumbnail string `json:"thumbnail"` + Location Location `json:"location"` + Text string `json:"text"` +} + +type Location struct { + LeftOffsetInPixel int `json:"leftOffsetInPixel"` + TopOffsetInPixel int `json:"topOffsetInPixel"` + WidthInPixel int `json:"widthInPixel"` + HeightInPixel int `json:"heightInPixel"` +} + +type CheckError struct { + Code string `json:"code"` + Message string `json:"message"` +} + +type PutTextArgs struct { + Text string `json:"text"` + Preset string `json:"preset"` +} + +type PutTextResult struct { + Text string `json:"text"` + Preset string `json:"preset"` + Results []CheckResult `json:"results"` +} + +type PutImageSyncArgs struct { + Source string `json:"source"` + Preset string `json:"preset"` +} + +type PutImageSyncResult struct { + Source string `json:"source"` + Label string `json:"label"` + Preset string `json:"preset"` + Status string `json:"status"` + Results []CheckResult `json:"results"` +} diff --git a/bce-sdk-go/services/vcr/api/text.go b/bce-sdk-go/services/vcr/api/text.go new file mode 100644 index 0000000..c00c16a --- /dev/null +++ b/bce-sdk-go/services/vcr/api/text.go @@ -0,0 +1,53 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// media.go - the media APIs definition supported by the VCR service + +// Package api defines all APIs supported by the VCR service of BCE. +package api + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +func PutText(cli bce.Client, args *PutTextArgs) (*PutTextResult, error) { + jsonBytes, jsonErr := json.Marshal(args) + if jsonErr != nil { + return nil, jsonErr + } + body, err := bce.NewBodyFromBytes(jsonBytes) + if err != nil { + return nil, err + } + + req := &bce.BceRequest{} + req.SetUri(URI_PREFIX + TEXT_URI) + req.SetMethod(http.PUT) + req.SetBody(body) + + resp := &bce.BceResponse{} + if err := cli.SendRequest(req, resp); err != nil { + return nil, err + } + if resp.IsFail() { + return nil, resp.ServiceError() + } + jsonBody := &PutTextResult{} + if err := resp.ParseJsonBody(jsonBody); err != nil { + return nil, err + } + return jsonBody, nil +} diff --git a/bce-sdk-go/services/vcr/client.go b/bce-sdk-go/services/vcr/client.go new file mode 100644 index 0000000..01df208 --- /dev/null +++ b/bce-sdk-go/services/vcr/client.go @@ -0,0 +1,91 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for VCR service + +// Package vcr defines the VCR services of BCE. The supported APIs are all defined in sub-package +package vcr + +import ( + "github.com/baidubce/bce-sdk-go/auth" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/services/vcr/api" +) + +const ( + DEFAULT_SERVICE_DOMAIN = "vcr." + bce.DEFAULT_REGION + "." + bce.DEFAULT_DOMAIN +) + +// Client of VCR service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +// NewClient make the VCR service client with default configuration. +// Use `cli.Config.xxx` to access the config or change it to non-default value. +func NewClient(ak, sk, endpoint string) (*Client, error) { + credentials, err := auth.NewBceCredentials(ak, sk) + if err != nil { + return nil, err + } + if len(endpoint) == 0 { + endpoint = DEFAULT_SERVICE_DOMAIN + } + defaultSignOptions := &auth.SignOptions{ + HeadersToSign: auth.DEFAULT_HEADERS_TO_SIGN, + ExpireSeconds: auth.DEFAULT_EXPIRE_SECONDS} + defaultConf := &bce.BceClientConfiguration{ + Endpoint: endpoint, + Region: bce.DEFAULT_REGION, + UserAgent: bce.DEFAULT_USER_AGENT, + Credentials: credentials, + SignOption: defaultSignOptions, + Retry: bce.DEFAULT_RETRY_POLICY, + ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} + v1Signer := &auth.BceV1Signer{} + + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} + return client, nil +} + +func (c *Client) PutMedia(args *api.PutMediaArgs) error { + return api.PutMedia(c, args) +} + +func (c *Client) SimplePutMedia(source string, description string, preset string, notification string) error { + args := &api.PutMediaArgs{Source: source, Description: description, Preset: preset, Notification: notification} + return api.PutMedia(c, args) +} + +func (c *Client) GetMedia(source string) (*api.GetMediaResult, error) { + return api.GetMedia(c, source) +} + +func (c *Client) PutText(args *api.PutTextArgs) (*api.PutTextResult, error) { + return api.PutText(c, args) +} + +func (c *Client) SimplePutText(text string) (*api.PutTextResult, error) { + args := &api.PutTextArgs{Text: text} + return api.PutText(c, args) +} + +func (c *Client) PutImageSync(args *api.PutImageSyncArgs) (*api.PutImageSyncResult, error) { + return api.PutImageSync(c, args) +} + +func (c *Client) SimplePutImageSync(source string) (*api.PutImageSyncResult, error) { + args := &api.PutImageSyncArgs{Source: source} + return api.PutImageSync(c, args) +} diff --git a/bce-sdk-go/services/vcr/client_test.go b/bce-sdk-go/services/vcr/client_test.go new file mode 100644 index 0000000..87136b4 --- /dev/null +++ b/bce-sdk-go/services/vcr/client_test.go @@ -0,0 +1,88 @@ +package vcr + +import ( + "github.com/baidubce/bce-sdk-go/services/vcr/api" + "github.com/baidubce/bce-sdk-go/util/log" + "testing" +) + +var CLIENT *Client + +const ( + AK = "YourAK" + SK = "YourSK" + MEDIA_SOURCE = "YourTestMedia" // e.g. "bos://YourBucket/dir/video.mp4 + TEXT = "YourTestText" + IMAGE_SOURCE = "YourTestImage" // e.g. "bos://YourBucket/dir/image.jpg" +) + +func init() { + CLIENT, _ = NewClient(AK, SK, "") + //log.SetLogHandler(log.STDERR | log.FILE) + //log.SetRotateType(log.ROTATE_SIZE) + //log.SetLogLevel(log.WARN) + + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) +} + +func TestPutMedia(t *testing.T) { + preset := "default" + desc := "vcr_test" + args := &api.PutMediaArgs{Source: MEDIA_SOURCE, Preset: preset, Description: desc} + if err := CLIENT.PutMedia(args); err != nil { + t.Log("put media error") + } else { + t.Log("put media success") + } +} + +func TestSimplePutMedia(t *testing.T) { + if err := CLIENT.SimplePutMedia(MEDIA_SOURCE, "", "", ""); err != nil { + t.Log("simple put media error") + } else { + t.Log("simple put media success") + } +} + +func TestGetMedia(t *testing.T) { + if res, err := CLIENT.GetMedia(MEDIA_SOURCE); err != nil { + t.Log("get media error") + } else { + t.Logf("%+v", res) + } +} + +func TestPutText(t *testing.T) { + args := &api.PutTextArgs{Text: TEXT} + if res, err := CLIENT.PutText(args); err != nil { + t.Log("simple put text error") + } else { + t.Logf("%+v", res) + } +} + +func TestSimplePutText(t *testing.T) { + if res, err := CLIENT.SimplePutText(TEXT); err != nil { + t.Log("simple put text error") + } else { + t.Logf("%+v", res) + } +} + +func TestPutImageSync(t *testing.T) { + args := &api.PutImageSyncArgs{Source: IMAGE_SOURCE} + if res, err := CLIENT.PutImageSync(args); err != nil { + t.Log("simple put image sync error", err) + } else { + t.Logf("%+v", res) + } +} + +func TestSimplePutImageSync(t *testing.T) { + if res, err := CLIENT.SimplePutImageSync(IMAGE_SOURCE); err != nil { + t.Log("simple put image sync error", err) + } else { + t.Logf("%+v", res) + } +} diff --git a/bce-sdk-go/services/vpc/acl.go b/bce-sdk-go/services/vpc/acl.go new file mode 100644 index 0000000..e542340 --- /dev/null +++ b/bce-sdk-go/services/vpc/acl.go @@ -0,0 +1,127 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// acl.go - the acl APIs definition supported by the VPC service + +package vpc + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// ListAclEntrys - list all acl entrys of the given VPC +// +// PARAMS: +// - vpcId: the id of the specific VPC +// +// RETURNS: +// - *ListAclEntrysResult: the result of all acl entrys +// - error: nil if success otherwise the specific error +func (c *Client) ListAclEntrys(vpcId string) (*ListAclEntrysResult, error) { + result := &ListAclEntrysResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForAclEntry()). + WithMethod(http.GET). + WithQueryParam("vpcId", vpcId). + WithResult(result). + Do() + + return result, err +} + +// CreateAclRule - create a new acl rule with the specific parameters +// +// PARAMS: +// - args: the arguments to create acl rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateAclRule(args *CreateAclRuleArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForAclRule()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// ListAclRules - list all acl rules with the specific parameters +// +// PARAMS: +// - args: the arguments to list all acl rules +// +// RETURNS: +// - *ListAclRulesResult: the result of all acl rules +// - error: nil if success otherwise the specific error +func (c *Client) ListAclRules(args *ListAclRulesArgs) (*ListAclRulesResult, error) { + if args == nil { + return nil, fmt.Errorf("The listAclRulesArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListAclRulesResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForAclRule()). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithQueryParam("subnetId", args.SubnetId). + WithResult(result). + Do() + + return result, err +} + +// UpdateAclRule - udpate acl rule with the specific parameters +// +// PARAMS: +// - aclRuleId: the id of the specific acl rule +// - args: the arguments to update acl rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateAclRule(aclRuleId string, args *UpdateAclRuleArgs) error { + if args == nil { + args = &UpdateAclRuleArgs{} + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForAclRuleId(aclRuleId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// DeleteAclRule - delete the specific acl rule +// +// PARAMS: +// - aclRuleId: the id of the specific acl rule +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteAclRule(aclRuleId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForAclRuleId(aclRuleId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} diff --git a/bce-sdk-go/services/vpc/client.go b/bce-sdk-go/services/vpc/client.go new file mode 100644 index 0000000..5322d0e --- /dev/null +++ b/bce-sdk-go/services/vpc/client.go @@ -0,0 +1,145 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for VPC service + +// Package vpc defines the VPC services of BCE. +// The supported APIs are all defined in different files. +package vpc + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_VPC_URL = "/vpc" + REQUEST_SUBNET_URL = "/subnet" + REQUEST_ROUTE_URL = "/route" + REQUEST_RULE_URL = "/rule" + REQUEST_ACL_URL = "/acl" + REQUEST_NAT_URL = "/nat" + REQUEST_PEERCONN_URL = "/peerconn" + REQUEST_NETWORK_TOPOLOGY_URL = "/topology" + REQUEST_PROBE_URL = "/probe" + REQUEST_NETWORK_IPV6GATEWAY_URL = "/IPv6Gateway" +) + +// Client of VPC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{BceClient: client}, nil +} + +func getURLForVPC() string { + return URI_PREFIX + REQUEST_VPC_URL +} + +func getURLForVPCId(vpcId string) string { + return getURLForVPC() + "/" + vpcId +} + +func getURLForSubnet() string { + return URI_PREFIX + REQUEST_SUBNET_URL +} + +func getURLForSubnetId(subnetId string) string { + return getURLForSubnet() + "/" + subnetId +} + +// getURLForIpreserve 返回一个包含 /ipreserve 的请求 URL +func getURLForIpreserve() string { + // URI_PREFIX + REQUEST_SUBNET_URL + "/ipreserve" + return getURLForSubnet() + "/ipreserve" +} + +// getURLForDeleteIpreserve returns the url for deleting an IP preserve. +func getURLForDeleteIpreserve(ipReserveId string) string { + // URI_PREFIX + REQUEST_SUBNET_URL + "/ipreserve/" + ipReserveId + return getURLForSubnet() + "/ipreserve/" + ipReserveId +} + +func getURLForRouteTable() string { + return URI_PREFIX + REQUEST_ROUTE_URL +} + +func getURLForRouteRule() string { + return getURLForRouteTable() + REQUEST_RULE_URL +} + +func getURLForRouteRuleId(routeRuleId string) string { + return getURLForRouteRule() + "/" + routeRuleId +} + +func getURLForAclEntry() string { + return URI_PREFIX + REQUEST_ACL_URL +} + +func getURLForAclRule() string { + return URI_PREFIX + REQUEST_ACL_URL + REQUEST_RULE_URL +} + +func getURLForAclRuleId(aclRuleId string) string { + return URI_PREFIX + REQUEST_ACL_URL + REQUEST_RULE_URL + "/" + aclRuleId +} + +func getURLForNat() string { + return URI_PREFIX + REQUEST_NAT_URL +} + +func getURLForNatId(natId string) string { + return getURLForNat() + "/" + natId +} + +func getURLForPeerConn() string { + return URI_PREFIX + REQUEST_PEERCONN_URL +} + +func getURLForPeerConnId(peerConnId string) string { + return getURLForPeerConn() + "/" + peerConnId +} + +// getURLForNetworkTopology 获取网络拓扑信息的URL +func getURLForNetworkTopology() string { + return getURLForVPC() + REQUEST_NETWORK_TOPOLOGY_URL +} + +func getURLForProbe() string { + return URI_PREFIX + REQUEST_PROBE_URL +} + +func getURLForProbeId(probeId string) string { + return getURLForProbe() + "/" + probeId +} + +func getURLForIpv6Gateway() string { + return URI_PREFIX + REQUEST_NETWORK_IPV6GATEWAY_URL +} + +func getURLForIpv6GatewayId(ipv6GatewayId string) string { + return getURLForIpv6Gateway() + "/" + ipv6GatewayId +} diff --git a/bce-sdk-go/services/vpc/client_test.go b/bce-sdk-go/services/vpc/client_test.go new file mode 100644 index 0000000..85ab1fb --- /dev/null +++ b/bce-sdk-go/services/vpc/client_test.go @@ -0,0 +1,1125 @@ +package vpc + +import ( + "encoding/json" + "fmt" + "os" + "path/filepath" + "reflect" + "runtime" + "strings" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/model" + "github.com/baidubce/bce-sdk-go/services/eip" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + VPC_CLIENT *Client + EIP_CLIENT *eip.Client + + region string + + VPCID string + SubnetID string + RouteTableID string + RouteRuleID string + AclRuleID string + NatID string + PeerConnID string + LocalIfID string + PeerVPCID string + EIPAddress string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + VPCEndpoint string `json:"VPC"` + EIPEndpoint string `json:"EIP"` +} + +func init() { + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + //for i := 0; i < 7; i++ { + // f = filepath.Dir(f) + //} + f = filepath.Dir(f) + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + VPC_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.VPCEndpoint) + EIP_CLIENT, _ = eip.NewClient(confObj.AK, confObj.SK, confObj.EIPEndpoint) + log.SetLogLevel(log.WARN) + + region = confObj.VPCEndpoint[4:6] +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestCreateVPCDhcp(t *testing.T) { + VPCID = "" + args := &CreateVpcDhcpArgs{ + DomainNameServers: "3.3.3.5", + ClientToken: getClientToken(), + } + err := VPC_CLIENT.CreateVPCDhcp(VPCID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestUpdateVPCDhcp(t *testing.T) { + VPCID = "" + args := &UpdateVpcDhcpArgs{ + DomainNameServers: "", + ClientToken: getClientToken(), + } + err := VPC_CLIENT.UpdateVPCDhcp(VPCID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetVPCDhcp(t *testing.T) { + VPCID = "" + result, err := VPC_CLIENT.GetVPCDhcpInfo(VPCID) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestCreateVPC(t *testing.T) { + args := &CreateVPCArgs{ + Name: "TestSDK-VPC", + Description: "vpc test", + Cidr: "192.168.0.0/16", + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + ClientToken: getClientToken(), + } + result, err := VPC_CLIENT.CreateVPC(args) + ExpectEqual(t.Errorf, nil, err) + + VPCID = result.VPCID +} + +func TestListVPC(t *testing.T) { + args := &ListVPCArgs{ + MaxKeys: 1000, + IsDefault: "false", + } + res, err := VPC_CLIENT.ListVPC(args) + fmt.Println(res.VPCs[0].CreatedTime) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) +} + +func TestGetVPCDetail(t *testing.T) { + result, err := VPC_CLIENT.GetVPCDetail(VPCID) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) + ExpectEqual(t.Errorf, "TestSDK-VPC", result.VPC.Name) + ExpectEqual(t.Errorf, "vpc test", result.VPC.Description) + ExpectEqual(t.Errorf, "192.168.0.0/16", result.VPC.Cidr) + ExpectEqual(t.Errorf, 1, len(result.VPC.Tags)) + ExpectEqual(t.Errorf, "tagK", result.VPC.Tags[0].TagKey) + ExpectEqual(t.Errorf, "tagV", result.VPC.Tags[0].TagValue) +} + +func TestUpdateVPC(t *testing.T) { + args := &UpdateVPCArgs{ + Name: "TestSDK-VPC-update", + Description: "vpc update", + ClientToken: getClientToken(), + } + err := VPC_CLIENT.UpdateVPC(VPCID, args) + ExpectEqual(t.Errorf, nil, err) + + result, err := VPC_CLIENT.GetVPCDetail(VPCID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "TestSDK-VPC-update", result.VPC.Name) + ExpectEqual(t.Errorf, "vpc update", result.VPC.Description) +} + +func TestGetPrivateIpAddressInfo(t *testing.T) { + args := &GetVpcPrivateIpArgs{ + VpcId: "vpc-2pa2x0bjt26i", + PrivateIpAddresses: []string{"192.168.0.1,192.168.0.2"}, + PrivateIpRange: "192.168.0.0-192.168.0.45", + } + result, err := VPC_CLIENT.GetPrivateIpAddressesInfo(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} +func TestCreateSubnet(t *testing.T) { + args := &CreateSubnetArgs{ + Name: "TestSDK-Subnet", + ZoneName: fmt.Sprintf("cn-%s-a", region), + Cidr: "192.168.1.0/24", + VpcId: VPCID, + SubnetType: SUBNET_TYPE_BCC, + Description: "test subnet", + EnableIpv6: true, + Tags: []model.TagModel{ + { + TagKey: "tagK", + TagValue: "tagV", + }, + }, + ClientToken: getClientToken(), + } + result, err := VPC_CLIENT.CreateSubnet(args) + ExpectEqual(t.Errorf, nil, err) + + SubnetID = result.SubnetId +} + +func TestListSubnets(t *testing.T) { + args := &ListSubnetArgs{ + VpcId: VPCID, + SubnetType: SUBNET_TYPE_BCC, + } + _, err := VPC_CLIENT.ListSubnets(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetSubnetDetail(t *testing.T) { + result, err := VPC_CLIENT.GetSubnetDetail(SubnetID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "TestSDK-Subnet", result.Subnet.Name) + ExpectEqual(t.Errorf, fmt.Sprintf("cn-%s-a", region), result.Subnet.ZoneName) + ExpectEqual(t.Errorf, "192.168.1.0/24", result.Subnet.Cidr) + ExpectEqual(t.Errorf, VPCID, result.Subnet.VPCId) + ExpectEqual(t.Errorf, SUBNET_TYPE_BCC, result.Subnet.SubnetType) + ExpectEqual(t.Errorf, "test subnet", result.Subnet.Description) + ExpectEqual(t.Errorf, 1, len(result.Subnet.Tags)) + ExpectEqual(t.Errorf, "tagK", result.Subnet.Tags[0].TagKey) + ExpectEqual(t.Errorf, "tagV", result.Subnet.Tags[0].TagValue) +} + +func TestUpdateSubnet(t *testing.T) { + args := &UpdateSubnetArgs{ + ClientToken: getClientToken(), + Name: "TestSDK-Subnet-update", + Description: "subnet update", + EnableIpv6: true, + } + err := VPC_CLIENT.UpdateSubnet(SubnetID, args) + ExpectEqual(t.Errorf, nil, err) + + result, err := VPC_CLIENT.GetSubnetDetail(SubnetID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "TestSDK-Subnet-update", result.Subnet.Name) + ExpectEqual(t.Errorf, "subnet update", result.Subnet.Description) +} + +func TestListAclEntrys(t *testing.T) { + _, err := VPC_CLIENT.ListAclEntrys(VPCID) + ExpectEqual(t.Errorf, nil, err) +} + +func TestCreateAclRule(t *testing.T) { + args := &CreateAclRuleArgs{ + ClientToken: getClientToken(), + AclRules: []AclRuleRequest{ + { + SubnetId: SubnetID, + Description: "test acl rule", + Protocol: ACL_RULE_PROTOCOL_TCP, + SourceIpAddress: "192.168.1.1", + DestinationIpAddress: "172.17.1.1", + SourcePort: "5555", + DestinationPort: "6666", + Position: 10, + Direction: ACL_RULE_DIRECTION_EGRESS, + Action: ACL_RULE_ACTION_ALLOW, + }, + }, + } + err := VPC_CLIENT.CreateAclRule(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestListAclRules(t *testing.T) { + args := &ListAclRulesArgs{ + SubnetId: SubnetID, + } + result, err := VPC_CLIENT.ListAclRules(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 3, len(result.AclRules)) + for _, acl := range result.AclRules { + if acl.Position == 10 { + ExpectEqual(t.Errorf, SubnetID, acl.SubnetId) + ExpectEqual(t.Errorf, "test acl rule", acl.Description) + ExpectEqual(t.Errorf, ACL_RULE_PROTOCOL_TCP, acl.Protocol) + ExpectEqual(t.Errorf, "192.168.1.1/32", acl.SourceIpAddress) + ExpectEqual(t.Errorf, "172.17.1.1/32", acl.DestinationIpAddress) + ExpectEqual(t.Errorf, "5555", acl.SourcePort) + ExpectEqual(t.Errorf, "6666", acl.DestinationPort) + ExpectEqual(t.Errorf, ACL_RULE_DIRECTION_EGRESS, acl.Direction) + ExpectEqual(t.Errorf, ACL_RULE_ACTION_ALLOW, acl.Action) + AclRuleID = acl.Id + break + } + } + if AclRuleID == "" { + t.Errorf("Test acl rule failed.") + } +} + +func TestUpdateAclRule(t *testing.T) { + args := &UpdateAclRuleArgs{ + ClientToken: getClientToken(), + Description: "acl rule update", + Protocol: ACL_RULE_PROTOCOL_UDP, + SourceIpAddress: "192.168.1.2", + DestinationIpAddress: "172.17.1.2", + SourcePort: "7777", + DestinationPort: "8888", + Position: 10, + Action: ACL_RULE_ACTION_DENY, + } + err := VPC_CLIENT.UpdateAclRule(AclRuleID, args) + ExpectEqual(t.Errorf, nil, err) + + listAclArgs := &ListAclRulesArgs{SubnetId: SubnetID} + result, err := VPC_CLIENT.ListAclRules(listAclArgs) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 3, len(result.AclRules)) + isExist := false + for _, acl := range result.AclRules { + if acl.Position == 10 { + isExist = true + ExpectEqual(t.Errorf, SubnetID, acl.SubnetId) + ExpectEqual(t.Errorf, "acl rule update", acl.Description) + ExpectEqual(t.Errorf, ACL_RULE_PROTOCOL_UDP, acl.Protocol) + ExpectEqual(t.Errorf, "192.168.1.2/32", acl.SourceIpAddress) + ExpectEqual(t.Errorf, "172.17.1.2/32", acl.DestinationIpAddress) + ExpectEqual(t.Errorf, "7777", acl.SourcePort) + ExpectEqual(t.Errorf, "8888", acl.DestinationPort) + ExpectEqual(t.Errorf, ACL_RULE_ACTION_DENY, acl.Action) + break + } + } + if !isExist { + t.Errorf("Test acl rule failed.") + } +} + +func TestCreateDefaultNatGateway(t *testing.T) { + args := &CreateNatGatewayArgs{ + ClientToken: getClientToken(), + Name: "Test-SDK-NatGateway", + VpcId: VPCID, + Spec: NAT_GATEWAY_SPEC_SMALL, + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + }, + } + result, err := VPC_CLIENT.CreateNatGateway(args) + ExpectEqual(t.Errorf, nil, err) + NatID = result.NatId + + err = waitStateForNatGateway(NatID, NAT_STATUS_UNCONFIGURED) + ExpectEqual(t.Errorf, nil, err) +} + +func TestCreateEnhanceNatGateway(t *testing.T) { + args := &CreateNatGatewayArgs{ + ClientToken: getClientToken(), + Name: "Test-SDK-NatGateway-CU", + VpcId: VPCID, + CuNum: "3", + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + } + result, err := VPC_CLIENT.CreateNatGateway(args) + ExpectEqual(t.Errorf, nil, err) + NatID = result.NatId + + err = waitStateForNatGateway(NatID, NAT_STATUS_UNCONFIGURED) + ExpectEqual(t.Errorf, nil, err) +} + +func TestGetRouteTableDetail(t *testing.T) { + RouteTableID = "" + result, err := VPC_CLIENT.GetRouteTableDetail(RouteTableID, VPCID) + r, err := json.Marshal(result) + fmt.Println(string(r)) + ExpectEqual(t.Errorf, nil, err) + RouteTableID = result.RouteTableId +} + +func TestCreateRouteRule(t *testing.T) { + args := &CreateRouteRuleArgs{ + ClientToken: getClientToken(), + RouteTableId: RouteTableID, + SourceAddress: "192.168.1.0/24", + DestinationAddress: "172.17.0.0/16", + NexthopType: NEXTHOP_TYPE_NAT, + NexthopId: NatID, + Description: "test route rule", + } + result, err := VPC_CLIENT.CreateRouteRule(args) + ExpectEqual(t.Errorf, nil, err) + + RouteRuleID = result.RouteRuleId + + routeTable, err := VPC_CLIENT.GetRouteTableDetail("", VPCID) + ExpectEqual(t.Errorf, nil, err) + isExist := false + for _, rule := range routeTable.RouteRules { + if rule.RouteRuleId == result.RouteRuleId { + isExist = true + ExpectEqual(t.Errorf, RouteTableID, rule.RouteTableId) + ExpectEqual(t.Errorf, "192.168.1.0/24", rule.SourceAddress) + ExpectEqual(t.Errorf, "172.17.0.0/16", rule.DestinationAddress) + ExpectEqual(t.Errorf, NEXTHOP_TYPE_NAT, rule.NexthopType) + ExpectEqual(t.Errorf, NatID, rule.NexthopId) + ExpectEqual(t.Errorf, "test route rule", rule.Description) + } + } + if !isExist { + t.Errorf("Test route rule failed.") + } +} + +func TestCreateEtGatewayRouteRule(t *testing.T) { + RouteTableID = "" + var SourceAddress = "12.0.0.0/25" + var DestinationAddress = "2.2.2.6/32" + var Description = "sdk test etGateway route rule" + var NexthopType = NEXTHOP_TYPE_ETGATEWAY + + mulargs := &CreateRouteRuleArgs{ + ClientToken: getClientToken(), + RouteTableId: RouteTableID, + SourceAddress: SourceAddress, + DestinationAddress: DestinationAddress, + NextHopList: []NextHop{ + { + NexthopId: "", + NexthopType: NexthopType, + PathType: "ha:active", + }, { + NexthopId: "", + NexthopType: NexthopType, + PathType: "ha:standby", + }, + }, + Description: Description, + } + result, err := VPC_CLIENT.CreateRouteRule(mulargs) + + r, err := json.Marshal(result) + fmt.Println(string(r)) + fmt.Println(err) + + ExpectEqual(t.Errorf, nil, err) + + var RouteRuleIds = result.RouteRuleIds + routeTable, err := VPC_CLIENT.GetRouteTableDetail(RouteTableID, VPCID) + ExpectEqual(t.Errorf, nil, err) + isExist := false + for _, rule := range routeTable.RouteRules { + for _, RouteRuleId := range RouteRuleIds { + if rule.RouteRuleId == RouteRuleId { + isExist = true + ExpectEqual(t.Errorf, RouteTableID, rule.RouteTableId) + ExpectEqual(t.Errorf, SourceAddress, rule.SourceAddress) + ExpectEqual(t.Errorf, DestinationAddress, rule.DestinationAddress) + ExpectEqual(t.Errorf, NexthopType, rule.NexthopType) + ExpectEqual(t.Errorf, Description, rule.Description) + } + } + } + if !isExist { + t.Errorf("Test route rule failed.") + } +} + +func TestListNatGateway(t *testing.T) { + args := &ListNatGatewayArgs{ + VpcId: VPCID, + NatId: NatID, + } + result, err := VPC_CLIENT.ListNatGateway(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 1, len(result.Nats)) +} + +func TestGetNatGatewayDetail(t *testing.T) { + result, err := VPC_CLIENT.GetNatGatewayDetail("nat-bzrav7t2ppb5") + tags := []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + } + r, _ := json.Marshal(result) + fmt.Println(string(r)) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Test-SDK-NatGateway", result.Name) + ExpectEqual(t.Errorf, VPCID, result.VpcId) + ExpectEqual(t.Errorf, NAT_GATEWAY_SPEC_SMALL, result.Spec) + ExpectEqual(t.Errorf, PAYMENT_TIMING_POSTPAID, result.PaymentTiming) + ExpectEqual(t.Errorf, tags, result.Tags) +} + +func TestUpdateNatGateway(t *testing.T) { + args := &UpdateNatGatewayArgs{ + ClientToken: getClientToken(), + Name: "Test-SDK-NatGateway-update", + } + err := VPC_CLIENT.UpdateNatGateway(NatID, args) + ExpectEqual(t.Errorf, nil, err) + + result, err := VPC_CLIENT.GetNatGatewayDetail(NatID) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "Test-SDK-NatGateway-update", result.Name) +} + +func TestResizeNatGateway(t *testing.T) { + args := &ResizeNatGatewayArgs{ + ClientToken: getClientToken(), + CuNum: 8, + } + err := VPC_CLIENT.ResizeNatGateway(NatID, args) + ExpectEqual(t.Errorf, nil, err) + err = waitCuNumForNatGateway(NatID, args.CuNum) + ExpectEqual(t.Errorf, nil, err) +} + +func TestBindEips(t *testing.T) { + // create eip first + args := &eip.CreateEipArgs{ + Name: "sdk-eip", + BandWidthInMbps: 10, + Billing: &eip.Billing{ + PaymentTiming: "Postpaid", + BillingMethod: "ByTraffic", + }, + ClientToken: getClientToken(), + } + result, err := EIP_CLIENT.CreateEip(args) + ExpectEqual(t.Errorf, nil, err) + EIPAddress = result.Eip + + // wait until the eip available + err = waitStateForEIP(EIPAddress, "available") + ExpectEqual(t.Errorf, nil, err) + + // bind eip + bindEipArgs := &BindEipsArgs{ + ClientToken: getClientToken(), + Eips: []string{EIPAddress}, + } + err = VPC_CLIENT.BindEips(NatID, bindEipArgs) + ExpectEqual(t.Errorf, nil, err) + + // wait until the eip bind completed + err = waitStateForNatGateway(NatID, NAT_STATUS_ACTIVE) + ExpectEqual(t.Errorf, nil, err) +} + +func TestUnBindEips(t *testing.T) { + // unbind eip + args := &UnBindEipsArgs{ + ClientToken: getClientToken(), + Eips: []string{EIPAddress}, + } + err := VPC_CLIENT.UnBindEips(NatID, args) + ExpectEqual(t.Errorf, nil, err) + + // wait until the eip unbind completed + err = waitStateForNatGateway(NatID, NAT_STATUS_UNCONFIGURED) + ExpectEqual(t.Errorf, nil, err) + + // delete eip + err = EIP_CLIENT.DeleteEip(EIPAddress, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestRenewNatGateway(t *testing.T) { + args := &RenewNatGatewayArgs{ + ClientToken: getClientToken(), + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + } + err := VPC_CLIENT.RenewNatGateway(NatID, args) + if err == nil { + t.Errorf("Test RenewNatGateway failed.") + } +} + +func TestCreateNatGatewaySnatRule(t *testing.T) { + args := &CreateNatGatewaySnatRuleArgs{ + RuleName: "sdk-test", + PublicIpAddresses: []string{"100.88.10.84"}, + SourceCIDR: "192.168.3.33", + } + result, err := VPC_CLIENT.CreateNatGatewaySnatRule("nat-b1jb3b5e34tc", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestBatchCreateNatGatewaySnatRule(t *testing.T) { + snatargs1 := SnatRuleArgs{ + RuleName: "sdk-test-b1", + PublicIpAddresses: []string{"100.88.9.91", "100.88.2.154"}, + SourceCIDR: "192.168.3.6", + } + snatargs2 := SnatRuleArgs{ + RuleName: "sdk-test-b2", + PublicIpAddresses: []string{"100.88.10.84", "100.88.2.154"}, + SourceCIDR: "192.168.3.7", + } + + args := &BatchCreateNatGatewaySnatRuleArgs{ + NatId: "nat-b1jb3b5e34tc", + } + + args.SnatRules = append(args.SnatRules, snatargs1) + args.SnatRules = append(args.SnatRules, snatargs2) + result, err := VPC_CLIENT.BatchCreateNatGatewaySnatRule(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestUpdateNatGatewaySnatRule(t *testing.T) { + args := &UpdateNatGatewaySnatRuleArgs{ + RuleName: "sdk-test-1", + SourceCIDR: "192.168.3.66", + } + result := VPC_CLIENT.UpdateNatGatewaySnatRule("nat-b1jb3b5e34tc", "rule-7zr5941yngks", args) + r, _ := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestDeleteNatGatewaySnatRule(t *testing.T) { + result := VPC_CLIENT.DeleteNatGatewaySnatRule("nat-b1jb3b5e34tc", "rule-7zr5941yngks", getClientToken()) + r, _ := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestListNatGatewaySnatRules(t *testing.T) { + args := &ListNatGatewaySnatRuleArgs{ + NatId: "nat-b1jb3b5e34tc", + } + result, err := VPC_CLIENT.ListNatGatewaySnatRules(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestCreateNatGatewayDnatRule(t *testing.T) { + args := &CreateNatGatewayDnatRuleArgs{ + RuleName: "sdk-test", + PublicIpAddress: "100.88.0.217", + PrivateIpAddress: "192.168.1.4", + Protocol: "TCP", + PublicPort: "121", + PrivatePort: "122", + } + result, err := VPC_CLIENT.CreateNatGatewayDnatRule("nat-b1jb3b5e34tc", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestBatchCreateNatGatewayDnatRule(t *testing.T) { + snatargs1 := DnatRuleArgs{ + RuleName: "sdk-test-db1", + PublicIpAddress: "100.88.0.217", + PrivateIpAddress: "192.168.1.21", + Protocol: "TCP", + PublicPort: "1211", + PrivatePort: "1221", + } + snatargs2 := DnatRuleArgs{ + RuleName: "sdk-test-db2", + PublicIpAddress: "100.88.0.217", + PrivateIpAddress: "192.168.1.22", + Protocol: "TCP", + PublicPort: "1212", + PrivatePort: "1222", + } + + args := &BatchCreateNatGatewayDnatRuleArgs{ + Rules: []DnatRuleArgs{snatargs1, snatargs2}, + } + + result, err := VPC_CLIENT.BatchCreateNatGatewayDnatRule("nat-b1jb3b5e34tc", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestUpdateNatGatewayDnatRule(t *testing.T) { + args := &UpdateNatGatewayDnatRuleArgs{ + RuleName: "sdk-test-3", + PrivateIpAddress: "192.168.1.5", + } + result := VPC_CLIENT.UpdateNatGatewayDnatRule("nat-b1jb3b5e34tc", "rule-8gee5abqins0", args) + r, _ := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestDeleteNatGatewayDnatRule(t *testing.T) { + result := VPC_CLIENT.DeleteNatGatewayDnatRule("nat-b1jb3b5e34tc", "rule-8gee5abqins0", getClientToken()) + r, _ := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestListNatGatewayDnatRules(t *testing.T) { + args := &ListNatGatewaDnatRuleArgs{ + MaxKeys: 2, + Marker: "rule-29n3en0z8tku", + } + result, err := VPC_CLIENT.ListNatGatewayDnatRules("nat-b1jb3b5e34tc", args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestCreatePeerConn(t *testing.T) { + // create another VPC + createVPCArgs := &CreateVPCArgs{ + Name: "TestSDK-VPC-Peer", + Description: "vpc test", + Cidr: "172.17.0.0/16", + ClientToken: getClientToken(), + } + vpcResult, err := VPC_CLIENT.CreateVPC(createVPCArgs) + ExpectEqual(t.Errorf, nil, err) + PeerVPCID = vpcResult.VPCID + + args := &CreatePeerConnArgs{ + ClientToken: getClientToken(), + BandwidthInMbps: 10, + Description: "test peer conn", + LocalIfName: "local-interface", + LocalVpcId: VPCID, + PeerVpcId: PeerVPCID, + PeerRegion: region, + PeerIfName: "peer-interface", + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + Tags: []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + }, + } + result, err := VPC_CLIENT.CreatePeerConn(args) + ExpectEqual(t.Errorf, nil, err) + + PeerConnID = result.PeerConnId + + // wait until peerconn active + err = waitStateForPeerConn(PeerConnID, PEERCONN_STATUS_ACTIVE) + ExpectEqual(t.Errorf, nil, err) +} + +func TestListPeerConn(t *testing.T) { + args := &ListPeerConnsArgs{ + VpcId: VPCID, + } + result, err := VPC_CLIENT.ListPeerConn(args) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 1, len(result.PeerConns)) +} + +func TestGetPeerConnDetail(t *testing.T) { + result, err := VPC_CLIENT.GetPeerConnDetail(PeerConnID, PEERCONN_ROLE_INITIATOR) + r, _ := json.Marshal(result) + fmt.Println(string(r)) + tags := []model.TagModel{ + { + TagKey: "tagKey", + TagValue: "tagValue", + }, + } + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, 10, result.BandwidthInMbps) + ExpectEqual(t.Errorf, "test peer conn", result.Description) + ExpectEqual(t.Errorf, "local-interface", result.LocalIfName) + ExpectEqual(t.Errorf, VPCID, result.LocalVpcId) + ExpectEqual(t.Errorf, PAYMENT_TIMING_POSTPAID, result.PaymentTiming) + ExpectEqual(t.Errorf, tags, result.Tags) + + LocalIfID = result.LocalIfId +} + +func TestUpdatePeerConn(t *testing.T) { + args := &UpdatePeerConnArgs{ + LocalIfId: LocalIfID, + LocalIfName: "local-interface-update", + Description: "peer conn update", + } + err := VPC_CLIENT.UpdatePeerConn(PeerConnID, args) + ExpectEqual(t.Errorf, nil, err) + + result, err := VPC_CLIENT.GetPeerConnDetail(PeerConnID, PEERCONN_ROLE_INITIATOR) + ExpectEqual(t.Errorf, nil, err) + ExpectEqual(t.Errorf, "peer conn update", result.Description) + ExpectEqual(t.Errorf, "local-interface-update", result.LocalIfName) + ExpectEqual(t.Errorf, VPCID, result.LocalVpcId) + ExpectEqual(t.Errorf, PAYMENT_TIMING_POSTPAID, result.PaymentTiming) +} + +func TestAcceptPeerConnApply(t *testing.T) { + err := VPC_CLIENT.AcceptPeerConnApply(PeerConnID, getClientToken()) + if err == nil { + t.Errorf("Test AcceptPeerConnApply failed.") + } +} + +func TestRejectPeerConnReject(t *testing.T) { + err := VPC_CLIENT.RejectPeerConnApply(PeerConnID, getClientToken()) + if err == nil { + t.Errorf("Test RejectPeerConnApply failed.") + } +} + +func TestResizePeerConn(t *testing.T) { + args := &ResizePeerConnArgs{ + NewBandwidthInMbps: 20, + ClientToken: getClientToken(), + } + err := VPC_CLIENT.ResizePeerConn(PeerConnID, args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestRenewPeerConn(t *testing.T) { + args := &RenewPeerConnArgs{ + ClientToken: getClientToken(), + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_POSTPAID, + }, + } + err := VPC_CLIENT.RenewPeerConn(PeerConnID, args) + if err == nil { + t.Errorf("Test RenewPeerConn failed.") + } +} + +func TestOpenPeerConnSyncDNS(t *testing.T) { + args := &PeerConnSyncDNSArgs{ + Role: PEERCONN_ROLE_INITIATOR, + ClientToken: getClientToken(), + } + err := VPC_CLIENT.OpenPeerConnSyncDNS(PeerConnID, args) + ExpectEqual(t.Errorf, nil, err) + + // wait until dns sync completed + err = waitStateForPeerConn(PeerConnID, DNS_STATUS_OPEN) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClosePeerConnSyncDNS(t *testing.T) { + args := &PeerConnSyncDNSArgs{ + Role: PEERCONN_ROLE_INITIATOR, + ClientToken: getClientToken(), + } + err := VPC_CLIENT.ClosePeerConnSyncDNS(PeerConnID, args) + ExpectEqual(t.Errorf, nil, err) + + // wait until dns sync completed + err = waitStateForPeerConn(PeerConnID, DNS_STATUS_CLOSE) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeletePeerConn(t *testing.T) { + err := VPC_CLIENT.DeletePeerConn(PeerConnID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) + + err = waitStateForPeerConn(PeerConnID, PEERCONN_STATUS_DELETED) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeleteNatGateway(t *testing.T) { + err := VPC_CLIENT.DeleteNatGateway(NatID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) + + err = waitStateForNatGateway(NatID, NAT_STATUS_DELETED) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeleteAclRule(t *testing.T) { + err := VPC_CLIENT.DeleteAclRule(AclRuleID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeleteRouteRule(t *testing.T) { + err := VPC_CLIENT.DeleteRouteRule(RouteRuleID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeleteSubnet(t *testing.T) { + err := VPC_CLIENT.DeleteSubnet(SubnetID, getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestDeleteVPC(t *testing.T) { + // The vpc will be SUBNET_INUSE status after the subnet deleted in a period of time. + // So delete vpc by waitStateForVPC currently. + err := waitStateForVPC(VPCID) + ExpectEqual(t.Errorf, nil, err) + + err = waitStateForVPC(PeerVPCID) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} + +func waitStateForNatGateway(natID string, status NatStatusType) error { + ticker := time.NewTicker(2 * time.Second) + errChan := make(chan error, 1) + + go func() { + for { + select { + case <-ticker.C: + nat, err := VPC_CLIENT.GetNatGatewayDetail(natID) + if err != nil { + if !strings.Contains(err.Error(), "NoSuchNat") { + errChan <- err + return + } + nat = &NAT{Status: NAT_STATUS_DELETED} + } + if nat.Status == status { + errChan <- nil + return + } + } + } + }() + + select { + case <-time.After(10 * time.Minute): + return fmt.Errorf("Test nat gateway %s timeout.", natID) + case err := <-errChan: + return err + } +} + +func waitCuNumForNatGateway(natID string, cuNum int) error { + ticker := time.NewTicker(2 * time.Second) + errChan := make(chan error, 1) + + go func() { + for { + select { + case <-ticker.C: + nat, err := VPC_CLIENT.GetNatGatewayDetail(natID) + r, _ := json.Marshal(nat) + fmt.Println(string(r)) + fmt.Println(cuNum) + if err != nil { + if !strings.Contains(err.Error(), "NoSuchNat") { + errChan <- err + return + } + } + if nat.CuNum == cuNum { + errChan <- nil + return + } + } + } + }() + + select { + case <-time.After(10 * time.Minute): + return fmt.Errorf("Test nat gateway %s timeout.", natID) + case err := <-errChan: + return err + } +} + +func waitStateForEIP(eipAddress, status string) error { + ticker := time.NewTicker(2 * time.Second) + errChan := make(chan error, 1) + + go func() { + for { + select { + case <-ticker.C: + args := &eip.ListEipArgs{Eip: EIPAddress} + eips, err := EIP_CLIENT.ListEip(args) + if err != nil { + errChan <- err + return + } + if len(eips.EipList) == 1 && eips.EipList[0].Status == status { + errChan <- nil + return + } + } + } + }() + + select { + case <-time.After(10 * time.Minute): + return fmt.Errorf("Test eip %s timeout.", eipAddress) + case err := <-errChan: + return err + } +} + +func waitStateForVPC(vpcID string) error { + ticker := time.NewTicker(2 * time.Second) + errChan := make(chan error, 1) + + go func() { + for { + select { + case <-ticker.C: + err := VPC_CLIENT.DeleteVPC(vpcID, getClientToken()) + if err != nil && strings.Contains(err.Error(), "SUBNET_INUSE") { + continue + } + errChan <- err + return + } + } + }() + + select { + case <-time.After(10 * time.Minute): + return fmt.Errorf("Test VPC %s timeout.", vpcID) + case err := <-errChan: + return err + } +} + +func waitStateForPeerConn(peerConnID string, status interface{}) error { + ticker := time.NewTicker(2 * time.Second) + errChan := make(chan error, 1) + + go func() { + for { + select { + case <-ticker.C: + result, err := VPC_CLIENT.GetPeerConnDetail(peerConnID, PEERCONN_ROLE_INITIATOR) + if err != nil { + // not found error + if !strings.Contains(err.Error(), "EOF") { + errChan <- err + return + } + result = &PeerConn{Status: PEERCONN_STATUS_DELETED} + } + + switch status.(type) { + case PeerConnStatusType: + if result.Status == status { + errChan <- nil + return + } + case DnsStatusType: + if result.DnsStatus == status { + errChan <- nil + return + } + default: + errChan <- fmt.Errorf("The status %s type is not supported.", status) + return + } + } + } + }() + + select { + case <-time.After(10 * time.Minute): + return fmt.Errorf("Test peer conn %s timeout.", peerConnID) + case err := <-errChan: + return err + } +} + +func TestGetNetworkTopologyInfo(t *testing.T) { + args := &GetNetworkTopologyArgs{ + HostId: "", + HostIp: "", + } + result, err := VPC_CLIENT.GetNetworkTopologyInfo(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) +} + +func TestClient_BindDnatEips(t *testing.T) { + args := &BindDnatEipsArgs{ + ClientToken: getClientToken(), + DnatEips: []string{"100.88.14.243"}, + } + err := VPC_CLIENT.BindDnatEips("nat-bc39ugw5ry9z", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnBindDnatEips(t *testing.T) { + args := &UnBindDnatEipsArgs{ + ClientToken: getClientToken(), + DnatEips: []string{"100.88.14.243"}, + } + err := VPC_CLIENT.UnBindDnatEips("nat-bc39ugw5ry9z", args) + ExpectEqual(t.Errorf, nil, err) +} diff --git a/bce-sdk-go/services/vpc/ipv6gateway.go b/bce-sdk-go/services/vpc/ipv6gateway.go new file mode 100644 index 0000000..280a8a7 --- /dev/null +++ b/bce-sdk-go/services/vpc/ipv6gateway.go @@ -0,0 +1,295 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// ipv6gateway.go - the ipv6 gateway APIs definition supported by the VPC service + +package vpc + +import ( + "errors" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateIPv6Gateway - create a new ipv6 gateway +// +// PARAMS: +// - args: the arguments to create ipv6 gateway +// +// RETURNS: +// - *CreateIPv6GatewayResult: the id of the ipv6 gateway newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateIPv6Gateway(args *CreateIPv6GatewayArgs) (*CreateIPv6GatewayResult, error) { + if args == nil { + return nil, errors.New("The CreateIPv6GatewayArgs cannot be nil.") + } + + result := &CreateIPv6GatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpv6Gateway()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListIPv6Gateway - list all ipv6 gateways with the specific parameters +// +// PARAMS: +// - args: the arguments to list ipv6 gateways +// +// RETURNS: +// - *ListIPv6GatewayResult: the result of ipv6 gateway list +// - error: nil if success otherwise the specific error +func (c *Client) ListIPv6Gateway(args *ListIPv6GatewayArgs) (*ListIPv6GatewayResult, error) { + if args == nil { + return nil, errors.New("The ListIPv6GatewayArgs cannot be nil.") + } + + result := &ListIPv6GatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpv6Gateway()). + WithMethod(http.GET). + WithQueryParam("vpcId", args.VpcId). + WithResult(result). + Do() + + return result, err +} + +// DeleteIPv6Gateway - delete the specified ipv6 gateway +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - args: the arguments to delete ipv6 gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteIPv6Gateway(gatewayId string, args *DeleteIPv6GatewayArgs) error { + if args == nil { + return errors.New("The DeleteIPv6GatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)). + WithMethod(http.DELETE). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// ResizeIPv6Gateway - resize the specified ipv6 gateway +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - args: the arguments to resize ipv6 gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizeIPv6Gateway(gatewayId string, args *ResizeIPv6GatewayArgs) error { + if args == nil { + return errors.New("The ResizeIPv6GatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParam("resize", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// CreateIPv6GatewayEgressOnlyRule - create a new ipv6 gateway egress only rule +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - args: the arguments to create ipv6 gateway egress only rule +// +// RETURNS: +// - *CreateIPv6GatewayEgressOnlyRuleResult: the id of the ipv6 gateway egress only rule newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateIPv6GatewayEgressOnlyRule(gatewayId string, args *CreateIPv6GatewayEgressOnlyRuleArgs) ( + *CreateIPv6GatewayEgressOnlyRuleResult, error) { + if args == nil { + return nil, errors.New("The CreateIPv6GatewayEgressOnlyRuleArgs cannot be nil.") + } + + result := &CreateIPv6GatewayEgressOnlyRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/egressOnlyRule"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListIPv6GatewayEgressOnlyRule - list all ipv6 gateway egress only rules with the specific parameters +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - args: the arguments to list ipv6 gateway egress only rules +// +// RETURNS: +// - *ListIPv6GatewayEgressOnlyRuleResult: the result of ipv6 gateway egress only rule list +// - error: nil if success otherwise the specific error +func (c *Client) ListIPv6GatewayEgressOnlyRule(gatewayId string, args *ListIPv6GatewayEgressOnlyRuleArgs) (*ListIPv6GatewayEgressOnlyRuleResult, error) { + if args == nil { + return nil, errors.New("The ListIPv6GatewayEgressOnlyRuleArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListIPv6GatewayEgressOnlyRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/egressOnlyRule"). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// DeleteIPv6GatewayEgressOnlyRule - delete the specified ipv6 gateway egress only rule +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - egressOnlyRuleId: the id of the specific ipv6 gateway egress only rule +// - args: the arguments to delete ipv6 gateway egress only rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteIPv6GatewayEgressOnlyRule(gatewayId, egressOnlyRuleId string, args *DeleteIPv6GatewayEgressOnlyRuleArgs) error { + if args == nil { + return errors.New("The DeleteIPv6GatewayEgressOnlyRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/egressOnlyRule/"+egressOnlyRuleId). + WithMethod(http.DELETE). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// CreateIPv6GatewayRateLimitRule - create a new ipv6 gateway rate limit rule +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - args: the arguments to create ipv6 gateway rate limit rule +// +// RETURNS: +// - *CreateIPv6GatewayRateLimitRuleResult: the id of the ipv6 gateway rate limit rule newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateIPv6GatewayRateLimitRule(gatewayId string, args *CreateIPv6GatewayRateLimitRuleArgs) ( + *CreateIPv6GatewayRateLimitRuleResult, error) { + if args == nil { + return nil, errors.New("The CreateIPv6GatewayRateLimitRuleArgs cannot be nil.") + } + + result := &CreateIPv6GatewayRateLimitRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/rateLimitRule"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListIPv6GatewayRateLimitRule - list all ipv6 gateway rate limit rules with the specific parameters +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - args: the arguments to list ipv6 gateway rate limit rules +// +// RETURNS: +// - *ListIPv6GatewayRateLimitRuleResult: the result of ipv6 gateway rate limit rule list +// - error: nil if success otherwise the specific error +func (c *Client) ListIPv6GatewayRateLimitRule(gatewayId string, args *ListIPv6GatewayRateLimitRuleArgs) (*ListIPv6GatewayRateLimitRuleResult, error) { + if args == nil { + return nil, errors.New("The ListIPv6GatewayRateLimitRuleArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListIPv6GatewayRateLimitRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/rateLimitRule"). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// DeleteIPv6GatewayRateLimitRule - delete the specified ipv6 gateway rate limit rule +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - rateLimitRuleId: the id of the specific ipv6 gateway rate limit rule +// - args: the arguments to delete ipv6 gateway rate limit rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteIPv6GatewayRateLimitRule(gatewayId, rateLimitRuleId string, args *DeleteIPv6GatewayRateLimitRuleArgs) error { + if args == nil { + return errors.New("The DeleteIPv6GatewayRateLimitRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/rateLimitRule/"+rateLimitRuleId). + WithMethod(http.DELETE). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// UpdateIPv6GatewayRateLimitRule - update the specified ipv6 gateway rate limit rule +// +// PARAMS: +// - gatewayId: the id of the specific ipv6 gateway +// - rateLimitRuleId: the id of the specific ipv6 gateway rate limit rule +// - args: the arguments to update ipv6 gateway rate limit rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateIPv6GatewayRateLimitRule(gatewayId, rateLimitRuleId string, args *UpdateIPv6GatewayRateLimitRuleArgs) error { + if args == nil { + return errors.New("The UpdateIPv6GatewayRateLimitRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForIpv6GatewayId(gatewayId)+"/rateLimitRule/"+rateLimitRuleId). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} diff --git a/bce-sdk-go/services/vpc/model.go b/bce-sdk-go/services/vpc/model.go new file mode 100644 index 0000000..0547ae1 --- /dev/null +++ b/bce-sdk-go/services/vpc/model.go @@ -0,0 +1,995 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package vpc + +import ( + "github.com/baidubce/bce-sdk-go/model" +) + +type ( + SubnetType string + + NexthopType string + + AclRuleProtocolType string + + AclRuleDirectionType string + + AclRuleActionType string + + AclRulePortType string + + NatGatewaySpecType string + + PaymentTimingType string + + PeerConnRoleType string + + NatStatusType string + + PeerConnStatusType string + + DnsStatusType string +) + +const ( + SUBNET_TYPE_BCC SubnetType = "BCC" + SUBNET_TYPE_BCCNAT SubnetType = "BCC_NAT" + SUBNET_TYPE_BBC SubnetType = "BBC" + + NEXTHOP_TYPE_CUSTOM NexthopType = "custom" + NEXTHOP_TYPE_VPN NexthopType = "vpn" + NEXTHOP_TYPE_NAT NexthopType = "nat" + NEXTHOP_TYPE_ETGATEWAY NexthopType = "dcGateway" + NEXTHOP_TYPE_PEERCONN NexthopType = "peerConn" + NEXTHOP_TYPE_IPV6GATEWAY NexthopType = "ipv6gateway" + NEXTHOP_TYPE_ENIC NexthopType = "enic" + NEXTHOP_TYPE_HAVIP NexthopType = "havip" + + ACL_RULE_PROTOCOL_TCP AclRuleProtocolType = "tcp" + ACL_RULE_PROTOCOL_UDP AclRuleProtocolType = "udp" + ACL_RULE_PROTOCOL_ICMP AclRuleProtocolType = "icmp" + + ACL_RULE_DIRECTION_INGRESS AclRuleDirectionType = "ingress" + ACL_RULE_DIRECTION_EGRESS AclRuleDirectionType = "egress" + + ACL_RULE_ACTION_ALLOW AclRuleActionType = "allow" + ACL_RULE_ACTION_DENY AclRuleActionType = "deny" + + ACL_RULE_PORT_ALL AclRulePortType = "all" + + NAT_GATEWAY_SPEC_SMALL NatGatewaySpecType = "small" + NAT_GATEWAY_SPEC_MEDIUM NatGatewaySpecType = "medium" + NAT_GATEWAY_SPEC_LARGE NatGatewaySpecType = "large" + + PAYMENT_TIMING_PREPAID PaymentTimingType = "Prepaid" + PAYMENT_TIMING_POSTPAID PaymentTimingType = "Postpaid" + + PEERCONN_ROLE_INITIATOR PeerConnRoleType = "initiator" + PEERCONN_ROLE_ACCEPTOR PeerConnRoleType = "acceptor" + + NAT_STATUS_BUILDING NatStatusType = "building" + NAT_STATUS_UNCONFIGURED NatStatusType = "unconfigured" + NAT_STATUS_CONFIGURING NatStatusType = "configuring" + NAT_STATUS_ACTIVE NatStatusType = "active" + NAT_STATUS_STOPPING NatStatusType = "stopping" + NAT_STATUS_DOWN NatStatusType = "down" + NAT_STATUS_STARTING NatStatusType = "starting" + NAT_STATUS_DELETING NatStatusType = "deleting" + NAT_STATUS_DELETED NatStatusType = "deleted" + + PEERCONN_STATUS_CREATING PeerConnStatusType = "creating" + PEERCONN_STATUS_CONSULTING PeerConnStatusType = "consulting" + PEERCONN_STATUS_CONSULT_FAILED PeerConnStatusType = "consult_failed" + PEERCONN_STATUS_ACTIVE PeerConnStatusType = "active" + PEERCONN_STATUS_DOWN PeerConnStatusType = "down" + PEERCONN_STATUS_STARTING PeerConnStatusType = "starting" + PEERCONN_STATUS_STOPPING PeerConnStatusType = "stopping" + PEERCONN_STATUS_DELETING PeerConnStatusType = "deleting" + PEERCONN_STATUS_DELETED PeerConnStatusType = "deleted" + PEERCONN_STATUS_EXPIRED PeerConnStatusType = "expired" + PEERCONN_STATUS_ERROR PeerConnStatusType = "error" + PEERCONN_STATUS_UPDATING PeerConnStatusType = "updating" + + DNS_STATUS_CLOSE DnsStatusType = "close" + DNS_STATUS_WAIT DnsStatusType = "wait" + DNS_STATUS_SYNCING DnsStatusType = "syncing" + DNS_STATUS_OPEN DnsStatusType = "open" + DNS_STATUS_CLOSING DnsStatusType = "closing" +) + +// CreateVPCArgs defines the structure of the input parameters for the CreateVPC api +type CreateVPCArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + Cidr string `json:"cidr"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +// CreateVPCResult defines the structure of the output parameters for the CreateVPC api +type CreateVPCResult struct { + VPCID string `json:"vpcId"` +} + +// ListVPCArgs defines the structure of the input parameters for the ListVPC api +type ListVPCArgs struct { + Marker string + MaxKeys int + + // IsDefault is a string type, + // so we can identify if it has been setted when the value is false. + // NOTE: it can be only true or false. + IsDefault string +} + +// ListVPCResult defines the structure of the output parameters for the ListVPC api +type ListVPCResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + VPCs []VPC `json:"vpcs"` +} + +type VPC struct { + VPCID string `json:"vpcId"` + Name string `json:"name"` + Cidr string `json:"cidr"` + CreatedTime string `json:"createdTime"` + Description string `json:"description"` + IsDefault bool `json:"isDefault"` + SecondaryCidr []string `json:"secondaryCidr"` + Tags []model.TagModel `json:"tags"` +} + +// GetVPCDetailResult defines the structure of the output parameters for the GetVPCDetail api +type GetVPCDetailResult struct { + VPC ShowVPCModel `json:"vpc"` +} + +type ShowVPCModel struct { + VPCId string `json:"vpcId"` + Name string `json:"name"` + Cidr string `json:"cidr"` + CreatedTime string `json:"createdTime"` + Description string `json:"description"` + IsDefault bool `json:"isDefault"` + Subnets []Subnet `json:"subnets"` + SecondaryCidr []string `json:"secondaryCidr"` + Tags []model.TagModel `json:"tags"` +} + +type Subnet struct { + SubnetId string `json:"subnetId"` + Name string `json:"name"` + ZoneName string `json:"zoneName"` + Cidr string `json:"cidr"` + Ipv6Cidr string `json:"ipv6Cidr"` + VPCId string `json:"vpcId"` + SubnetType SubnetType `json:"subnetType"` + Description string `json:"description"` + CreatedTime string `json:"createdTime"` + AvailableIp int `json:"availableIp"` + Tags []model.TagModel `json:"tags"` +} + +// UpdateVPCArgs defines the structure of the input parameters for the UpdateVPC api +type UpdateVPCArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description,omitempty"` +} + +// CreateSubnetArgs defines the structure of the input parameters for the CreateSubnet api +type CreateSubnetArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + ZoneName string `json:"zoneName"` + Cidr string `json:"cidr"` + VpcId string `json:"vpcId"` + VpcSecondaryCidr string `json:"vpcSecondaryCidr,omitempty"` + SubnetType SubnetType `json:"subnetType,omitempty"` + Description string `json:"description,omitempty"` + EnableIpv6 bool `json:"enableIpv6,omitempty"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +// CreateSubnetResult defines the structure of the output parameters for the CreateSubnet api +type CreateSubnetResult struct { + SubnetId string `json:"subnetId"` +} + +// ListSubnetArgs defines the structure of the input parameters for the ListSubnet api +type ListSubnetArgs struct { + Marker string + MaxKeys int + VpcId string + ZoneName string + SubnetType SubnetType +} + +// ListSubnetResult defines the structure of the output parameters for the ListSubnet api +type ListSubnetResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + Subnets []Subnet `json:"subnets"` +} + +// GetSubnetDetailResult defines the structure of the output parameters for the GetSubnetDetail api +type GetSubnetDetailResult struct { + Subnet Subnet `json:"subnet"` +} + +// UpdateSubnetArgs defines the structure of the input parameters for the UpdateSubnet api +type UpdateSubnetArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + Description string `json:"description,omitempty"` + EnableIpv6 bool `json:"enableIpv6"` +} + +// CreateIpreserveArgs - arguments for creating a reserved CIDR +type CreateIpreserveArgs struct { + SubnetId string `json:"subnetId"` + IpCidr string `json:"ipCidr"` + IpVersion int32 `json:"ipVersion"` + Description string `json:"description"` + ClientToken string `json:"-"` +} + +// CreateIpreserveResult - result of creating a reserved CIDR +type CreateIpreserveResult struct { + IpReserveId string `json:"ipReserveId"` +} + +// ListIpeserveArgs - arguments for listing reserved CIDRs +type ListIpeserveArgs struct { + SubnetId string `json:"subnetId,omitempty"` + Marker string `json:"marker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type ipReserve struct { + IpReserveId string `json:"ipReserveId"` + SubnetId string `json:"subnetId"` + IpCidr string `json:"ipCidr"` + IpVersion int32 `json:"ipVersion"` + Description string `json:"description"` + CreatedTime string `json:"createdTime"` + UpdatedTime string `json:"updatedTime"` +} + +// ListIpeserveResult - result of listing reserved CIDRs +type ListIpeserveResult struct { + IpReserves []ipReserve `json:"ipReserves"` + Marker string `json:"marker,omitempty"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker,omitempty"` + MaxKeys int `json:"maxKeys,omitempty"` +} + +type RouteRule struct { + RouteRuleId string `json:"routeRuleId"` + RouteTableId string `json:"routeTableId"` + SourceAddress string `json:"sourceAddress"` + DestinationAddress string `json:"destinationAddress"` + NexthopId string `json:"nexthopId"` + NexthopType NexthopType `json:"nexthopType"` + Description string `json:"description"` + PathType string `json:"pathType"` +} + +// GetRouteTableResult defines the structure of the output parameters for the GetRouteTableDetail api +type GetRouteTableResult struct { + RouteTableId string `json:"routeTableId"` + VpcId string `json:"vpcId"` + RouteRules []RouteRule `json:"routeRules"` +} + +type GetRouteRuleArgs struct { + RouteTableId string `json:"routeTableId"` + VpcId string `json:"vpcId"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type GetRouteRuleResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RouteRules []RouteRule `json:"routeRules"` +} + +type UpdateRouteRuleArgs struct { + RouteRuleId string `json:"routeRuleId"` + ClientToken string `json:"-"` + SourceAddress string `json:"sourceAddress"` + DestinationAddress string `json:"destinationAddress"` + NexthopId string `json:"nexthopId,omitempty"` + Description string `json:"description,omitempty"` +} + +// CreateRouteRuleArgs defines the structure of the input parameters for the CreateRouteRule api +type CreateRouteRuleArgs struct { + ClientToken string `json:"-"` + RouteTableId string `json:"routeTableId"` + SourceAddress string `json:"sourceAddress"` + DestinationAddress string `json:"destinationAddress"` + NexthopId string `json:"nexthopId,omitempty"` + IpVersion string `json:"ipVersion,omitempty"` + NexthopType NexthopType `json:"nexthopType"` + NextHopList []NextHop `json:"nextHopList,omitempty"` + Description string `json:"description,omitempty"` +} + +type NextHop struct { + NexthopId string `json:"nexthopId"` + NexthopType NexthopType `json:"nexthopType"` + PathType string `json:"pathType"` +} + +// CreateRouteRuleResult defines the structure of the output parameters for the CreateRouteRule api +type CreateRouteRuleResult struct { + RouteRuleId string `json:"routeRuleId"` + RouteRuleIds []string `json:"routeRuleIds,omitempty"` +} + +// ListAclEntrysResult defines the structure of the output parameters for the ListAclEntrys api +type ListAclEntrysResult struct { + VpcId string `json:"vpcId"` + VpcName string `json:"vpcName"` + VpcCidr string `json:"vpcCidr"` + AclEntrys []AclEntry `json:"aclEntrys"` +} + +type AclEntry struct { + SubnetId string `json:"subnetId"` + SubnetName string `json:"subnetName"` + SubnetCidr string `json:"subnetCidr"` + AclRules []AclRule `json:"aclRules"` +} + +type AclRule struct { + Id string `json:"id"` + SubnetId string `json:"subnetId"` + Description string `json:"description"` + Protocol AclRuleProtocolType `json:"protocol"` + SourceIpAddress string `json:"sourceIpAddress"` + DestinationIpAddress string `json:"destinationIpAddress"` + SourcePort string `json:"sourcePort"` + DestinationPort string `json:"destinationPort"` + Position int `json:"position"` + Direction AclRuleDirectionType `json:"direction"` + Action AclRuleActionType `json:"action"` +} + +// CreateAclRuleArgs defines the structure of the input parameters for the CreateAclRule api +type CreateAclRuleArgs struct { + ClientToken string `json:"-"` + AclRules []AclRuleRequest `json:"aclRules"` +} + +type AclRuleRequest struct { + SubnetId string `json:"subnetId"` + Description string `json:"description,omitempty"` + Protocol AclRuleProtocolType `json:"protocol"` + SourceIpAddress string `json:"sourceIpAddress"` + DestinationIpAddress string `json:"destinationIpAddress"` + SourcePort string `json:"sourcePort"` + DestinationPort string `json:"destinationPort"` + Position int `json:"position"` + Direction AclRuleDirectionType `json:"direction"` + Action AclRuleActionType `json:"action"` +} + +// ListAclRulesArgs defines the structure of the input parameters for the ListAclRules api +type ListAclRulesArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + SubnetId string `json:"subnetId"` +} + +// ListAclRulesResult defines the structure of the output parameters for the ListAclRules api +type ListAclRulesResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + AclRules []AclRule `json:"aclRules"` +} + +// UpdateAclRuleArgs defines the structure of the input parameters for the UpdateAclRule api +type UpdateAclRuleArgs struct { + ClientToken string `json:"-"` + Description string `json:"description,omitempty"` + Protocol AclRuleProtocolType `json:"protocol,omitempty"` + SourceIpAddress string `json:"sourceIpAddress,omitempty"` + DestinationIpAddress string `json:"destinationIpAddress,omitempty"` + SourcePort string `json:"sourcePort,omitempty"` + DestinationPort string `json:"destinationPort,omitempty"` + Position int `json:"position,omitempty"` + Action AclRuleActionType `json:"action,omitempty"` +} + +// CreateNatGatewayArgs defines the structure of the input parameters for the CreateNatGateway api +type CreateNatGatewayArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + VpcId string `json:"vpcId"` + Spec NatGatewaySpecType `json:"spec"` + CuNum string `json:"cuNum,omitempty"` + Eips []string `json:"eips,omitempty"` + DnatEips []string `json:"dnatEips,omitempty"` + Billing *Billing `json:"billing"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +type ResizeNatGatewayArgs struct { + ClientToken string `json:"-"` + CuNum int `json:"cuNum"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} + +type Billing struct { + PaymentTiming PaymentTimingType `json:"paymentTiming,omitempty"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +// CreateNatGatewayResult defines the structure of the output parameters for the CreateNatGateway api +type CreateNatGatewayResult struct { + NatId string `json:"natId"` +} + +// ListNatGatewayArgs defines the structure of the input parameters for the ListNatGateway api +type ListNatGatewayArgs struct { + VpcId string + NatId string + Name string + Ip string + Marker string + MaxKeys int +} + +// ListNatGatewayResult defines the structure of the output parameters for the ListNatGateway api +type ListNatGatewayResult struct { + Nats []NAT `json:"nats"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +// NAT is the result for getNatGatewayDetail api. +type NAT struct { + Id string `json:"id"` + Name string `json:"name"` + VpcId string `json:"vpcId"` + Spec string `json:"spec,omitempty"` + CuNum int `json:"cuNum,omitempty"` + Status NatStatusType `json:"status"` + Eips []string `json:"eips"` + DnatEips []string `json:"dnatEips"` + PaymentTiming string `json:"paymentTiming"` + ExpiredTime string `json:"expiredTime"` + Tags []model.TagModel `json:"tags"` +} + +type SnatRule struct { + RuleId string `json:"ruleId"` + RuleName string `json:"ruleName"` + PublicIpAddresses []string `json:"publicIpsAddress"` + SourceCIDR string `json:"sourceCIDR"` + Status string `json:"status"` +} + +type SnatRuleArgs struct { + RuleName string `json:"ruleName,omitempty"` + SourceCIDR string `json:"sourceCIDR,omitempty"` + PublicIpAddresses []string `json:"publicIpsAddress,omitempty"` +} + +type DnatRuleArgs struct { + RuleName string `json:"ruleName,omitempty"` + PublicIpAddress string `json:"publicIpAddress,omitempty"` + PrivateIpAddress string `json:"privateIpAddress,omitempty"` + Protocol string `json:"protocol,omitempty"` + PublicPort string `json:"publicPort,omitempty"` + PrivatePort string `json:"privatePort,omitempty"` +} + +type DnatRule struct { + RuleId string `json:"ruleId"` + RuleName string `json:"ruleName"` + PublicIpAddress string `json:"publicIpAddress"` + PrivateIpAddress string `json:"privateIpAddress"` + Protocol string `json:"protocol"` + PublicPort int `json:"publicPort"` + PrivatePort int `json:"privatePort"` + Status string `json:"status"` +} + +// UpdateNatGatewayArgs defines the structure of the input parameters for the UpdateNatGateway api +type UpdateNatGatewayArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` +} + +// BindEipsArgs defines the structure of the input parameters for the BindEips api +type BindEipsArgs struct { + ClientToken string `json:"-"` + Eips []string `json:"eips"` +} + +// BindDnatEipsArgs defines the structure of the input parameters for the BindDnatEips api +type BindDnatEipsArgs struct { + ClientToken string `json:"-"` + DnatEips []string `json:"dnatEips"` +} + +// UnBindEipsArgs defines the structure of the input parameters for the UnBindEips api +type UnBindEipsArgs struct { + ClientToken string `json:"-"` + Eips []string `json:"eips"` +} + +// UnBindDnatEipsArgs defines the structure of the input parameters for the UnBindDnatEips api +type UnBindDnatEipsArgs struct { + ClientToken string `json:"-"` + DnatEips []string `json:"dnatEips"` +} + +// RenewNatGatewayArgs defines the structure of the input parameters for the RenewNatGateway api +type RenewNatGatewayArgs struct { + ClientToken string `json:"-"` + Billing *Billing `json:"billing"` +} + +type CreateNatGatewaySnatRuleArgs struct { + ClientToken string `json:"-"` + RuleName string `json:"ruleName,omitempty"` + SourceCIDR string `json:"sourceCIDR,omitempty"` + PublicIpAddresses []string `json:"publicIpsAddress,omitempty"` +} + +type BatchCreateNatGatewaySnatRuleArgs struct { + ClientToken string `json:"-"` + NatId string `json:"natId"` + SnatRules []SnatRuleArgs `json:"snatRules"` +} + +type UpdateNatGatewaySnatRuleArgs struct { + ClientToken string `json:"-"` + RuleName string `json:"ruleName,omitempty"` + SourceCIDR string `json:"sourceCIDR,omitempty"` + PublicIpAddresses []string `json:"publicIpsAddress,omitempty"` +} + +type ListNatGatewaySnatRuleArgs struct { + NatId string `json:"natId"` + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListNatGatewaySnatRulesResult struct { + Rules []SnatRule `json:"rules"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type CreateNatGatewaySnatRuleResult struct { + RuleId string `json:"ruleId"` +} + +type BatchCreateNatGatewaySnatRuleResult struct { + SnatRuleIds []string `json:"snatRuleIds"` +} + +type CreateNatGatewayDnatRuleArgs struct { + ClientToken string `json:"-"` + RuleName string `json:"ruleName,omitempty"` + PublicIpAddress string `json:"publicIpAddress,omitempty"` + PrivateIpAddress string `json:"privateIpAddress,omitempty"` + Protocol string `json:"protocol,omitempty"` + PublicPort string `json:"publicPort,omitempty"` + PrivatePort string `json:"privatePort,omitempty"` +} + +type BatchCreateNatGatewayDnatRuleArgs struct { + ClientToken string `json:"-"` + Rules []DnatRuleArgs `json:"rules"` +} + +type UpdateNatGatewayDnatRuleArgs struct { + ClientToken string `json:"-"` + RuleName string `json:"ruleName,omitempty"` + PublicIpAddress string `json:"publicIpAddress,omitempty"` + PrivateIpAddress string `json:"privateIpAddress,omitempty"` + Protocol string `json:"protocol,omitempty"` + PublicPort string `json:"publicPort,omitempty"` + PrivatePort string `json:"privatePort,omitempty"` +} + +type ListNatGatewaDnatRuleArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` +} + +type ListNatGatewayDnatRulesResult struct { + Rules []DnatRule `json:"rules"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type CreateNatGatewayDnatRuleResult struct { + RuleId string `json:"ruleId"` +} + +type BatchCreateNatGatewayDnatRuleResult struct { + RuleIds []string `json:"ruleIds"` +} + +// CreatePeerConnArgs defines the structure of the input parameters for the CreatePeerConn api +type CreatePeerConnArgs struct { + ClientToken string `json:"-"` + BandwidthInMbps int `json:"bandwidthInMbps"` + Description string `json:"description,omitempty"` + LocalIfName string `json:"localIfName,omitempty"` + LocalVpcId string `json:"localVpcId"` + PeerAccountId string `json:"peerAccountId,omitempty"` + PeerVpcId string `json:"peerVpcId"` + PeerRegion string `json:"peerRegion"` + PeerIfName string `json:"peerIfName,omitempty"` + Billing *Billing `json:"billing"` + Tags []model.TagModel `json:"tags,omitempty"` +} + +// CreatePeerConnResult defines the structure of the output parameters for the CreatePeerConn api +type CreatePeerConnResult struct { + PeerConnId string `json:"peerConnId"` +} + +// ListPeerConnsArgs defines the structure of the input parameters for the ListPeerConns api +type ListPeerConnsArgs struct { + VpcId string + Marker string + MaxKeys int +} + +// ListPeerConnsResult defines the structure of the output parameters for the ListPeerConns api +type ListPeerConnsResult struct { + PeerConns []PeerConn `json:"peerConns"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type PeerConn struct { + PeerConnId string `json:"peerConnId"` + Role PeerConnRoleType `json:"role"` + Status PeerConnStatusType `json:"status"` + BandwidthInMbps int `json:"bandwidthInMbps"` + Description string `json:"description"` + LocalIfId string `json:"localIfId"` + LocalIfName string `json:"localIfName"` + LocalVpcId string `json:"localVpcId"` + LocalRegion string `json:"localRegion"` + PeerVpcId string `json:"peerVpcId"` + PeerRegion string `json:"peerRegion"` + PeerAccountId string `json:"peerAccountId"` + PaymentTiming string `json:"paymentTiming"` + DnsStatus DnsStatusType `json:"dnsStatus"` + CreatedTime string `json:"createdTime"` + ExpiredTime string `json:"expiredTime"` + Tags []model.TagModel `json:"tags"` +} + +// UpdatePeerConnArgs defines the structure of the input parameters for the UpdatePeerConn api +type UpdatePeerConnArgs struct { + LocalIfId string `json:"localIfId"` + Description string `json:"description,omitempty"` + LocalIfName string `json:"localIfName,omitempty"` +} + +// ResizePeerConnArgs defines the structure of the input parameters for the ResizePeerConn api +type ResizePeerConnArgs struct { + NewBandwidthInMbps int `json:"newBandwidthInMbps"` + ClientToken string `json:"-"` +} + +// RenewPeerConnArgs defines the structure of the input parameters for the RenewPeerConn api +type RenewPeerConnArgs struct { + Billing *Billing `json:"billing"` + ClientToken string `json:"-"` +} + +// PeerConnSyncDNSArgs defines the structure of the input parameters for the PeerConnSyncDNS api +type PeerConnSyncDNSArgs struct { + Role PeerConnRoleType `json:"role"` + ClientToken string `json:"-"` +} + +/* +Get VpcPrivateIpAddressedInfo args + + VpcId:the vpc you want to query ips + PrivateIpAddresses:the privateIp list you want to query + PrivateIpRange:the range of privateIp .ex:"192.168.0.1-192.168.0.5" + pay attention that the size of PrivateIpAddresses and PrivateIpRange must less than 100 + if both PrivateIpAddresses and PrivateIpRange ,the PrivateIpRange will effect +*/ +type GetVpcPrivateIpArgs struct { + VpcId string `json:"vpcId"` + PrivateIpAddresses []string `json:"privateIpAddresses",omitempty` + PrivateIpRange string `json:"privateIpRange,omitempty"` +} + +type VpcPrivateIpAddress struct { + PrivateIpAddress string `json:"privateIpAddress"` + Cidr string `json:"cidr"` + PrivateIpAddressType string `json:"privateIpAddressType` + CreatedTime string `json:"createdTime"` +} + +// VpcPrivateIpAddressesResult defines the structure of the output parameters for the GetPrivateIpAddressInfo api +type VpcPrivateIpAddressesResult struct { + VpcPrivateIpAddresses []VpcPrivateIpAddress `json:"vpcPrivateIpAddresses"` +} + +/* +Get NetworkTopologyInfo args + + HostIp:the host ip of the network topology to be queried + HostId:the host id of the network topology to be queried + If both HostIp and HostId are passed in, the HostIp will effect (only need to pass in one of the two) +*/ +type GetNetworkTopologyArgs struct { + HostIp string `json:"hostIp,omitempty"` + HostId string `json:"hostId,omitempty"` +} + +type NetworkTopology struct { + ClusterName string `json:"clusterName"` + HostId string `json:"hostId"` + SwitchId string `json:"switchId"` + HostIp string `json:"hostIp"` + PodName string `json:"podName"` +} + +// NetworkTopologyResult defines the structure of the output parameters for the GetNetworkTopologyInfo api +type NetworkTopologyResult struct { + NetworkTopologies []NetworkTopology `json:"networkTopologies"` +} + +type CreateProbeArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Protocol string `json:"protocol"` + Frequency int `json:"frequency"` + DestIp string `json:"destIp"` + DestPort string `json:"destPort"` + SourceIps []string `json:"sourceIps"` + SourceIpNum int `json:"sourceIpNum,omitempty"` + Description string `json:"description,omitempty"` + Payload string `json:"payload,omitempty"` +} + +type CreateProbeResult struct { + ProbeId string `json:"probeId"` +} + +type UpdateProbeArgs struct { + ClientToken string `json:"-"` + Name string `json:"name,omitempty"` + Frequency int `json:"frequency,omitempty"` + DestIp string `json:"destIp,omitempty"` + DestPort string `json:"destPort,omitempty"` + Description string `json:"description,omitempty"` + Payload string `json:"payload,omitempty"` +} + +type UpdateProbeResult struct { + ProbeId string `json:"probeId"` +} + +type ListProbesArgs struct { + Marker string + MaxKeys int +} + +type Probe struct { + ProbeId string `json:"probeId"` + Name string `json:"name"` + VpcId string `json:"vpcId"` + SubnetId string `json:"subnetId"` + Protocol string `json:"protocol"` + Frequency int `json:"frequency"` + DestIp string `json:"destIp"` + DestPort string `json:"destPort"` + SourceIps []string `json:"sourceIps"` + SourceIpNum int `json:"sourceIpNum,omitempty"` + Description string `json:"description,omitempty"` + Payload string `json:"payload,omitempty"` +} + +type ListProbesResult struct { + Probes []Probe `json:"probes"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +type GetProbeDetailResult struct { + Probe Probe `json:"probes"` +} + +// CreateIPv6GatewayArgs defines the structure of the input parameters for the CreateIPv6Gateway api +type CreateIPv6GatewayArgs struct { + ClientToken string `json:"-"` + Name string `json:"name"` + VpcId string `json:"vpcId"` + BandwidthInMbps int `json:"bandwidthInMbps"` + Billing *Billing `json:"billing"` +} + +// CreateIPv6GatewayResult defines the structure of the output parameters for the CreateIPv6Gateway api +type CreateIPv6GatewayResult struct { + GatewayId string `json:"gatewayId"` +} + +// ListIPv6GatewayArgs defines the structure of the input parameters for the ListIPv6Gateway api +type ListIPv6GatewayArgs struct { + VpcId string `json:"vpcId"` +} + +// DeleteIPv6GatewayArgs defines the structure of the input parameters for the DeleteIPv6Gateway api +type DeleteIPv6GatewayArgs struct { + ClientToken string `json:"-"` +} + +// ListIPv6GatewayResult defines the structure of the output parameters for the ListIPv6Gateway api +type ListIPv6GatewayResult struct { + GatewayId string `json:"gatewayId"` + Name string `json:"name"` + BandwidthInMbps int `json:"bandwidthInMbps"` + VpcId string `json:"vpcId"` + EgressOnlyRules []EgressOnlyRule `json:"egressOnlyRules"` + RateLimitRules []RateLimitRule `json:"rateLimitRules"` +} + +type EgressOnlyRule struct { + EgressOnlyRuleId string `json:"egressOnlyRuleId"` + Cidr string `json:"cidr"` +} + +type RateLimitRule struct { + RateLimitRuleId string `json:"rateLimitRuleId"` + IPv6Address string `json:"ipv6Address"` + IngressBandwidthInMbps int `json:"ingressBandwidthInMbps"` + EgressBandwidthInMbps int `json:"egressBandwidthInMbps"` +} + +// ResizeIPv6GatewayArgs defines the structure of the input parameters for the ResizeIPv6Gateway api +type ResizeIPv6GatewayArgs struct { + ClientToken string `json:"-"` + BandwidthInMbps int `json:"bandwidthInMbps"` +} + +// CreateIPv6GatewayEgressOnlyRuleArgs defines the structure of the input parameters for the CreateIPv6GatewayEgressOnlyRule api +type CreateIPv6GatewayEgressOnlyRuleArgs struct { + ClientToken string `json:"-"` + Cidr string `json:"cidr"` +} + +// CreateIPv6GatewayEgressOnlyRuleResult defines the structure of the output parameters for the CreateIPv6GatewayEgressOnlyRule api +type CreateIPv6GatewayEgressOnlyRuleResult struct { + EgressOnlyRuleId string `json:"egressOnlyRuleId"` +} + +// ListIPv6GatewayEgressOnlyRuleArgs defines the structure of the input parameters for the ListIPv6GatewayEgressOnlyRule api +type ListIPv6GatewayEgressOnlyRuleArgs struct { + Marker string + MaxKeys int +} + +// DeleteIPv6GatewayEgressOnlyRuleArgs defines the structure of the input parameters for the DeleteIPv6GatewayEgressOnlyRule api +type DeleteIPv6GatewayEgressOnlyRuleArgs struct { + ClientToken string `json:"-"` +} + +// ListIPv6GatewayEgressOnlyRuleResult defines the structure of the output parameters for the ListIPv6GatewayEgressOnlyRule api +type ListIPv6GatewayEgressOnlyRuleResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + EgressOnlyRules []EgressOnlyRule `json:"egressOnlyRules"` +} + +// CreateIPv6GatewayRateLimitRuleArgs defines the structure of the input parameters for the CreateIPv6GatewayRateLimitRule api +type CreateIPv6GatewayRateLimitRuleArgs struct { + ClientToken string `json:"-"` + IPv6Address string `json:"ipv6Address"` + IngressBandwidthInMbps int `json:"ingressBandwidthInMbps"` + EgressBandwidthInMbps int `json:"egressBandwidthInMbps"` +} + +// CreateIPv6GatewayRateLimitRuleResult defines the structure of the output parameters for the CreateIPv6GatewayRateLimitRule api +type CreateIPv6GatewayRateLimitRuleResult struct { + RateLimitRuleId string `json:"rateLimitRuleId"` +} + +// ListIPv6GatewayRateLimitRuleArgs defines the structure of the input parameters for the ListIPv6GatewayRateLimitRule api +type ListIPv6GatewayRateLimitRuleArgs struct { + Marker string + MaxKeys int +} + +// DeleteIPv6GatewayRateLimitRuleArgs defines the structure of the input parameters for the DeleteIPv6GatewayRateLimitRule api +type DeleteIPv6GatewayRateLimitRuleArgs struct { + ClientToken string `json:"-"` +} + +// ListIPv6GatewayRateLimitRuleResult defines the structure of the output parameters for the ListIPv6GatewayRateLimitRule api +type ListIPv6GatewayRateLimitRuleResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + RateLimitRules []RateLimitRule `json:"rateLimitRules"` +} + +// UpdateIPv6GatewayRateLimitRuleArgs defines the structure of the input parameters for the UpdateIPv6GatewayRateLimitRule api +type UpdateIPv6GatewayRateLimitRuleArgs struct { + ClientToken string `json:"-"` + IngressBandwidthInMbps int `json:"ingressBandwidthInMbps"` + EgressBandwidthInMbps int `json:"egressBandwidthInMbps"` +} + +type CreateVpcDhcpArgs struct { + ClientToken string `json:"-"` + DomainNameServers string `json:"domainNameServers"` +} + +type UpdateVpcDhcpArgs struct { + ClientToken string `json:"-"` + DomainNameServers string `json:"domainNameServers"` +} + +type VpcDhcpInfo struct { + VPCID string `json:"vpcId"` + DhcpOptions DhcpOptions `json:"dhcpOptions"` +} + +type DhcpOptions struct { + DomainNameServers string `json:"domainNameServers"` +} diff --git a/bce-sdk-go/services/vpc/nat.go b/bce-sdk-go/services/vpc/nat.go new file mode 100644 index 0000000..cb1f030 --- /dev/null +++ b/bce-sdk-go/services/vpc/nat.go @@ -0,0 +1,412 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// nat.go - the nat gateway APIs definition supported by the VPC service + +package vpc + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateNatGateway - create a new nat gateway +// +// PARAMS: +// - args: the arguments to create nat gateway +// +// RETURNS: +// - *CreateNatGatewayResult: the id of the nat gateway newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateNatGateway(args *CreateNatGatewayArgs) (*CreateNatGatewayResult, error) { + if args == nil { + return nil, fmt.Errorf("The createNatGatewayArgs cannot be nil.") + } + + result := &CreateNatGatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNat()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListNatGateway - list all nat gateways with the specific parameters +// +// PARAMS: +// - args: the arguments to list nat gateways +// +// RETURNS: +// - *ListNatGatewayResult: the result of nat gateway list +// - error: nil if success otherwise the specific error +func (c *Client) ListNatGateway(args *ListNatGatewayArgs) (*ListNatGatewayResult, error) { + if args == nil { + return nil, fmt.Errorf("The listNatGatewayArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListNatGatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNat()). + WithMethod(http.GET). + WithQueryParam("vpcId", args.VpcId). + WithQueryParamFilter("natId", args.NatId). + WithQueryParamFilter("name", args.Name). + WithQueryParamFilter("ip", args.Ip). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetNatGatewayDetail - get details of the specific nat gateway +// +// PARAMS: +// - natId: the id of the specified nat +// +// RETURNS: +// - *NAT: the result of the specific nat gateway details +// - error: nil if success otherwise the specific error +func (c *Client) GetNatGatewayDetail(natId string) (*NAT, error) { + result := &NAT{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// UpdateNatGateway - update the specified nat gateway +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - args: the arguments to update nat gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateNatGateway(natId string, args *UpdateNatGatewayArgs) error { + if args == nil { + return fmt.Errorf("The updateNatGatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// BindEips - bind eips for the specific nat gateway +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - args: the arguments to bind eips +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindEips(natId string, args *BindEipsArgs) error { + if args == nil { + return fmt.Errorf("The bindEipArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("bind", ""). + Do() +} + +// UnBindEips - unbind eips for the specific nat gateway +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - args: the arguments to unbind eips +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindEips(natId string, args *UnBindEipsArgs) error { + if args == nil { + return fmt.Errorf("The unBindEipArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("unbind", ""). + Do() +} + +// BindDnatEips - bind dnatEips for the specific nat gateway +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - args: the arguments to bind dnatEips +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindDnatEips(natId string, args *BindDnatEipsArgs) error { + if args == nil { + return fmt.Errorf("The bindDnatEipsArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("bind", ""). + Do() +} + +// UnBindDnatEips - unbind dnatEips for the specific nat gateway +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - args: the arguments to unbind dnatEips +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindDnatEips(natId string, args *UnBindDnatEipsArgs) error { + if args == nil { + return fmt.Errorf("the unBindDnatEipArgs cannot be nil") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("unbind", ""). + Do() +} + +// DeleteNatGateway - delete the specific nat gateway +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteNatGateway(natId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// RenewNatGateway - renew nat gateway with the specific parameters +// +// PARAMS: +// - natId: the id of the specific nat gateway +// - args: the arguments to renew nat gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenewNatGateway(natId string, args *RenewNatGatewayArgs) error { + if args == nil { + return fmt.Errorf("The renewNatGatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("purchaseReserved", ""). + Do() +} + +func (c *Client) CreateNatGatewaySnatRule(natId string, args *CreateNatGatewaySnatRuleArgs) (*CreateNatGatewaySnatRuleResult, error) { + if args == nil { + return nil, fmt.Errorf("The CreateNatGatewaySnatRuleArgs cannot be nil.") + } + + result := &CreateNatGatewaySnatRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/snatRule"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) BatchCreateNatGatewaySnatRule(args *BatchCreateNatGatewaySnatRuleArgs) (*BatchCreateNatGatewaySnatRuleResult, error) { + if args == nil { + return nil, fmt.Errorf("The BatchCreateNatGatewaySnatRuleArgs cannot be nil.") + } + + result := &BatchCreateNatGatewaySnatRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNat()+"/snatRule/batchCreate"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) DeleteNatGatewaySnatRule(natId string, snatRuleId string, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/snatRule/"+snatRuleId). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +func (c *Client) UpdateNatGatewaySnatRule(natId string, snatRuleId string, args *UpdateNatGatewaySnatRuleArgs) error { + if args == nil { + return fmt.Errorf("The UpdateNatGatewaySnatRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/snatRule/"+snatRuleId). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +func (c *Client) ListNatGatewaySnatRules(args *ListNatGatewaySnatRuleArgs) (*ListNatGatewaySnatRulesResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListNatGatewaySnatRuleArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListNatGatewaySnatRulesResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNatId(args.NatId)+"/snatRule"). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) CreateNatGatewayDnatRule(natId string, args *CreateNatGatewayDnatRuleArgs) (*CreateNatGatewayDnatRuleResult, error) { + if args == nil { + return nil, fmt.Errorf("The CreateNatGatewayDnatRuleArgs cannot be nil.") + } + + result := &CreateNatGatewayDnatRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/dnatRule"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) BatchCreateNatGatewayDnatRule(natId string, args *BatchCreateNatGatewayDnatRuleArgs) (*BatchCreateNatGatewayDnatRuleResult, error) { + if args == nil { + return nil, fmt.Errorf("The BatchCreateNatGatewayDnatRuleArgs cannot be nil.") + } + + result := &BatchCreateNatGatewayDnatRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/dnatRule/batchCreate"). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) DeleteNatGatewayDnatRule(natId string, dnatRuleId string, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/dnatRule/"+dnatRuleId). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +func (c *Client) UpdateNatGatewayDnatRule(natId string, dnatRuleId string, args *UpdateNatGatewayDnatRuleArgs) error { + if args == nil { + return fmt.Errorf("The UpdateNatGatewayDnatRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/dnatRule/"+dnatRuleId). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +func (c *Client) ListNatGatewayDnatRules(natId string, args *ListNatGatewaDnatRuleArgs) (*ListNatGatewayDnatRulesResult, error) { + if args == nil { + return nil, fmt.Errorf("The ListNatGatewaDnatRuleArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListNatGatewayDnatRulesResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)+"/dnatRule"). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +func (c *Client) ResizeNatGateway(natId string, args *ResizeNatGatewayArgs) error { + if args == nil { + return fmt.Errorf("The ResizeNatGatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForNatId(natId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("resize", " "). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} diff --git a/bce-sdk-go/services/vpc/peerconn.go b/bce-sdk-go/services/vpc/peerconn.go new file mode 100644 index 0000000..d6ff381 --- /dev/null +++ b/bce-sdk-go/services/vpc/peerconn.go @@ -0,0 +1,259 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// peerconn.go - the peer connection APIs definition supported by the VPC service + +package vpc + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreatePeerConn - create a new peer connection with the specific parameters +// +// PARAMS: +// - args: the arguments to create peer connection +// +// RETURNS: +// - *CreatePeerConnResult: the id of peer connection newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreatePeerConn(args *CreatePeerConnArgs) (*CreatePeerConnResult, error) { + if args == nil { + return nil, fmt.Errorf("The createPeerConnArgs cannot be nil.") + } + + result := &CreatePeerConnResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForPeerConn()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListPeerConn - list all peer connections with the specific parameters +// +// PARAMS: +// - args: the arguments to list peer connections +// +// RETURNS: +// - *ListPeerConnsResult: the result of the peer connection list +// - error: nil if success otherwise the specific error +func (c *Client) ListPeerConn(args *ListPeerConnsArgs) (*ListPeerConnsResult, error) { + if args == nil { + args = &ListPeerConnsArgs{} + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListPeerConnsResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForPeerConn()). + WithMethod(http.GET). + WithQueryParamFilter("vpcId", args.VpcId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetPeerConnDetail - get details for the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - role: the role of the specific peer connection, which can be initiator or acceptor +// +// RETURNS: +// - *PeerConn: the result of the specfic peer connection details +// - error: nil if success otherwise the specific error +func (c *Client) GetPeerConnDetail(peerConnId string, role PeerConnRoleType) (*PeerConn, error) { + result := &PeerConn{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.GET). + WithQueryParamFilter("role", string(role)). + WithResult(result). + Do() + + return result, err +} + +// UpdatePeerConn - update the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - args: the arguments to update the specific peer connection +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdatePeerConn(peerConnId string, args *UpdatePeerConnArgs) error { + if args == nil { + return fmt.Errorf("The updatePeerConnArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithBody(args). + Do() +} + +// AcceptPeerConnApply - accept the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) AcceptPeerConnApply(peerConnId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithQueryParam("accept", ""). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// RejectPeerConnApply - reject the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RejectPeerConnApply(peerConnId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithQueryParam("reject", ""). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// DeletePeerConn - delete the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeletePeerConn(peerConnId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// ResizePeerConn - resize the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - args: the arguments to resize the peer connection +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ResizePeerConn(peerConnId string, args *ResizePeerConnArgs) error { + if args == nil { + return fmt.Errorf("The resizePeerConnArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParam("resize", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// RenewPeerConn - renew the specific peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - args: the arguments to renew the peer connection +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenewPeerConn(peerConnId string, args *RenewPeerConnArgs) error { + if args == nil { + return fmt.Errorf("The renewPeerConnArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParam("purchaseReserved", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// OpenPeerConnSyncDNS - open the dns synchronization for the given peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - args: the arguments to open dns synchronization +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) OpenPeerConnSyncDNS(peerConnId string, args *PeerConnSyncDNSArgs) error { + if args == nil { + return fmt.Errorf("The peerConnSyncDNS cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithQueryParam("open", ""). + WithQueryParamFilter("role", string(args.Role)). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} + +// ClosePeerConnSyncDNS - close the dns synchronization for the given peer connection +// +// PARAMS: +// - peerConnId: the id of the specific peer connection +// - args: the arguments to close dns synchronization +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) ClosePeerConnSyncDNS(peerConnId string, args *PeerConnSyncDNSArgs) error { + if args == nil { + return fmt.Errorf("The peerConnSyncDNS cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForPeerConnId(peerConnId)). + WithMethod(http.PUT). + WithQueryParam("close", ""). + WithQueryParamFilter("role", string(args.Role)). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} diff --git a/bce-sdk-go/services/vpc/probe.go b/bce-sdk-go/services/vpc/probe.go new file mode 100644 index 0000000..beafa5f --- /dev/null +++ b/bce-sdk-go/services/vpc/probe.go @@ -0,0 +1,145 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// probe.go - the probe APIs definition supported by the VPC service + +package vpc + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateProbe - create a new probe with the specified parameters +// +// PARAMS: +// - args: the arguments to create a probe +// +// RETURNS: +// - *CreateProbeResult: the ID of the probe newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateProbe(args *CreateProbeArgs) (*CreateProbeResult, error) { + if args == nil { + return nil, fmt.Errorf("CreateProbeResult cannot be nil.") + } + result := &CreateProbeResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForProbe()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// UpdateProbe - update a probe with the specified parameters +// +// PARAMS: +// - probeId: the ID of the probe to be updated +// - args: the arguments to update the probe +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateProbe(probeId string, args *UpdateProbeArgs) error { + if probeId == "" { + return fmt.Errorf("The probeId cannot be blank.") + } + if args == nil { + return fmt.Errorf("UpdateProbeArgs cannot be nil.") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForProbeId(probeId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("modifyAttribute", ""). + Do() +} + +// DeleteProbe - delete a probe +// PARAMS: +// - probeId: the ID of the probe to be deleted +// - clientToken: the client token of the request +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteProbe(probeId string, clientToken string) error { + if probeId == "" { + return fmt.Errorf("The probeId cannot be blank.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForProbeId(probeId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// ListProbes - list all probes of the user +// +// PARAMS: +// - args: the arguments to list probes +// +// RETURNS: +// - *ListProbesResult: the infromation of all probes +// - error: nil if success otherwise the specific error +func (c *Client) ListProbes(args *ListProbesArgs) (*ListProbesResult, error) { + if args == nil { + args = &ListProbesArgs{} + } + if args.MaxKeys < 0 || args.MaxKeys > 1000 { + return nil, fmt.Errorf("The field maxKeys is out of range [0, 1000]") + } else if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListProbesResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForProbe()). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetProbeDetail - get details of a probe +// +// PARAMS: +// - probeId: the ID of the probe to get +// +// RETURNS: +// - *Probe: the infromation of the probe +// - error: nil if success otherwise the specific error +func (c *Client) GetProbeDetail(probeId string) (*Probe, error) { + if probeId == "" { + return nil, fmt.Errorf("The probeId cannot be blank.") + } + + result := &Probe{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForProbeId(probeId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/vpc/route.go b/bce-sdk-go/services/vpc/route.go new file mode 100644 index 0000000..15251d1 --- /dev/null +++ b/bce-sdk-go/services/vpc/route.go @@ -0,0 +1,166 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// route.go - the route APIs definition supported by the VPC service + +package vpc + +import ( + "errors" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// GetRouteTableDetail - get details of the given routeTableId or vpcId +// +// PARAMS: +// - routeTableId: the id of the specific route table +// - vpcId: the id of the specific VPC +// +// RETURNS: +// - *GetRouteTableResult: the result of route table details +// - error: nil if success otherwise the specific error +func (c *Client) GetRouteTableDetail(routeTableId, vpcId string) (*GetRouteTableResult, error) { + if routeTableId == "" && vpcId == "" { + return nil, errors.New("The routeTableId and vpcId cannot be blank at the same time.") + } + + result := &GetRouteTableResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForRouteTable()). + WithMethod(http.GET). + WithQueryParamFilter("routeTableId", routeTableId). + WithQueryParamFilter("vpcId", vpcId). + WithResult(result). + Do() + + return result, err +} + +// CreateRouteRule - create a new route rule with the given parameters +// +// PARAMS: +// - args: the arguments to create route rule +// +// RETURNS: +// - *CreateRouteRuleResult: the id of the route rule newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateRouteRule(args *CreateRouteRuleArgs) (*CreateRouteRuleResult, error) { + if args == nil { + return nil, errors.New("CreateRouteRuleArgs cannot be nil.") + } + + result := &CreateRouteRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForRouteRule()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// DeleteRouteRule - delete the given routing rule +// +// PARAMS: +// - routeRuleId: the id of the specific routing rule +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteRouteRule(routeRuleId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForRouteRuleId(routeRuleId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// switchRoute +// +// PARAMS: +// - routeRuleId: 主路由规则ID +// - clientToken: the idempotent token, 可选 +// - action: 切换路由规则的动作,可选值:switchRouteHA +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) SwitchRoute(routeRuleId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForRouteRuleId(routeRuleId)). + WithMethod(http.PUT). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParamFilter("action", "switchRouteHA"). + Do() +} + +// GetRouteTableDetail - get details of the given routeTableId or vpcId +// +// PARAMS: +// - routeTableId: the id of the specific route table +// - vpcId: the id of the specific VPC +// +// RETURNS: +// - *GetRouteTableResult: the result of route table details +// - error: nil if success otherwise the specific error +func (c *Client) GetRouteRuleDetail(args *GetRouteRuleArgs) (*GetRouteRuleResult, error) { + if args.RouteTableId == "" && args.VpcId == "" { + return nil, errors.New("The RouteTableId and VpcId cannot be blank at the same time.") + } + + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &GetRouteRuleResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForRouteRule()). + WithMethod(http.GET). + WithQueryParamFilter("routeTableId", args.RouteTableId). + WithQueryParamFilter("vpcId", args.VpcId). + WithQueryParamFilter("marker", args.Marker). + WithQueryParam("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// UpdateRouteRule - update the given route rule +// +// PARAMS: +// - routeRuleId: the id of the specific route rule +// - args: the arguments to update route rule +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateRouteRule(args *UpdateRouteRuleArgs) error { + if args.RouteRuleId == "" { + return errors.New("The RouteRuleId cannot be blank.") + } + if args == nil { + return errors.New("The UpdateRouteRuleArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForRouteRuleId(args.RouteRuleId)). + WithMethod(http.PUT). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + Do() +} diff --git a/bce-sdk-go/services/vpc/subnet.go b/bce-sdk-go/services/vpc/subnet.go new file mode 100644 index 0000000..d5f2c58 --- /dev/null +++ b/bce-sdk-go/services/vpc/subnet.go @@ -0,0 +1,236 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// subnet.go - the subnet APIs definition supported by the VPC service + +package vpc + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateSubnet - create a new subnet with the specified parameters +// +// PARAMS: +// - args: the arguments to create subnet +// +// RETURNS: +// - *CreateSubnetResult: the ID of the subnet newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateSubnet(args *CreateSubnetArgs) (*CreateSubnetResult, error) { + if args == nil { + return nil, fmt.Errorf("CreateSubnetArgs cannot be nil.") + } + + result := &CreateSubnetResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForSubnet()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListSubnets - list all subnets with the specified parameters +// +// PARAMS: +// - args: the arguments to list subnets +// - : +// +// RETURNS: +// - *ListSubnetResult: the result of all subnets +// - error: nil if success otherwise the specific error +func (c *Client) ListSubnets(args *ListSubnetArgs) (*ListSubnetResult, error) { + if args == nil { + args = &ListSubnetArgs{} + } + if args.MaxKeys < 0 || args.MaxKeys > 1000 { + return nil, fmt.Errorf("The field maxKeys is out of range [0, 1000]") + } else if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListSubnetResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForSubnet()). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("vpcId", args.VpcId). + WithQueryParamFilter("zoneName", args.ZoneName). + WithQueryParamFilter("subnetType", string(args.SubnetType)). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// GetSubnetDetail - get details of the given subnet +// +// PARAMS: +// - subnetId: the id of the specified subnet +// +// RETURNS: +// - *GetSubnetDetailResult: the result of the given subnet details +// - error: nil if success otherwise the specific error +func (c *Client) GetSubnetDetail(subnetId string) (*GetSubnetDetailResult, error) { + if subnetId == "" { + return nil, fmt.Errorf("The subnetId cannot be blank.") + } + + result := &GetSubnetDetailResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForSubnetId(subnetId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// UpdateSubnet - update the given subnet +// +// PARAMS: +// - subnetId: the id of the given subnet +// - args: the arguments to update subnet +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSubnet(subnetId string, args *UpdateSubnetArgs) error { + if subnetId == "" { + return fmt.Errorf("The subnetId cannot be blank.") + } + if args == nil { + return fmt.Errorf("The UpdateSubnetArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForSubnetId(subnetId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("modifyAttribute", ""). + Do() +} + +// DeleteSubnet - delete the given subnet +// +// PARAMS: +// - subnetId: the id of the specified subnet +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSubnet(subnetId string, clientToken string) error { + if subnetId == "" { + return fmt.Errorf("The subnetId cannot be blank.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForSubnetId(subnetId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// CreateReservedCIDR - delete the given ReservedCIDR +// +// PARAMS: +// - ipReserveId: the id of the reserved subnet +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateIpreserve(args *CreateIpreserveArgs) (*CreateIpreserveResult, error) { + if args.SubnetId == "" { + return nil, fmt.Errorf("SubnetId cannot be nil.") + } + + if args.IpCidr == "" { + return nil, fmt.Errorf("ipCidr cannot be blank.") + } + + if args.IpVersion != 4 && args.IpVersion != 6 { + return nil, fmt.Errorf("wrong ipVersion.") + } + + result := &CreateIpreserveResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpreserve()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// DeleteIpreserve - delete the given ReservedCIDR +// +// PARAMS: +// - ipReserveId: the id of the reserved subnet +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteIpreserve(ipReserveId, clientToken string) error { + if ipReserveId == "" { + return fmt.Errorf("The ipReserveId cannot be blank.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForDeleteIpreserve(ipReserveId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// ListIpreserve - list all reserved CIDRs with the specified parameters +// +// PARAMS: +// - args: the arguments to list reserved CIDRs +// +// RETURNS: +// - *ListReservedCIDRResult: the result of all reserved CIDRs +// - error: nil if success otherwise the specific error +func (c *Client) ListIpreserve(args *ListIpeserveArgs) (*ListIpeserveResult, error) { + if args == nil { + args = &ListIpeserveArgs{} + } + if args.MaxKeys < 0 || args.MaxKeys > 1000 { + return nil, fmt.Errorf("The field maxKeys is out of range [0, 1000]") + } else if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListIpeserveResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForIpreserve()). + WithMethod(http.GET). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("subnetId", args.SubnetId). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} diff --git a/bce-sdk-go/services/vpc/vpc.go b/bce-sdk-go/services/vpc/vpc.go new file mode 100644 index 0000000..025ee15 --- /dev/null +++ b/bce-sdk-go/services/vpc/vpc.go @@ -0,0 +1,240 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// vpc.go - the vpc APIs definition supported by the VPC service + +package vpc + +import ( + "fmt" + "strconv" + + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" +) + +// CreateVPC - create a new VPC with the specified parameters +// +// PARAMS: +// - args: the arguments to create VPC +// +// RETURNS: +// - *CreateVPCResult: the id of the VPC newly created +// - error: nil if success otherwise the specific error +func (c *Client) CreateVPC(args *CreateVPCArgs) (*CreateVPCResult, error) { + if args == nil { + return nil, fmt.Errorf("The createVPCArgs cannot be nil.") + } + + result := &CreateVPCResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPC()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// ListVPC - list all VPCs with the specified parameters +// +// PARAMS: +// - args: the arguments to list VPCs +// +// RETURNS: +// - *ListVPCResult: the result of all VPCs +// - error: nil if success otherwise the specific error +func (c *Client) ListVPC(args *ListVPCArgs) (*ListVPCResult, error) { + if args == nil { + args = &ListVPCArgs{} + } + if args.IsDefault != "" && args.IsDefault != "true" && args.IsDefault != "false" { + return nil, fmt.Errorf("The field isDefault can only be true or false.") + } + if args.MaxKeys < 0 || args.MaxKeys > 1000 { + return nil, fmt.Errorf("The field maxKeys is out of range [0, 1000]") + } + + result := &ListVPCResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForVPC()). + WithMethod(http.GET). + WithResult(result). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("isDefault", args.IsDefault) + if args.MaxKeys != 0 { + builder.WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)) + } + err := builder.Do() + + return result, err +} + +// GetVPCDetail - get details of the specified VPC +// +// PARAMS: +// - vpcId: the VPC id +// +// RETURNS: +// - *GetVPCDetailResult: the details of the specified VPC +// - error: nil if success otherwise the specific error +func (c *Client) GetVPCDetail(vpcId string) (*GetVPCDetailResult, error) { + result := &GetVPCDetailResult{} + + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(vpcId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// UpdateVPC - update a specified VPC +// +// PARAMS: +// - vpcId: the id of the specified VPC +// - updateVPCArgs: the arguments to udpate VPC +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateVPC(vpcId string, updateVPCArgs *UpdateVPCArgs) error { + if updateVPCArgs == nil { + return fmt.Errorf("The updateVPCArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(vpcId)). + WithMethod(http.PUT). + WithQueryParam("modifyAttribute", ""). + WithBody(updateVPCArgs). + WithQueryParamFilter("clientToken", updateVPCArgs.ClientToken). + Do() +} + +// DeleteVPC - delete a specified VPC +// +// PARAMS: +// - vpcId: the VPC id to be deleted +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteVPC(vpcId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(vpcId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// GetPrivateIpAddressesInfo - get the privateIpAddressesInfo from vpc +// +// PARAMS: +// - getVpcPrivateIpArgs: the arguments to GetPrivateIpAddressInfo +// +// RETURNS: +// - *VpcPrivateIpAddressesResult: the privateIpAddresses info of the specified privateIps in specified vpc +// - error: nil if success otherwise the specific error +func (c *Client) GetPrivateIpAddressesInfo(args *GetVpcPrivateIpArgs) (*VpcPrivateIpAddressesResult, error) { + if args == nil { + return nil, fmt.Errorf("The GetVpcPrivateIpArgs cannot be nil.") + } + result := &VpcPrivateIpAddressesResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(args.VpcId)+"/privateIpAddressInfo"). + WithMethod(http.GET).WithQueryParamFilter("privateIpRange", args.PrivateIpRange) + if len(args.PrivateIpAddresses) != 0 { + for i := range args.PrivateIpAddresses { + builder.WithQueryParam("privateIpAddresses", args.PrivateIpAddresses[i]) + } + } + err := builder.WithResult(result).Do() + return result, err +} + +// GetNetworkTopologyInfo - get the network topology info +// +// PARAMS: +// - getNetworkTopologyArgs: the arguments to GetNetworkTopologyInfo +// +// RETURNS: +// - *NetworkTopologyResult: the network topologies info obtained based on host ip or host id +// - error: nil if success otherwise the specific error +func (c *Client) GetNetworkTopologyInfo(args *GetNetworkTopologyArgs) (*NetworkTopologyResult, error) { + if args == nil { + return nil, fmt.Errorf("The GetNetworkTopologyArgs cannot be nil.") + } + result := &NetworkTopologyResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForNetworkTopology()). + WithMethod(http.GET). + WithQueryParamFilter("hostIp", args.HostIp). + WithQueryParamFilter("hostId", args.HostId) + err := builder.WithResult(result).Do() + return result, err +} + +// CreateVPCDhcp - create vpc's dhcp info with the specified parameters +// +// PARAMS: +// - args: the arguments to create vpc's dhcp info +func (c *Client) CreateVPCDhcp(vpcId string, createVpcDhcpArgs *CreateVpcDhcpArgs) error { + if createVpcDhcpArgs == nil { + return fmt.Errorf("The CreateVPCDhcp cannot be nil.") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(vpcId)+"/dhcp"). + WithMethod(http.POST). + WithBody(createVpcDhcpArgs). + WithQueryParamFilter("clientToken", createVpcDhcpArgs.ClientToken). + Do() +} + +// UpdateVPCDhcp - update vpc's dhcp info with the specified parameters +// +// if domainNameServers is nil, will delete vpc's dhcp. +// +// PARAMS: +// - args: the arguments to create vpc's dhcp info +func (c *Client) UpdateVPCDhcp(vpcId string, updateVpcDhcpArgs *UpdateVpcDhcpArgs) error { + if updateVpcDhcpArgs == nil { + return fmt.Errorf("The UpdateVPCDhcp cannot be nil.") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(vpcId)+"/dhcp"). + WithMethod(http.PUT). + WithBody(updateVpcDhcpArgs). + WithQueryParamFilter("clientToken", updateVpcDhcpArgs.ClientToken). + Do() +} + +// GetVPCDhcpInfo - get the dhcp info of specified vpc +// PARAMS: +// - args: the vpc id to get vpc's dhcp info +// +// RETURNS: +// - *VpcDhcpInfo: the info of the VPC dhcp +// - error: nil if success otherwise the specific error +func (c *Client) GetVPCDhcpInfo(vpcId string) (*VpcDhcpInfo, error) { + result := &VpcDhcpInfo{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPCId(vpcId) + "/dhcp"). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} diff --git a/bce-sdk-go/services/vpn/client.go b/bce-sdk-go/services/vpn/client.go new file mode 100644 index 0000000..7515522 --- /dev/null +++ b/bce-sdk-go/services/vpn/client.go @@ -0,0 +1,70 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// client.go - define the client for VPC service + +// Package vpn defines the vpn services of BCE. +// The supported APIs are all defined in different files. +package vpn + +import ( + "github.com/baidubce/bce-sdk-go/bce" +) + +const ( + URI_PREFIX = bce.URI_PREFIX + "v1" + + DEFAULT_ENDPOINT = "bcc." + bce.DEFAULT_REGION + ".baidubce.com" + + REQUEST_VPN_URL = "/vpn" +) + +// Client of VPC service is a kind of BceClient, so derived from BceClient +type Client struct { + *bce.BceClient +} + +func NewClient(ak, sk, endPoint string) (*Client, error) { + if len(endPoint) == 0 { + endPoint = DEFAULT_ENDPOINT + } + client, err := bce.NewBceClientWithAkSk(ak, sk, endPoint) + if err != nil { + return nil, err + } + return &Client{client}, nil +} + +func getURLForVPN() string { + return URI_PREFIX + REQUEST_VPN_URL +} + +func getURLForVPNId(vpnId string) string { + return getURLForVPN() + "/" + vpnId +} + +func getURLForVpnConn() string { + return getURLForVPN() + "/vpnconn" +} +func getURLForVpnConnId(vpnConnId string) string { + return getURLForVPN() + "/vpnconn/" + vpnConnId +} + +func getURLForSslVpnServerByVpnId(vpnId string) string { + return getURLForVPNId(vpnId) + "/sslVpnServer" +} + +func getURLForSslVpnUserByVpnId(vpnId string) string { + return getURLForVPNId(vpnId) + "/sslVpnUser" +} diff --git a/bce-sdk-go/services/vpn/client_test.go b/bce-sdk-go/services/vpn/client_test.go new file mode 100644 index 0000000..4dfbbac --- /dev/null +++ b/bce-sdk-go/services/vpn/client_test.go @@ -0,0 +1,358 @@ +package vpn + +import ( + "encoding/json" + "fmt" + "github.com/baidubce/bce-sdk-go/util" + "github.com/baidubce/bce-sdk-go/util/log" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" +) + +var ( + VPN_CLIENT *Client + + region string + + VPNID string +) + +// For security reason, ak/sk should not hard write here. +type Conf struct { + AK string `json:"AK"` + SK string `json:"SK"` + VPCEndpoint string `json:"VPC"` + EIPEndpoint string `json:"EIP"` +} + +func init() { + log.SetLogHandler(log.STDERR) + log.SetLogLevel(log.DEBUG) + _, f, _, _ := runtime.Caller(0) + // Get the directory of GOPATH, the config file should be under the directory. + for i := 0; i < 7; i++ { + f = filepath.Dir(f) + } + conf := filepath.Join(f, "config.json") + fp, err := os.Open(conf) + if err != nil { + log.Fatal("config json file of ak/sk not given:", conf) + os.Exit(1) + } + decoder := json.NewDecoder(fp) + confObj := &Conf{} + decoder.Decode(confObj) + + VPN_CLIENT, _ = NewClient(confObj.AK, confObj.SK, confObj.VPCEndpoint) + + region = confObj.VPCEndpoint[4:6] +} + +// ExpectEqual is the helper function for test each case +func ExpectEqual(alert func(format string, args ...interface{}), + expected interface{}, actual interface{}) bool { + expectedValue, actualValue := reflect.ValueOf(expected), reflect.ValueOf(actual) + equal := false + switch { + case expected == nil && actual == nil: + return true + case expected != nil && actual == nil: + equal = expectedValue.IsNil() + case expected == nil && actual != nil: + equal = actualValue.IsNil() + default: + if actualType := reflect.TypeOf(actual); actualType != nil { + if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { + equal = reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) + } + } + } + if !equal { + _, file, line, _ := runtime.Caller(1) + alert("%s:%d: missmatch, expect %v but %v", file, line, expected, actual) + return false + } + return true +} + +func TestClient_CreateVpnGateway(t *testing.T) { + args := &CreateVpnGatewayArgs{ + VpnName: "TestSDK-VPN", + Description: "vpn test", + VpcId: "vpc-2pa2x0bjt26i", + Billing: &Billing{ + PaymentTiming: PAYMENT_TIMING_PREPAID, + Reservation: &Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + ClientToken: getClientToken(), + } + result, err := VPN_CLIENT.CreateVpnGateway(args) + ExpectEqual(t.Errorf, nil, err) + VPNID := result.VpnId + log.Debug(VPNID) +} + +func TestClient_ListVpnGateway(t *testing.T) { + args := &ListVpnGatewayArgs{ + MaxKeys: 1000, + VpcId: "vpc-2pa2x0bjt26i", + } + res, err := VPN_CLIENT.ListVpnGateway(args) + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(res) + fmt.Println(string(r)) + +} + +func TestClient_BindEip(t *testing.T) { + args := &BindEipArgs{ + ClientToken: getClientToken(), + Eip: "100.88.4.213", + } + err := VPN_CLIENT.BindEip("vpn-sd3vxkwisgux", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UnBindEip(t *testing.T) { + err := VPN_CLIENT.UnBindEip("vpn-sd3vxkwisgux", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_UpdateVpnGateway(t *testing.T) { + args := &UpdateVpnGatewayArgs{ + ClientToken: getClientToken(), + Name: "vpnTest", + } + err := VPN_CLIENT.UpdateVpnGateway("vpn-sd3vxkwisgux", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_GetVpnGatewayDetail(t *testing.T) { + result, err := VPN_CLIENT.GetVpnGatewayDetail("vpn-shr6dtz1jjbk") + ExpectEqual(t.Errorf, nil, err) + r, err := json.Marshal(result) + fmt.Println(string(r)) + +} + +func TestClient_RenewVpnGateway(t *testing.T) { + args := &RenewVpnGatewayArgs{ + ClientToken: getClientToken(), + Billing: &Billing{ + Reservation: &Reservation{ + ReservationLength: 1, + ReservationTimeUnit: "month", + }, + }, + } + err := VPN_CLIENT.RenewVpnGateway("vpn-smt119kcvqb1", args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_ListVpnConn(t *testing.T) { + res, err := VPN_CLIENT.ListVpnConn("vpn-shr6dtz1jjbk") + ExpectEqual(t.Errorf, nil, err) + log.Debug("%+v", res) + r, _ := json.Marshal(*res) + fmt.Println(string(r)) + +} +func TestClient_UpdateVpnConn(t *testing.T) { + args := &UpdateVpnConnArgs{ + VpnConnId: "vpnconn-mpfwkca8zsuv", + UpdateVpnconn: &CreateVpnConnArgs{ + VpnId: "vpn-shr6dtz1jjbk", + VpnConnName: "vpnconntest", + LocalIp: "0.1.2.3", + SecretKey: "!sdse154d", + LocalSubnets: []string{"192.168.0.0/20"}, + RemoteIp: "3.4.5.6", + RemoteSubnets: []string{"192.168.100.0/24"}, + CreateIkeConfig: &CreateIkeConfig{ + IkeVersion: "v1", + IkeMode: "main", + IkeEncAlg: "aes", + IkeAuthAlg: "sha1", + IkePfs: "group2", + IkeLifeTime: 25500, + }, + CreateIpsecConfig: &CreateIpsecConfig{ + IpsecEncAlg: "aes", + IpsecAuthAlg: "sha1", + IpsecPfs: "group2", + IpsecLifetime: 25500, + }, + }, + } + err := VPN_CLIENT.UpdateVpnConn(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateVpnConn(t *testing.T) { + args := &CreateVpnConnArgs{ + VpnId: "vpn-shr6dtz1jjbk", + VpnConnName: "vpnconntest111", + LocalIp: "0.1.2.3", + SecretKey: "!sdse154d", + LocalSubnets: []string{"192.168.0.0/20"}, + RemoteIp: "3.4.5.6", + RemoteSubnets: []string{"192.168.100.0/24"}, + CreateIkeConfig: &CreateIkeConfig{ + IkeVersion: "v1", + IkeMode: "main", + IkeEncAlg: "aes", + IkeAuthAlg: "sha1", + IkePfs: "group2", + IkeLifeTime: 25500, + }, + CreateIpsecConfig: &CreateIpsecConfig{ + IpsecEncAlg: "aes", + IpsecAuthAlg: "sha1", + IpsecPfs: "group2", + IpsecLifetime: 25500, + }, + } + res, err := VPN_CLIENT.CreateVpnConn(args) + ExpectEqual(t.Errorf, nil, err) + log.Debug("%+v", res) +} + +func TestClient_DeleteVpnConn(t *testing.T) { + err := VPN_CLIENT.DeleteVpnConn("vpnconn-mpfwkca8zsuv", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteVpn(t *testing.T) { + err := VPN_CLIENT.DeleteVpn("vpn-sd3vxkwisgux", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_CreateSslVpnServer(t *testing.T) { + interfaceTypeStr := "tun" + ClientDnsStr := "" + args := &CreateSslVpnServerArgs{ + ClientToken: getClientToken(), + VpnId: "vpn-s5bi05y3yyds", // ssl vpn + SslVpnServerName: "server_1", + InterfaceType: &interfaceTypeStr, + LocalSubnets: []string{"192.168.0.0/20"}, + RemoteSubnet: "192.168.100.0/24", + ClientDns: &ClientDnsStr, + } + log.Info(args) + log.Info("args.InterfaceType:", args.InterfaceType) + log.Info("args.ClientDns:", args.ClientDns) + if args.InterfaceType == nil { + log.Info("args.InterfaceType is unassigned") + } + res, err := VPN_CLIENT.CreateSslVpnServer(args) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_GetSslVpnServer(t *testing.T) { + res, err := VPN_CLIENT.GetSslVpnServer("vpn-s5bi05y3yyds", getClientToken()) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_UpdateSslVpnServer(t *testing.T) { + clientDnsStr := "100.88.0.83" + args := &UpdateSslVpnServerArgs{ + ClientToken: getClientToken(), + VpnId: "vpn-s5bi05y3yyds", + SslVpnServerId: "sslvpn-s8aqk5iw6ki1", + UpdateSslVpnServer: &UpdateSslVpnServer{ + SslVpnServerName: "SslVpnServer1test twice", + LocalSubnets: []string{"192.168.0.0/20"}, + RemoteSubnet: "192.168.100.0/24", + ClientDns: &clientDnsStr, + }, + } + err := VPN_CLIENT.UpdateSslVpnServer(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteSslVpnServer(t *testing.T) { + err := VPN_CLIENT.DeleteSslVpnServer("vpn-s5bi05y3yyds", "sslvpn-1swvxqrzn1we", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_BatchCreateSslVpnUser(t *testing.T) { + desc1 := "user1 description" + args := &BatchCreateSslVpnUserArgs{ + ClientToken: getClientToken(), + VpnId: "vpn-s5bi05y3yyds", // ssl vpn + SslVpnUsers: []SslVpnUser{ + SslVpnUser{ + UserName: "user1test", + Password: "psd123456!", + Description: &desc1, + }, + SslVpnUser{ + UserName: "user2test", + Password: "psd123456!", + }, + }, + } + res, err := VPN_CLIENT.BatchCreateSslVpnUser(args) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(res) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_ListSslVpnUser(t *testing.T) { + args := &ListSslVpnUserArgs{ + MaxKeys: 1000, + VpnId: "vpn-s5bi05y3yyds", + } + result, err := VPN_CLIENT.ListSslVpnUser(args) + ExpectEqual(t.Errorf, nil, err) + e, err1 := json.Marshal(result) + if err1 != nil { + log.Error("json format result error") + } + log.Info(string(e)) +} + +func TestClient_UpdateSslVpnUser(t *testing.T) { + psdStr := "123abcd!!!" + desc := "333" + args := &UpdateSslVpnUserArgs{ + ClientToken: getClientToken(), + VpnId: "vpn-s5bi05y3yyds", + UserId: "vpn-ssl-user-ebfysi53dye3", + SslVpnUser: &UpdateSslVpnUser{ + Password: psdStr, + Description: &desc, + }, + } + err := VPN_CLIENT.UpdateSslVpnUser(args) + ExpectEqual(t.Errorf, nil, err) +} + +func TestClient_DeleteSslVpnUser(t *testing.T) { + err := VPN_CLIENT.DeleteSslVpnUser("vpn-s5bi05y3yyds", "vpn-ssl-user-ggngktunui0k", getClientToken()) + ExpectEqual(t.Errorf, nil, err) +} + +func getClientToken() string { + return util.NewUUID() +} diff --git a/bce-sdk-go/services/vpn/model.go b/bce-sdk-go/services/vpn/model.go new file mode 100644 index 0000000..da5f7d5 --- /dev/null +++ b/bce-sdk-go/services/vpn/model.go @@ -0,0 +1,290 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// model.go - definitions of the request arguments and results data structure model + +package vpn + +type ( + PaymentTimingType string + PeerConnRoleType string + VpnStatusType string +) + +const ( + PAYMENT_TIMING_PREPAID PaymentTimingType = "Prepaid" + PAYMENT_TIMING_POSTPAID PaymentTimingType = "Postpaid" + + VPN_STATUS_BUILDING VpnStatusType = "building" + VPN_STATUS_UNCONFIGURED VpnStatusType = "unconfigured" + VPN_STATUS_CONFIGURING VpnStatusType = "configuring" + VPN_STATUS_ACTIVE VpnStatusType = "active" +) + +// CreateVpnGatewayArgs defines the structure of the input parameters for the CreateVpnGateway api +type CreateVpnGatewayArgs struct { + ClientToken string `json:"-"` + VpnName string `json:"vpnName"` + VpcId string `json:"vpcId"` + Description string `json:"description,omitempty"` + Eip string `json:"eip,omitempty"` + Billing *Billing `json:"billing"` +} + +type Reservation struct { + ReservationLength int `json:"reservationLength"` + ReservationTimeUnit string `json:"reservationTimeUnit"` +} + +type Billing struct { + PaymentTiming PaymentTimingType `json:"paymentTiming,omitempty"` + Reservation *Reservation `json:"reservation,omitempty"` +} + +// CreateVpnGatewayResult defines the structure of the output parameters for the CreateVpnGateway api +type CreateVpnGatewayResult struct { + VpnId string `json:"vpnId"` +} + +// ListVpnGatewayArgs defines the structure of the input parameters for the ListVpnGateway api +type ListVpnGatewayArgs struct { + VpcId string + Eip string + Marker string + MaxKeys int +} + +// ListVpnGatewayResult defines the structure of the output parameters for the ListVpnGateway api +type ListVpnGatewayResult struct { + Vpns []VPN `json:"vpns"` + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` +} + +// VPN is the result for getVpnDetail api. +type VPN struct { + Status VpnStatusType `json:"status"` + Eip string `json:"eip"` + VpnId string `json:"vpnId"` + VpcId string `json:"vpcId"` + Description string `json:"description"` + ExpiredTime string `json:"expiredTime"` + ProductType string `json:"paymentTiming"` + VpnConnNum int `json:"vpnConnNum"` + BandwidthInMbps int `json:"bandwidthInMbps"` + VpnConns []VpnConn `json:"vpnConns"` + Name string `json:"vpnName"` +} + +// UpdateVpnGatewayArgs defines the structure of the input parameters for the UpdateVpnGateway api +type UpdateVpnGatewayArgs struct { + ClientToken string `json:"-"` + Name string `json:"vpnName"` +} + +// BindEipArgs defines the structure of the input parameters for the BindEip api +type BindEipArgs struct { + ClientToken string `json:"-"` + Eip string `json:"eip"` +} + +type VpnConn struct { + VpnId string `json:"vpnId"` + VpnConnId string `json:"vpnConnId"` + VpnConnName string `json:"vpnConnName"` + LocalIp string `json:"localIp"` + SecretKey string `json:"secretKey"` + LocalSubnets []string `json:"localSubnets"` + RemoteIp string `json:"remoteIp"` + RemoteSubnets []string `json:"remoteSubnets"` + Description string `json:"description"` + Status string `json:"status"` + CreatedTime string `json:"createdTime"` + HealthStatus string `json:"healthStatus"` + IkeConfig IkeConfig `json:"ikeConfig"` + IpsecConfig IpsecConfig `json:"ipsecConfig"` +} + +type IkeConfig struct { + IkeVersion string `json:"ikeVersion"` + IkeMode string `json:"ikeMode"` + IkeEncAlg string `json:"ikeEncAlg"` + IkeAuthAlg string `json:"ikeAuthAlg"` + IkePfs string `json:"ikePfs"` + IkeLifeTime string `json:"ikeLifeTime"` +} +type IpsecConfig struct { + IpsecEncAlg string `json:"ipsecEncAlg"` + IpsecAuthAlg string `json:"ipsecAuthAlg"` + IpsecPfs string `json:"ipsecPfs"` + IpsecLifetime string `json:"ipsecLifetime"` +} + +// RenewVpnGatewayArgs defines the structure of the input parameters for the RenewVpnGateway api +type RenewVpnGatewayArgs struct { + ClientToken string `json:"-"` + Billing *Billing `json:"billing"` +} + +type CreateIkeConfig struct { + IkeVersion string `json:"ikeVersion"` + IkeMode string `json:"ikeMode"` + IkeEncAlg string `json:"ikeEncAlg"` + IkeAuthAlg string `json:"ikeAuthAlg"` + IkePfs string `json:"ikePfs"` + IkeLifeTime int `json:"ikeLifeTime"` +} +type CreateIpsecConfig struct { + IpsecEncAlg string `json:"ipsecEncAlg"` + IpsecAuthAlg string `json:"ipsecAuthAlg"` + IpsecPfs string `json:"ipsecPfs"` + IpsecLifetime int `json:"ipsecLifetime"` +} + +// CreateVpnConnArgs defines the structure of the input parameters for the CreateVpnGatewayConn api +type CreateVpnConnArgs struct { + ClientToken string `json:"-"` + VpnId string `json:"vpnId"` + VpnConnName string `json:"vpnConnName"` + LocalIp string `json:"localIp"` + SecretKey string `json:"secretKey"` + LocalSubnets []string `json:"localSubnets"` + RemoteIp string `json:"remoteIp"` + RemoteSubnets []string `json:"remoteSubnets"` + Description string `json:"description,omitempty"` + CreateIkeConfig *CreateIkeConfig `json:"ikeConfig"` + CreateIpsecConfig *CreateIpsecConfig `json:"ipsecConfig"` +} + +// CreateVpnConnResult defines the structure of the output parameters for the CreateVpnConn api +type CreateVpnConnResult struct { + VpnConnId string `json:"vpnConnId"` +} + +// UpdateVpnConnArgs defines the structure of input parameters for the UpdateVpnConn api +type UpdateVpnConnArgs struct { + VpnConnId string `json:"vpnConnId"` + UpdateVpnconn *CreateVpnConnArgs `json:"updateVpnconn"` +} + +// ListVpnConnResult defines the structure of output parameters for the ListVpnConn api +type ListVpnConnResult struct { + VpnConns []VpnConn `json:"vpnConns"` +} + +// SslVpnServer defines the structure of the output parameters for the GetSslVpnServer api +type SslVpnServer struct { + VpnId string `json:"vpnId"` + SslVpnServerId string `json:"sslVpnServerId"` + SslVpnServerName string `json:"sslVpnServerName"` + InterfaceType string `json:"interfaceType"` + Status string `json:"status"` + LocalSubnets []string `json:"localSubnets"` + RemoteSubnet string `json:"remoteSubnet"` + ClientDns string `json:"clientDns"` + MaxConnection int `json:"maxConnection"` +} + +// CreateSslVpnServerArgs defines the structure of the input parameters for the CreateSslVpnServer api +type CreateSslVpnServerArgs struct { + ClientToken string `json:"-"` + VpnId string `json:"vpnId"` + SslVpnServerName string `json:"sslVpnServerName"` + InterfaceType *string `json:"interfaceType,omitempty"` + LocalSubnets []string `json:"localSubnets"` + RemoteSubnet string `json:"remoteSubnet"` + ClientDns *string `json:"clientDns,omitempty"` +} + +// UpdateSslVpnServer defines part of the structure of the input parameters for the UpdateSslVpnServer api +type UpdateSslVpnServer struct { + SslVpnServerName string `json:"sslVpnServerName,omitempty"` + LocalSubnets []string `json:"localSubnets,omitempty"` + RemoteSubnet string `json:"remoteSubnet,omitempty"` + ClientDns *string `json:"clientDns,omitempty"` +} + +// CreateSslVpnServerResult defines the structure of the output parameters for the CreateSslVpnServer api +type CreateSslVpnServerResult struct { + SslVpnServerId string `json:"sslVpnServerId"` +} + +// UpdateSslVpnServerArgs defines the structure of input parameters for the UpdateSslVpnServer api +type UpdateSslVpnServerArgs struct { + ClientToken string `json:"-"` + VpnId string `json:"VpnId"` + SslVpnServerId string `json:"sslVpnServerId"` + UpdateSslVpnServer *UpdateSslVpnServer `json:"updateSslVpnServer"` +} + +// ListSslVpnServerResult defines the structure of output parameters for the ListSslVpnServer api +type ListSslVpnServerResult struct { + SslVpnServers []SslVpnServer `json:"sslVpnServers"` +} + +type SslVpnUser struct { + UserName string `json:"userName"` + Password string `json:"password"` + Description *string `json:"description,omitempty"` +} + +type SelectSslVpnUser struct { + UserId string `json:"userId"` + UserName string `json:"userName"` + Description string `json:"description"` +} + +type UpdateSslVpnUser struct { + Password string `json:"password,omitempty"` + Description *string `json:"description,omitempty"` +} + +// BatchCreateSslVpnUserArgs defines the structure of the input parameters for the CreateSslVpnUser api +type BatchCreateSslVpnUserArgs struct { + ClientToken string `json:"-"` + VpnId string `json:"vpnId"` + SslVpnUsers []SslVpnUser `json:"sslVpnUsers"` +} + +// BatchCreateSslVpnUserResult defines the structure of the output parameters for the BatchCreateSslVpnUser api +type BatchCreateSslVpnUserResult struct { + SslVpnUserIds []string `json:"sslVpnUserIds"` +} + +// UpdateSslVpnUserArgs defines the structure of input parameters for the UpdateSslVpnUser api +type UpdateSslVpnUserArgs struct { + ClientToken string `json:"-"` + VpnId string `json:"vpnId"` + UserId string `json:"userId"` + SslVpnUser *UpdateSslVpnUser `json:"sslVpnUser"` +} + +// ListSslVpnUserArgs defines the structure of input parameters for the ListSslVpnUser api +type ListSslVpnUserArgs struct { + Marker string `json:"marker"` + MaxKeys int `json:"maxKeys"` + VpnId string `json:"vpnId"` + UserName string `json:"username"` +} + +// ListSslVpnUserResult defines the structure of output parameters for the ListSslVpnUser api +type ListSslVpnUserResult struct { + Marker string `json:"marker"` + IsTruncated bool `json:"isTruncated"` + NextMarker string `json:"nextMarker"` + MaxKeys int `json:"maxKeys"` + SslVpnUsers []SelectSslVpnUser `json:"sslVpnUsers"` +} diff --git a/bce-sdk-go/services/vpn/vpn.go b/bce-sdk-go/services/vpn/vpn.go new file mode 100644 index 0000000..ae3b311 --- /dev/null +++ b/bce-sdk-go/services/vpn/vpn.go @@ -0,0 +1,455 @@ +/* + * Copyright 2020 Baidu, Inc. + * + * 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. + */ + +// vpn.go - the vpn gateway APIs definition supported by the VPN service + +package vpn + +import ( + "fmt" + "github.com/baidubce/bce-sdk-go/bce" + "github.com/baidubce/bce-sdk-go/http" + "strconv" +) + +// CreateVPNGateway - create a new vpn gateway +// +// PARAMS: +// - args: the arguments to create vpn gateway +// RETURNS: +// - *CreateVpnGatewayResult: the id of the vpn gateway newly created +// - error: nil if success otherwise the specific error + +func (c *Client) CreateVpnGateway(args *CreateVpnGatewayArgs) (*CreateVpnGatewayResult, error) { + if args == nil { + return nil, fmt.Errorf("The createVpnGatewayArgs cannot be nil.") + } + + result := &CreateVpnGatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPN()). + WithMethod(http.POST). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithResult(result). + Do() + + return result, err +} + +// +// ListVpn - list all vpn gateways with the specific parameters +// PARAMS: +// - args: the arguments to list vpn gateways +// RETURNS: +// - *ListVpnGatewayResult: the result of vpn gateway list +// - error: nil if success otherwise the specific error + +func (c *Client) ListVpnGateway(args *ListVpnGatewayArgs) (*ListVpnGatewayResult, error) { + if args == nil { + return nil, fmt.Errorf("The listVpnGatewayArgs cannot be nil.") + } + if args.MaxKeys == 0 { + args.MaxKeys = 1000 + } + + result := &ListVpnGatewayResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPN()). + WithMethod(http.GET). + WithQueryParam("vpcId", args.VpcId). + WithQueryParamFilter("eip", args.Eip). + WithQueryParamFilter("marker", args.Marker). + WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)). + WithResult(result). + Do() + + return result, err +} + +// DeleteVpnGateway - delete the specific vpn gateway +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - clientToken: the idempotent token +// RETURNS: +// - error: nil if success otherwise the specific error + +func (c *Client) DeleteVpn(vpnId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpnId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// DeleteVpnGateway - delete the specific vpn gateway +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteVpnGateway(vpcId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpcId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// GetVpnGatewayDetail - get details of the specific vpn gateway +// +// PARAMS: +// - vpnId: the id of the specified vpn +// +// RETURNS: +// - *VPN: the result of the specific vpn gateway details +// - error: nil if success otherwise the specific error +func (c *Client) GetVpnGatewayDetail(vpnId string) (*VPN, error) { + result := &VPN{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpnId)). + WithMethod(http.GET). + WithResult(result). + Do() + + return result, err +} + +// UpdateVpnGateway - update the specified vpn gateway +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - args: the arguments to update vpn gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateVpnGateway(vpnId string, args *UpdateVpnGatewayArgs) error { + if args == nil { + return fmt.Errorf("The updateVpnGatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpnId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParam("modifyAttribute", ""). + WithQueryParamFilter("clientToken", args.ClientToken). + Do() +} + +// BindEip - bind eip for the specific vpn gateway +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - args: the arguments to bind eip +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BindEip(vpnId string, args *BindEipArgs) error { + if args == nil { + return fmt.Errorf("The bindEipArgs cannot be nil.") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpnId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("bind", ""). + Do() +} + +// UnBindEips - unbind eip for the specific vpn gateway +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UnBindEip(vpnId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpnId)). + WithMethod(http.PUT). + WithQueryParamFilter("clientToken", clientToken). + WithQueryParam("unbind", ""). + Do() +} + +// RenewVpnGateway - renew vpn gateway with the specific parameters +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - args: the arguments to renew vpn gateway +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) RenewVpnGateway(vpnId string, args *RenewVpnGatewayArgs) error { + if args == nil { + return fmt.Errorf("The renewVpnGatewayArgs cannot be nil.") + } + + return bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(vpnId)). + WithMethod(http.PUT). + WithBody(args). + WithQueryParamFilter("clientToken", args.ClientToken). + WithQueryParam("purchaseReserved", ""). + Do() +} + +// CreateVpnConn - create vpnconn with the specific parameters +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - args: the arguments to create vpnconn +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateVpnConn(args *CreateVpnConnArgs) (*CreateVpnConnResult, error) { + if args == nil { + return nil, fmt.Errorf("The CreateVpnConnArgs cannot be nil.") + } + result := &CreateVpnConnResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVPNId(args.VpnId) + "/vpnconn"). + WithMethod(http.POST). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpdateVpnConn - create vpnconn with the specific parameters +// +// PARAMS: +// - args: the arguments to update vpnconn +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateVpnConn(args *UpdateVpnConnArgs) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForVpnConnId(args.VpnConnId)). + WithMethod(http.PUT). + WithBody(args.UpdateVpnconn). + Do() +} + +// ListVpnConn - list vpnconn with the specific vpnId +// +// PARAMS: +// - vpnId:the id you want to list vpnconn +// +// RETURNS: +// - *ListVpnConnResult: the result of vpn gateway'conn list +// - error: nil if success otherwise the specific error +func (c *Client) ListVpnConn(vpnId string) (*ListVpnConnResult, error) { + result := &ListVpnConnResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForVpnConn() + "/" + vpnId). + WithMethod(http.GET). + WithResult(result). + Do() + return result, err +} + +// DeleteVpnConn - delete the specific vpnconn +// +// PARAMS: +// - vpnConnId: the id of the specific vpnconn +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteVpnConn(vpnConnId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForVpnConnId(vpnConnId)). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// CreateSslVpnServer - create ssl-vpn server with the specific parameters +// +// PARAMS: +// - args: the arguments to create ssl-vpn server +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) CreateSslVpnServer(args *CreateSslVpnServerArgs) (*CreateSslVpnServerResult, error) { + if args == nil { + return nil, fmt.Errorf("the CreateSslVpnServerArgs cannot be nil") + } + + if args.InterfaceType == nil { + defaultInterfaceType := "tap" + args.InterfaceType = &defaultInterfaceType + } + result := &CreateSslVpnServerResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnServerByVpnId(args.VpnId)). + WithMethod(http.POST). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpdateSslVpnServer - update ssl-vpn server with the specific parameters +// +// PARAMS: +// - args: the arguments to update ssl ssl-vpn server +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSslVpnServer(args *UpdateSslVpnServerArgs) error { + if args == nil { + return fmt.Errorf("the UpdateSslVpnServerArgs cannot be nil") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnServerByVpnId(args.VpnId)+"/"+args.SslVpnServerId). + WithMethod(http.PUT). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args.UpdateSslVpnServer). + Do() +} + +// GetSslVpnServer - get details of the specific ssl-vpn server +// +// PARAMS: +// - vpnId: the id of the specified vpn +// +// RETURNS: +// - *SslVpnServer: the result of the specific ssl-vpn server details +// - error: nil if success otherwise the specific error +func (c *Client) GetSslVpnServer(vpnId, clientToken string) (*SslVpnServer, error) { + result := &SslVpnServer{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnServerByVpnId(vpnId)). + WithMethod(http.GET). + WithQueryParamFilter("clientToken", clientToken). + WithResult(result). + Do() + + return result, err +} + +// DeleteSslVpnServer - delete ssl-vpn server with the specific vpnId +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - sslVpnServerId: the id of the specific ssl-vpn server +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSslVpnServer(vpnId, sslVpnServerId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnServerByVpnId(vpnId)+"/"+sslVpnServerId). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() +} + +// BatchCreateSslVpnUser - batch create ssl-vpn user with the specific parameters +// +// PARAMS: +// - args: the arguments to create ssl-vpn users +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) BatchCreateSslVpnUser(args *BatchCreateSslVpnUserArgs) (*BatchCreateSslVpnUserResult, error) { + if args == nil { + return nil, fmt.Errorf("the BatchCreateSslVpnUserArgs cannot be nil") + } + result := &BatchCreateSslVpnUserResult{} + err := bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnUserByVpnId(args.VpnId)). + WithMethod(http.POST). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args). + WithResult(result). + Do() + return result, err +} + +// UpdateSslVpnUser - update ssl-vpn user with the specific parameters +// +// PARAMS: +// - args: the arguments to update the specific ssl-vpn user +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) UpdateSslVpnUser(args *UpdateSslVpnUserArgs) error { + if args == nil { + return fmt.Errorf("the UpdateSslVpnUserArgs cannot be nil") + } + if len(args.SslVpnUser.Password) == 0 && args.SslVpnUser.Description == nil { + return fmt.Errorf("both password and description are nil") + } + return bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnUserByVpnId(args.VpnId)+"/"+args.UserId). + WithMethod(http.PUT). + WithQueryParamFilter("clientToken", args.ClientToken). + WithBody(args.SslVpnUser). + Do() +} + +// ListSslVpnUser - list ssl-vpn user with the specific vpnId +// +// PARAMS: +// - args: the arguments to list ssl-vpn users +// +// RETURNS: +// - *ListSslVpnUserResult: the result of vpn ssl-vpn user list contains page infos +// - error: nil if success otherwise the specific error +func (c *Client) ListSslVpnUser(args *ListSslVpnUserArgs) (*ListSslVpnUserResult, error) { + if args == nil { + args = &ListSslVpnUserArgs{} + } + if args.MaxKeys < 0 || args.MaxKeys > 1000 { + return nil, fmt.Errorf("the field maxKeys is out of range [0, 1000]") + } + result := &ListSslVpnUserResult{} + builder := bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnUserByVpnId(args.VpnId)). + WithMethod(http.GET). + WithResult(result). + WithQueryParamFilter("marker", args.Marker) + if args.MaxKeys != 0 { + builder.WithQueryParamFilter("maxKeys", strconv.Itoa(args.MaxKeys)) + } + err := builder.Do() + return result, err +} + +// DeleteSslVpnUser - delete ssl-vpn user with the specific vpnId and userId +// +// PARAMS: +// - vpnId: the id of the specific vpn gateway +// - userId: the id of the specific ssl-vpn user +// - clientToken: the idempotent token +// +// RETURNS: +// - error: nil if success otherwise the specific error +func (c *Client) DeleteSslVpnUser(vpnId, userId, clientToken string) error { + return bce.NewRequestBuilder(c). + WithURL(getURLForSslVpnUserByVpnId(vpnId)+"/"+userId). + WithMethod(http.DELETE). + WithQueryParamFilter("clientToken", clientToken). + Do() + +} diff --git a/bce-sdk-go/util/crypto/ebc.go b/bce-sdk-go/util/crypto/ebc.go new file mode 100644 index 0000000..34fa3fc --- /dev/null +++ b/bce-sdk-go/util/crypto/ebc.go @@ -0,0 +1,37 @@ +package crypto + +import ( + "bytes" + "crypto/aes" + "fmt" +) + +func EBCEncrypto(key, data []byte) ([]byte, error) { + block, err := aes.NewCipher(key) + if err != nil { + return nil, err + } + + content := pKCS5Padding([]byte(data), block.BlockSize()) + crypted := make([]byte, len(content)) + + if len(content)%block.BlockSize() != 0 { + return nil, fmt.Errorf("crypto/cipher: input not full blocks") + } + + src := content + dst := crypted + for len(src) > 0 { + block.Encrypt(dst, src[:block.BlockSize()]) + src = src[block.BlockSize():] + dst = dst[block.BlockSize():] + } + + return crypted, nil +} + +func pKCS5Padding(ciphertext []byte, blockSize int) []byte { + padding := blockSize - len(ciphertext)%blockSize + padtext := bytes.Repeat([]byte{byte(padding)}, padding) + return append(ciphertext, padtext...) +} diff --git a/bce-sdk-go/util/log/cce_logger.go b/bce-sdk-go/util/log/cce_logger.go new file mode 100644 index 0000000..5d2c645 --- /dev/null +++ b/bce-sdk-go/util/log/cce_logger.go @@ -0,0 +1,15 @@ +package log + +var _ SDKLogger = &logger{} + +type SDKLogger interface { + Logging(level Level, format string, args ...interface{}) +} + +func (l *logger) Logging(level Level, format string, args ...interface{}) { + l.logging(level, format, args...) +} + +func SetLogger(logger SDKLogger) { + gDefaultLogger = logger +} diff --git a/bce-sdk-go/util/log/logger.go b/bce-sdk-go/util/log/logger.go new file mode 100644 index 0000000..85eb85f --- /dev/null +++ b/bce-sdk-go/util/log/logger.go @@ -0,0 +1,400 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// logger.go - defines the logger structure and methods + +// Package log implements the log facilities for BCE. It supports log to stderr, stdout as well as +// log to file with rotating. It is safe to be called by multiple goroutines. +// By using the package level function to use the default logger: +// +// log.SetLogHandler(log.STDOUT | log.FILE) // default is log to stdout +// log.SetLogDir("/tmp") // default is /tmp +// log.SetRotateType(log.ROTATE_DAY) // default is log.HOUR +// log.SetRotateSize(1 << 30) // default is 1GB +// log.SetLogLevel(log.INFO) // default is log.DEBUG +// log.Debug(1, 1.2, "a") +// log.Debugln(1, 1.2, "a") +// log.Debugf(1, 1.2, "a") +// +// User can also create new logger without using the default logger: +// +// customLogger := log.NewLogger() +// customLogger.SetLogHandler(log.FILE) +// customLogger.Debug(1, 1.2, "a") +// +// The log format can also support custom setting by using the following interface: +// +// log.SetLogFormat([]string{log.FMT_LEVEL, log.FMT_TIME, log.FMT_MSG}) +// +// Most of the cases just use the default format is enough: +// +// []string{FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG} +package log + +import ( + "fmt" + "io" + "os" + "path/filepath" + "runtime" + "strings" + "time" +) + +type Handler uint8 + +// Constants for log handler flags, default is STDOUT +const ( + NONE Handler = 0 + STDOUT Handler = 1 + STDERR Handler = 1 << 1 + FILE Handler = 1 << 2 +) + +type RotateStrategy uint8 + +// Constants for log rotating strategy when logging to file, default is by hour +const ( + ROTATE_NONE RotateStrategy = iota + ROTATE_DAY + ROTATE_HOUR + ROTATE_MINUTE + ROTATE_SIZE + + DEFAULT_ROTATE_TYPE = ROTATE_HOUR + DEFAULT_ROTATE_SIZE int64 = 1 << 30 + DEFAULT_LOG_DIR = "/tmp" + ROTATE_SIZE_FILE_PREFIX = "rotating" +) + +type Level uint8 + +// Constants for log levels, default is DEBUG +const ( + DEBUG Level = iota + INFO + WARN + ERROR + FATAL + PANIC +) + +var gLevelString = [...]string{"DEBUG", "INFO", "WARN", "ERROR", "FATAL", "PANIC"} + +// Constants of the log format components to support user custom specification +const ( + FMT_LEVEL = "level" + FMT_LTIME = "ltime" // long time with microsecond + FMT_TIME = "time" // just with second + FMT_LOCATION = "location" // caller's location with file, line, function + FMT_MSG = "msg" +) + +var ( + LOG_FMT_STR = map[string]string{ + FMT_LEVEL: "[%s]", + FMT_LTIME: "2006-01-02 15:04:05.000000", + FMT_TIME: "2006-01-02 15:04:05", + FMT_LOCATION: "%s:%d:%s:", + FMT_MSG: "%s", + } + gDefaultLogFormat = []string{FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG} +) + +type writerArgs struct { + record string + rotateArgs interface{} // used for rotating: the size of the record or the logging time +} + +// Logger defines the internal implementation of the log facility +type logger struct { + writers map[Handler]io.WriteCloser // the destination writer to log message + writerChan chan *writerArgs // the writer channal to pass each record and time or size + logFormat []string + levelThreshold Level + handler Handler + + // Fields that used when logging to file + logDir string + logFile string + rotateType RotateStrategy + rotateSize int64 + done chan bool +} + +func (l *logger) logging(level Level, format string, args ...interface{}) { + // Only log message that set the handler and is greater than or equal to the threshold + if l.handler == NONE || level < l.levelThreshold { + return + } + + // Generate the log record string and pass it to the writer channel + now := time.Now() + pc, file, line, ok, funcname := uintptr(0), "???", 0, true, "???" + pc, file, line, ok = runtime.Caller(2) + if ok { + funcname = runtime.FuncForPC(pc).Name() + funcname = filepath.Ext(funcname) + funcname = strings.TrimPrefix(funcname, ".") + file = filepath.Base(file) + } + buf := make([]string, 0, len(l.logFormat)) + msg := fmt.Sprintf(format, args...) + for _, f := range l.logFormat { + if _, exists := LOG_FMT_STR[f]; !exists { // skip not supported part + continue + } + fmtStr := LOG_FMT_STR[f] + switch f { + case FMT_LEVEL: + buf = append(buf, fmt.Sprintf(fmtStr, gLevelString[level])) + case FMT_LTIME: + buf = append(buf, now.Format(fmtStr)) + case FMT_TIME: + buf = append(buf, now.Format(fmtStr)) + case FMT_LOCATION: + buf = append(buf, fmt.Sprintf(fmtStr, file, line, funcname)) + case FMT_MSG: + buf = append(buf, fmt.Sprintf(fmtStr, msg)) + } + } + record := strings.Join(buf, " ") + if l.rotateType == ROTATE_SIZE { + l.writerChan <- &writerArgs{record, int64(len(record))} + } else { + l.writerChan <- &writerArgs{record, now} + } + + // wait for current record done logging +} + +func (l *logger) buildWriter(args interface{}) { + if l.handler&STDOUT == STDOUT { + l.writers[STDOUT] = os.Stdout + } else { + delete(l.writers, STDOUT) + } + if l.handler&STDERR == STDERR { + l.writers[STDERR] = os.Stderr + } else { + delete(l.writers, STDERR) + } + if l.handler&FILE == FILE { + l.writers[FILE] = l.buildFileWriter(args) + } else { + delete(l.writers, FILE) + } +} + +func (l *logger) buildFileWriter(args interface{}) io.WriteCloser { + if l.handler&FILE != FILE { + return os.Stderr + } + + if len(l.logDir) == 0 { + l.logDir = DEFAULT_LOG_DIR + } + if l.rotateType < ROTATE_NONE || l.rotateType > ROTATE_SIZE { + l.rotateType = DEFAULT_ROTATE_TYPE + } + if l.rotateType == ROTATE_SIZE && l.rotateSize == 0 { + l.rotateSize = DEFAULT_ROTATE_SIZE + } + + logFile, needCreateFile := "", false + if l.rotateType == ROTATE_SIZE { + recordSize, _ := args.(int64) + logFile, needCreateFile = l.buildFileWriterBySize(recordSize) + } else { + recordTime, _ := args.(time.Time) + switch l.rotateType { + case ROTATE_NONE: + logFile = "default.log" + case ROTATE_DAY: + logFile = recordTime.Format("2006-01-02.log") + case ROTATE_HOUR: + logFile = recordTime.Format("2006-01-02_15.log") + case ROTATE_MINUTE: + logFile = recordTime.Format("2006-01-02_15-04.log") + } + if _, exist := getFileInfo(filepath.Join(l.logDir, logFile)); !exist { + needCreateFile = true + } + } + l.logFile = logFile + logFile = filepath.Join(l.logDir, l.logFile) + + // Should create new file + if needCreateFile { + if w, ok := l.writers[FILE]; ok { + w.Close() + } + if writer, err := os.Create(logFile); err == nil { + return writer + } else { + return os.Stderr + } + } + + // Already open the file + if w, ok := l.writers[FILE]; ok { + return w + } + + // Newly open the file + if writer, err := os.OpenFile(logFile, os.O_WRONLY|os.O_APPEND, 0666); err == nil { + return writer + } else { + return os.Stderr + } +} + +func (l *logger) buildFileWriterBySize(recordSize int64) (string, bool) { + logFile, needCreateFile := "", false + // First running the program and need to get filename by checking the existed files + if len(l.logFile) == 0 { + fname := fmt.Sprintf("%s-%s.0.log", ROTATE_SIZE_FILE_PREFIX, getSizeString(l.rotateSize)) + for { + size, exist := getFileInfo(filepath.Join(l.logDir, fname)) + if !exist { + logFile, needCreateFile = fname, true + break + } + if exist && size+recordSize <= l.rotateSize { + logFile, needCreateFile = fname, false + break + } + fname = getNextFileName(fname) + } + } else { // check the file size to append to the existed file or create a new file + currentFile := filepath.Join(l.logDir, l.logFile) + size, exist := getFileInfo(currentFile) + if !exist { + logFile, needCreateFile = l.logFile, true + } else { + if size+recordSize > l.rotateSize { // size exceeded + logFile, needCreateFile = getNextFileName(l.logFile), true + } else { + logFile, needCreateFile = l.logFile, false + } + } + } + return logFile, needCreateFile +} + +func (l *logger) SetHandler(h Handler) { l.handler = h } + +func (l *logger) SetLogDir(dir string) { l.logDir = dir } + +func (l *logger) SetLogLevel(level Level) { l.levelThreshold = level } + +func (l *logger) SetLogFormat(format []string) { l.logFormat = format } + +func (l *logger) SetRotateType(rotate RotateStrategy) { l.rotateType = rotate } + +func (l *logger) SetRotateSize(size int64) { l.rotateSize = size } + +func (l *logger) Debug(msg ...interface{}) { l.logging(DEBUG, "%s\n", concat(msg...)) } + +func (l *logger) Debugln(msg ...interface{}) { l.logging(DEBUG, "%s\n", concat(msg...)) } + +func (l *logger) Debugf(f string, msg ...interface{}) { l.logging(DEBUG, f+"\n", msg...) } + +func (l *logger) Info(msg ...interface{}) { l.logging(INFO, "%s\n", concat(msg...)) } + +func (l *logger) Infoln(msg ...interface{}) { l.logging(INFO, "%s\n", concat(msg...)) } + +func (l *logger) Infof(f string, msg ...interface{}) { l.logging(INFO, f+"\n", msg...) } + +func (l *logger) Warn(msg ...interface{}) { l.logging(WARN, "%s\n", concat(msg...)) } + +func (l *logger) Warnln(msg ...interface{}) { l.logging(WARN, "%s\n", concat(msg...)) } + +func (l *logger) Warnf(f string, msg ...interface{}) { l.logging(WARN, f+"\n", msg...) } + +func (l *logger) Error(msg ...interface{}) { l.logging(ERROR, "%s\n", concat(msg...)) } + +func (l *logger) Errorln(msg ...interface{}) { l.logging(ERROR, "%s\n", concat(msg...)) } + +func (l *logger) Errorf(f string, msg ...interface{}) { l.logging(ERROR, f+"\n", msg...) } + +func (l *logger) Fatal(msg ...interface{}) { l.logging(FATAL, "%s\n", concat(msg...)) } + +func (l *logger) Fatalln(msg ...interface{}) { l.logging(FATAL, "%s\n", concat(msg...)) } + +func (l *logger) Fatalf(f string, msg ...interface{}) { l.logging(FATAL, f+"\n", msg...) } + +func (l *logger) Panic(msg ...interface{}) { + record := concat(msg...) + l.logging(PANIC, "%s\n", record) + panic(record) +} + +func (l *logger) Panicln(msg ...interface{}) { + record := concat(msg...) + l.logging(PANIC, "%s\n", record) + panic(record) +} + +func (l *logger) Panicf(format string, msg ...interface{}) { + record := fmt.Sprintf(format, msg...) + l.logging(PANIC, format+"\n", msg...) + panic(record) +} + +func (l *logger) Close() { + select { + case <-l.done: + return + default: + } + l.writerChan <- nil +} + +func NewLogger() *logger { + obj := &logger{ + writers: make(map[Handler]io.WriteCloser, 3), // now only support 3 kinds of handler + writerChan: make(chan *writerArgs, 100), + logFormat: gDefaultLogFormat, + levelThreshold: DEBUG, + handler: NONE, + done: make(chan bool), + } + // The backend writer goroutine to write each log record + go func() { + defer func() { + if e := recover(); e != nil { + fmt.Println(e) + } + }() + for { + select { + case <-obj.done: + return + case args := <-obj.writerChan: // wait until a record comes to log + if args == nil { + close(obj.done) + close(obj.writerChan) + return + } + obj.buildWriter(args.rotateArgs) + for _, w := range obj.writers { + fmt.Fprint(w, args.record) + } + } + } + }() + + return obj +} diff --git a/bce-sdk-go/util/log/util.go b/bce-sdk-go/util/log/util.go new file mode 100644 index 0000000..dc46a51 --- /dev/null +++ b/bce-sdk-go/util/log/util.go @@ -0,0 +1,243 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// util.go - define the package-level default logger and functions for easily use. + +package log + +import ( + "fmt" + "os" + "strconv" + "strings" +) + +// The global default logger object to perform logging in this package-level functions +var gDefaultLogger SDKLogger + +func init() { + gDefaultLogger = NewLogger() +} + +// Helper functions +func getFileInfo(path string) (int64, bool) { + info, err := os.Stat(path) + if err != nil { + return -1, false + } else { + return info.Size(), true + } +} + +func getSizeString(size int64) string { + if size < 0 { + return fmt.Sprintf("%d", size) + } + if size < (1 << 10) { + return fmt.Sprintf("%dB", size) + } else if size < (1 << 20) { + return fmt.Sprintf("%dkB", size>>10) + } else if size < (1 << 30) { + return fmt.Sprintf("%dMB", size>>20) + } else if size < (1 << 40) { + return fmt.Sprintf("%dGB", size>>30) + } else { + return "SUPER-LARGE" + } +} + +func getNextFileName(nowFileName string) string { + pos1 := strings.Index(nowFileName, ".") + rest := nowFileName[pos1+1:] + pos2 := strings.Index(rest, ".") + num, _ := strconv.Atoi(rest[0:pos2]) + return fmt.Sprintf("%s.%d.log", nowFileName[0:pos1], num+1) +} + +func concat(msg ...interface{}) string { + buf := make([]string, 0, len(msg)) + for _, m := range msg { + buf = append(buf, fmt.Sprintf("%v", m)) + } + return strings.Join(buf, " ") +} + +// Export package-level functions for logging messages by using the default logger. It supports 3 +// kinds of interface which is similar to the standard package "fmt": with suffix of "ln", "f" or +// nothing. +func Debug(msg ...interface{}) { + gDefaultLogger.Logging(DEBUG, "%s\n", concat(msg...)) +} + +func Debugln(msg ...interface{}) { + gDefaultLogger.Logging(DEBUG, "%s\n", concat(msg...)) +} + +func Debugf(format string, msg ...interface{}) { + gDefaultLogger.Logging(DEBUG, format+"\n", msg...) +} + +func Info(msg ...interface{}) { + gDefaultLogger.Logging(INFO, "%s\n", concat(msg...)) +} + +func Infoln(msg ...interface{}) { + gDefaultLogger.Logging(INFO, "%s\n", concat(msg...)) +} + +func Infof(format string, msg ...interface{}) { + gDefaultLogger.Logging(INFO, format+"\n", msg...) +} + +func Warn(msg ...interface{}) { + gDefaultLogger.Logging(WARN, "%s\n", concat(msg...)) +} + +func Warnln(msg ...interface{}) { + gDefaultLogger.Logging(WARN, "%s\n", concat(msg...)) +} + +func Warnf(format string, msg ...interface{}) { + gDefaultLogger.Logging(WARN, format+"\n", msg...) +} + +func Error(msg ...interface{}) { + gDefaultLogger.Logging(ERROR, "%s\n", concat(msg...)) +} + +func Errorln(msg ...interface{}) { + gDefaultLogger.Logging(ERROR, "%s\n", concat(msg...)) +} + +func Errorf(format string, msg ...interface{}) { + gDefaultLogger.Logging(ERROR, format+"\n", msg...) +} + +func Fatal(msg ...interface{}) { + gDefaultLogger.Logging(FATAL, "%s\n", concat(msg...)) +} + +func Fatalln(msg ...interface{}) { + gDefaultLogger.Logging(FATAL, "%s\n", concat(msg...)) +} + +func Fatalf(format string, msg ...interface{}) { + gDefaultLogger.Logging(FATAL, format+"\n", msg...) +} + +func Panic(msg ...interface{}) { + record := concat(msg...) + gDefaultLogger.Logging(PANIC, "%s\n", record) + panic(record) +} + +func Panicln(msg ...interface{}) { + record := concat(msg...) + gDefaultLogger.Logging(PANIC, "%s\n", record) + panic(record) +} + +func Panicf(format string, msg ...interface{}) { + record := fmt.Sprintf(format, msg...) + gDefaultLogger.Logging(PANIC, format+"\n", msg...) + panic(record) +} + +func Close() { + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.Close() + } +} + +// SetLogHandler - set the handler of the logger +// +// PARAMS: +// - Handler: the handler defined in this package, now just support STDOUT, STDERR, FILE +func SetLogHandler(h Handler) { + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.handler = h + } +} + +// SetLogLevel - set the level threshold of the logger, only level equal to or bigger than this +// value will be logged. +// +// PARAMS: +// - Level: the level defined in this package, now support 6 levels. +func SetLogLevel(l Level) { + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.levelThreshold = l + } +} + +// SetLogFormat - set the log component of each record when logging it. The default log format is +// {FMT_LEVEL, FMT_LTIME, FMT_LOCATION, FMT_MSG}. +// +// PARAMS: +// - format: the format component array. +func SetLogFormat(format []string) { + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.logFormat = format + } +} + +// SetLogDir - set the logging directory if logging to file. +// +// PARAMS: +// - dir: the logging directory +// +// RETURNS: +// - error: check the directory and try to make it, otherwise return the error. +func SetLogDir(dir string) error { + if _, err := os.Stat(dir); err != nil { + if os.IsNotExist(err) { + if mkErr := os.Mkdir(dir, os.ModePerm); mkErr != nil { + return mkErr + } + } else { + return err + } + } + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.logDir = dir + } + return nil +} + +// SetRotateType - set the rotating strategy if logging to file. +// +// PARAMS: +// - RotateStrategy: the rotate strategy defined in this package, now support 5 strategy. +func SetRotateType(r RotateStrategy) { + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.rotateType = r + } +} + +// SetRotateSize - set the rotating size if logging to file and set the strategy of size. +// +// PARAMS: +// - size: the rotating size +// +// RETURNS: +// - error: check the value and return any error if error occurs. +func SetRotateSize(size int64) error { + if size <= 0 { + return fmt.Errorf("%s", "rotate size should not be negative") + } + if sdkLogger, ok := gDefaultLogger.(*logger); ok { + sdkLogger.rotateSize = size + } + return nil +} diff --git a/bce-sdk-go/util/mime.go b/bce-sdk-go/util/mime.go new file mode 100644 index 0000000..4246344 --- /dev/null +++ b/bce-sdk-go/util/mime.go @@ -0,0 +1,664 @@ +package util + +import ( + "sync" +) + +var DefaultMimeMap map[string]string +var once sync.Once + +func LoadMimeMap() { + DefaultMimeMap = make(map[string]string) + DefaultMimeMap[".ez"] = "application/andrew-inset" + DefaultMimeMap[".atom"] = "application/atom+xml" + DefaultMimeMap[".atomcat"] = "application/atomcat+xml" + DefaultMimeMap[".atomsvc"] = "application/atomsvc+xml" + DefaultMimeMap[".ccxml"] = "application/ccxml+xml" + DefaultMimeMap[".davmount"] = "application/davmount+xml" + DefaultMimeMap[".ecma"] = "application/ecmascript" + DefaultMimeMap[".pfr"] = "application/font-tdpfr" + DefaultMimeMap[".stk"] = "application/hyperstudio" + DefaultMimeMap[".js"] = "text/javascript" + DefaultMimeMap[".json"] = "text/json" + DefaultMimeMap[".hqx"] = "application/mac-binhex40" + DefaultMimeMap[".cpt"] = "application/mac-compactpro" + DefaultMimeMap[".mrc"] = "application/marc" + DefaultMimeMap[".ma"] = "application/mathematica" + DefaultMimeMap[".nb"] = "application/mathematica" + DefaultMimeMap[".mb"] = "application/mathematica" + DefaultMimeMap[".mathml"] = "application/mathml+xml" + DefaultMimeMap[".mbox"] = "application/mbox" + DefaultMimeMap[".mscml"] = "application/mediaservercontrol+xml" + DefaultMimeMap[".mp4s"] = "application/mp4" + DefaultMimeMap[".doc"] = "application/msword" + DefaultMimeMap[".dot"] = "application/msword" + DefaultMimeMap[".mxf"] = "application/mxf" + DefaultMimeMap[".bin"] = "application/octet-stream" + DefaultMimeMap[".dms"] = "application/octet-stream" + DefaultMimeMap[".lha"] = "application/octet-stream" + DefaultMimeMap[".lzh"] = "application/octet-stream" + DefaultMimeMap[".class"] = "application/octet-stream" + DefaultMimeMap[".so"] = "application/octet-stream" + DefaultMimeMap[".iso"] = "application/octet-stream" + DefaultMimeMap[".dmg"] = "application/octet-stream" + DefaultMimeMap[".dist"] = "application/octet-stream" + DefaultMimeMap[".distz"] = "application/octet-stream" + DefaultMimeMap[".pkg"] = "application/octet-stream" + DefaultMimeMap[".bpk"] = "application/octet-stream" + DefaultMimeMap[".dump"] = "application/octet-stream" + DefaultMimeMap[".elc"] = "application/octet-stream" + DefaultMimeMap[".oda"] = "application/oda" + DefaultMimeMap[".ogg"] = "application/ogg" + DefaultMimeMap[".pdf"] = "application/pdf" + DefaultMimeMap[".pgp"] = "application/pgp-encrypted" + DefaultMimeMap[".asc"] = "application/pgp-signature" + DefaultMimeMap[".sig"] = "application/pgp-signature" + DefaultMimeMap[".prf"] = "application/pics-rules" + DefaultMimeMap[".p10"] = "application/pkcs10" + DefaultMimeMap[".p7m"] = "application/pkcs7-mime" + DefaultMimeMap[".p7c"] = "application/pkcs7-mime" + DefaultMimeMap[".p7s"] = "application/pkcs7-signature" + DefaultMimeMap[".cer"] = "application/pkix-cert" + DefaultMimeMap[".crl"] = "application/pkix-crl" + DefaultMimeMap[".pkipath"] = "application/pkix-pkipath" + DefaultMimeMap[".pki"] = "application/pkixcmp" + DefaultMimeMap[".pls"] = "application/pls+xml" + DefaultMimeMap[".ai"] = "application/postscript" + DefaultMimeMap[".eps"] = "application/postscript" + DefaultMimeMap[".ps"] = "application/postscript" + DefaultMimeMap[".cww"] = "application/prs.cww" + DefaultMimeMap[".rdf"] = "application/rdf+xml" + DefaultMimeMap[".rif"] = "application/reginfo+xml" + DefaultMimeMap[".rnc"] = "application/relax-ng-compact-syntax" + DefaultMimeMap[".rl"] = "application/resource-lists+xml" + DefaultMimeMap[".rs"] = "application/rls-services+xml" + DefaultMimeMap[".rsd"] = "application/rsd+xml" + DefaultMimeMap[".rss"] = "application/rss+xml" + DefaultMimeMap[".rtf"] = "application/rtf" + DefaultMimeMap[".sbml"] = "application/sbml+xml" + DefaultMimeMap[".scq"] = "application/scvp-cv-request" + DefaultMimeMap[".scs"] = "application/scvp-cv-response" + DefaultMimeMap[".spq"] = "application/scvp-vp-request" + DefaultMimeMap[".spp"] = "application/scvp-vp-response" + DefaultMimeMap[".sdp"] = "application/sdp" + DefaultMimeMap[".setpay"] = "application/set-payment-initiation" + DefaultMimeMap[".setreg"] = "application/set-registration-initiation" + DefaultMimeMap[".shf"] = "application/shf+xml" + DefaultMimeMap[".smi"] = "application/smil+xml" + DefaultMimeMap[".smil"] = "application/smil+xml" + DefaultMimeMap[".rq"] = "application/sparql-query" + DefaultMimeMap[".srx"] = "application/sparql-results+xml" + DefaultMimeMap[".gram"] = "application/srgs" + DefaultMimeMap[".grxml"] = "application/srgs+xml" + DefaultMimeMap[".ssml"] = "application/ssml+xml" + DefaultMimeMap[".plb"] = "application/vnd.3gpp.pic-bw-large" + DefaultMimeMap[".psb"] = "application/vnd.3gpp.pic-bw-small" + DefaultMimeMap[".pvb"] = "application/vnd.3gpp.pic-bw-var" + DefaultMimeMap[".tcap"] = "application/vnd.3gpp2.tcap" + DefaultMimeMap[".pwn"] = "application/vnd.3m.post-it-notes" + DefaultMimeMap[".aso"] = "application/vnd.accpac.simply.aso" + DefaultMimeMap[".imp"] = "application/vnd.accpac.simply.imp" + DefaultMimeMap[".acu"] = "application/vnd.acucobol" + DefaultMimeMap[".atc"] = "application/vnd.acucorp" + DefaultMimeMap[".acutc"] = "application/vnd.acucorp" + DefaultMimeMap[".xdp"] = "application/vnd.adobe.xdp+xml" + DefaultMimeMap[".xfdf"] = "application/vnd.adobe.xfdf" + DefaultMimeMap[".ami"] = "application/vnd.amiga.ami" + DefaultMimeMap[".cii"] = "application/vnd.anser-web-certificate-issue-initiation" + DefaultMimeMap[".fti"] = "application/vnd.anser-web-funds-transfer-initiation" + DefaultMimeMap[".atx"] = "application/vnd.antix.game-component" + DefaultMimeMap[".mpkg"] = "application/vnd.apple.installer+xml" + DefaultMimeMap[".aep"] = "application/vnd.audiograph" + DefaultMimeMap[".mpm"] = "application/vnd.blueice.multipass" + DefaultMimeMap[".bmi"] = "application/vnd.bmi" + DefaultMimeMap[".rep"] = "application/vnd.businessobjects" + DefaultMimeMap[".cdxml"] = "application/vnd.chemdraw+xml" + DefaultMimeMap[".mmd"] = "application/vnd.chipnuts.karaoke-mmd" + DefaultMimeMap[".cdy"] = "application/vnd.cinderella" + DefaultMimeMap[".cla"] = "application/vnd.claymore" + DefaultMimeMap[".c4g"] = "application/vnd.clonk.c4group" + DefaultMimeMap[".c4d"] = "application/vnd.clonk.c4group" + DefaultMimeMap[".c4f"] = "application/vnd.clonk.c4group" + DefaultMimeMap[".c4p"] = "application/vnd.clonk.c4group" + DefaultMimeMap[".c4u"] = "application/vnd.clonk.c4group" + DefaultMimeMap[".csp"] = "application/vnd.commonspace" + DefaultMimeMap[".cst"] = "application/vnd.commonspace" + DefaultMimeMap[".cdbcmsg"] = "application/vnd.contact.cmsg" + DefaultMimeMap[".cmc"] = "application/vnd.cosmocaller" + DefaultMimeMap[".clkx"] = "application/vnd.crick.clicker" + DefaultMimeMap[".clkk"] = "application/vnd.crick.clicker.keyboard" + DefaultMimeMap[".clkp"] = "application/vnd.crick.clicker.palette" + DefaultMimeMap[".clkt"] = "application/vnd.crick.clicker.template" + DefaultMimeMap[".clkw"] = "application/vnd.crick.clicker.wordbank" + DefaultMimeMap[".wbs"] = "application/vnd.criticaltools.wbs+xml" + DefaultMimeMap[".pml"] = "application/vnd.ctc-posml" + DefaultMimeMap[".ppd"] = "application/vnd.cups-ppd" + DefaultMimeMap[".curl"] = "application/vnd.curl" + DefaultMimeMap[".rdz"] = "application/vnd.data-vision.rdz" + DefaultMimeMap[".fe_launch"] = "application/vnd.denovo.fcselayout-link" + DefaultMimeMap[".dna"] = "application/vnd.dna" + DefaultMimeMap[".mlp"] = "application/vnd.dolby.mlp" + DefaultMimeMap[".dpg"] = "application/vnd.dpgraph" + DefaultMimeMap[".dfac"] = "application/vnd.dreamfactory" + DefaultMimeMap[".mag"] = "application/vnd.ecowin.chart" + DefaultMimeMap[".nml"] = "application/vnd.enliven" + DefaultMimeMap[".esf"] = "application/vnd.epson.esf" + DefaultMimeMap[".msf"] = "application/vnd.epson.msf" + DefaultMimeMap[".qam"] = "application/vnd.epson.quickanime" + DefaultMimeMap[".slt"] = "application/vnd.epson.salt" + DefaultMimeMap[".ssf"] = "application/vnd.epson.ssf" + DefaultMimeMap[".es3"] = "application/vnd.eszigno3+xml" + DefaultMimeMap[".et3"] = "application/vnd.eszigno3+xml" + DefaultMimeMap[".ez2"] = "application/vnd.ezpix-album" + DefaultMimeMap[".ez3"] = "application/vnd.ezpix-package" + DefaultMimeMap[".fdf"] = "application/vnd.fdf" + DefaultMimeMap[".gph"] = "application/vnd.flographit" + DefaultMimeMap[".ftc"] = "application/vnd.fluxtime.clip" + DefaultMimeMap[".fm"] = "application/vnd.framemaker" + DefaultMimeMap[".frame"] = "application/vnd.framemaker" + DefaultMimeMap[".maker"] = "application/vnd.framemaker" + DefaultMimeMap[".fnc"] = "application/vnd.frogans.fnc" + DefaultMimeMap[".ltf"] = "application/vnd.frogans.ltf" + DefaultMimeMap[".fsc"] = "application/vnd.fsc.weblaunch" + DefaultMimeMap[".oas"] = "application/vnd.fujitsu.oasys" + DefaultMimeMap[".oa2"] = "application/vnd.fujitsu.oasys2" + DefaultMimeMap[".oa3"] = "application/vnd.fujitsu.oasys3" + DefaultMimeMap[".fg5"] = "application/vnd.fujitsu.oasysgp" + DefaultMimeMap[".bh2"] = "application/vnd.fujitsu.oasysprs" + DefaultMimeMap[".ddd"] = "application/vnd.fujixerox.ddd" + DefaultMimeMap[".xdw"] = "application/vnd.fujixerox.docuworks" + DefaultMimeMap[".xbd"] = "application/vnd.fujixerox.docuworks.binder" + DefaultMimeMap[".fzs"] = "application/vnd.fuzzysheet" + DefaultMimeMap[".txd"] = "application/vnd.genomatix.tuxedo" + DefaultMimeMap[".kml"] = "application/vnd.google-earth.kml+xml" + DefaultMimeMap[".kmz"] = "application/vnd.google-earth.kmz" + DefaultMimeMap[".gqf"] = "application/vnd.grafeq" + DefaultMimeMap[".gqs"] = "application/vnd.grafeq" + DefaultMimeMap[".gac"] = "application/vnd.groove-account" + DefaultMimeMap[".ghf"] = "application/vnd.groove-help" + DefaultMimeMap[".gim"] = "application/vnd.groove-identity-message" + DefaultMimeMap[".grv"] = "application/vnd.groove-injector" + DefaultMimeMap[".gtm"] = "application/vnd.groove-tool-message" + DefaultMimeMap[".tpl"] = "application/vnd.groove-tool-template" + DefaultMimeMap[".vcg"] = "application/vnd.groove-vcard" + DefaultMimeMap[".zmm"] = "application/vnd.handheld-entertainment+xml" + DefaultMimeMap[".hbci"] = "application/vnd.hbci" + DefaultMimeMap[".les"] = "application/vnd.hhe.lesson-player" + DefaultMimeMap[".hpgl"] = "application/vnd.hp-hpgl" + DefaultMimeMap[".hpid"] = "application/vnd.hp-hpid" + DefaultMimeMap[".hps"] = "application/vnd.hp-hps" + DefaultMimeMap[".jlt"] = "application/vnd.hp-jlyt" + DefaultMimeMap[".pcl"] = "application/vnd.hp-pcl" + DefaultMimeMap[".pclxl"] = "application/vnd.hp-pclxl" + DefaultMimeMap[".x3d"] = "application/vnd.hzn-3d-crossword" + DefaultMimeMap[".mpy"] = "application/vnd.ibm.minipay" + DefaultMimeMap[".afp"] = "application/vnd.ibm.modcap" + DefaultMimeMap[".listafp"] = "application/vnd.ibm.modcap" + DefaultMimeMap[".list3820"] = "application/vnd.ibm.modcap" + DefaultMimeMap[".irm"] = "application/vnd.ibm.rights-management" + DefaultMimeMap[".sc"] = "application/vnd.ibm.secure-container" + DefaultMimeMap[".igl"] = "application/vnd.igloader" + DefaultMimeMap[".ivp"] = "application/vnd.immervision-ivp" + DefaultMimeMap[".ivu"] = "application/vnd.immervision-ivu" + DefaultMimeMap[".xpw"] = "application/vnd.intercon.formnet" + DefaultMimeMap[".xpx"] = "application/vnd.intercon.formnet" + DefaultMimeMap[".qbo"] = "application/vnd.intu.qbo" + DefaultMimeMap[".qfx"] = "application/vnd.intu.qfx" + DefaultMimeMap[".rcprofile"] = "application/vnd.ipunplugged.rcprofile" + DefaultMimeMap[".irp"] = "application/vnd.irepository.package+xml" + DefaultMimeMap[".xpr"] = "application/vnd.is-xpr" + DefaultMimeMap[".jam"] = "application/vnd.jam" + DefaultMimeMap[".rms"] = "application/vnd.jcp.javame.midlet-rms" + DefaultMimeMap[".jisp"] = "application/vnd.jisp" + DefaultMimeMap[".joda"] = "application/vnd.joost.joda-archive" + DefaultMimeMap[".ktz"] = "application/vnd.kahootz" + DefaultMimeMap[".ktr"] = "application/vnd.kahootz" + DefaultMimeMap[".karbon"] = "application/vnd.kde.karbon" + DefaultMimeMap[".chrt"] = "application/vnd.kde.kchart" + DefaultMimeMap[".kfo"] = "application/vnd.kde.kformula" + DefaultMimeMap[".flw"] = "application/vnd.kde.kivio" + DefaultMimeMap[".kon"] = "application/vnd.kde.kontour" + DefaultMimeMap[".kpr"] = "application/vnd.kde.kpresenter" + DefaultMimeMap[".kpt"] = "application/vnd.kde.kpresenter" + DefaultMimeMap[".ksp"] = "application/vnd.kde.kspread" + DefaultMimeMap[".kwd"] = "application/vnd.kde.kword" + DefaultMimeMap[".kwt"] = "application/vnd.kde.kword" + DefaultMimeMap[".htke"] = "application/vnd.kenameaapp" + DefaultMimeMap[".kia"] = "application/vnd.kidspiration" + DefaultMimeMap[".kne"] = "application/vnd.kinar" + DefaultMimeMap[".knp"] = "application/vnd.kinar" + DefaultMimeMap[".skp"] = "application/vnd.koan" + DefaultMimeMap[".skd"] = "application/vnd.koan" + DefaultMimeMap[".skt"] = "application/vnd.koan" + DefaultMimeMap[".skm"] = "application/vnd.koan" + DefaultMimeMap[".lbd"] = "application/vnd.llamagraphics.life-balance.desktop" + DefaultMimeMap[".lbe"] = "application/vnd.llamagraphics.life-balance.exchange+xml" + DefaultMimeMap[".123"] = "application/vnd.lotus-1-2-3" + DefaultMimeMap[".apr"] = "application/vnd.lotus-approach" + DefaultMimeMap[".pre"] = "application/vnd.lotus-freelance" + DefaultMimeMap[".nsf"] = "application/vnd.lotus-notes" + DefaultMimeMap[".org"] = "application/vnd.lotus-organizer" + DefaultMimeMap[".scm"] = "application/vnd.lotus-screencam" + DefaultMimeMap[".lwp"] = "application/vnd.lotus-wordpro" + DefaultMimeMap[".portpkg"] = "application/vnd.macports.portpkg" + DefaultMimeMap[".mcd"] = "application/vnd.mcd" + DefaultMimeMap[".mc1"] = "application/vnd.medcalcdata" + DefaultMimeMap[".cdkey"] = "application/vnd.mediastation.cdkey" + DefaultMimeMap[".mwf"] = "application/vnd.mfer" + DefaultMimeMap[".mfm"] = "application/vnd.mfmp" + DefaultMimeMap[".flo"] = "application/vnd.micrografx.flo" + DefaultMimeMap[".igx"] = "application/vnd.micrografx.igx" + DefaultMimeMap[".mif"] = "application/vnd.mif" + DefaultMimeMap[".daf"] = "application/vnd.mobius.daf" + DefaultMimeMap[".dis"] = "application/vnd.mobius.dis" + DefaultMimeMap[".mbk"] = "application/vnd.mobius.mbk" + DefaultMimeMap[".mqy"] = "application/vnd.mobius.mqy" + DefaultMimeMap[".msl"] = "application/vnd.mobius.msl" + DefaultMimeMap[".plc"] = "application/vnd.mobius.plc" + DefaultMimeMap[".txf"] = "application/vnd.mobius.txf" + DefaultMimeMap[".mpn"] = "application/vnd.mophun.application" + DefaultMimeMap[".mpc"] = "application/vnd.mophun.certificate" + DefaultMimeMap[".cil"] = "application/vnd.ms-artgalry" + DefaultMimeMap[".asf"] = "application/vnd.ms-asf" + DefaultMimeMap[".cab"] = "application/vnd.ms-cab-compressed" + DefaultMimeMap[".xls"] = "application/vnd.ms-excel" + DefaultMimeMap[".xlm"] = "application/vnd.ms-excel" + DefaultMimeMap[".xla"] = "application/vnd.ms-excel" + DefaultMimeMap[".xlc"] = "application/vnd.ms-excel" + DefaultMimeMap[".xlt"] = "application/vnd.ms-excel" + DefaultMimeMap[".xlw"] = "application/vnd.ms-excel" + DefaultMimeMap[".eot"] = "application/vnd.ms-fontobject" + DefaultMimeMap[".chm"] = "application/vnd.ms-htmlhelp" + DefaultMimeMap[".ims"] = "application/vnd.ms-ims" + DefaultMimeMap[".lrm"] = "application/vnd.ms-lrm" + DefaultMimeMap[".ppt"] = "application/vnd.ms-powerpoint" + DefaultMimeMap[".pps"] = "application/vnd.ms-powerpoint" + DefaultMimeMap[".pot"] = "application/vnd.ms-powerpoint" + DefaultMimeMap[".mpp"] = "application/vnd.ms-project" + DefaultMimeMap[".mpt"] = "application/vnd.ms-project" + DefaultMimeMap[".wps"] = "application/vnd.ms-works" + DefaultMimeMap[".wks"] = "application/vnd.ms-works" + DefaultMimeMap[".wcm"] = "application/vnd.ms-works" + DefaultMimeMap[".wdb"] = "application/vnd.ms-works" + DefaultMimeMap[".wpl"] = "application/vnd.ms-wpl" + DefaultMimeMap[".xps"] = "application/vnd.ms-xpsdocument" + DefaultMimeMap[".mseq"] = "application/vnd.mseq" + DefaultMimeMap[".mus"] = "application/vnd.musician" + DefaultMimeMap[".msty"] = "application/vnd.muvee.style" + DefaultMimeMap[".nlu"] = "application/vnd.neurolanguage.nlu" + DefaultMimeMap[".nnd"] = "application/vnd.noblenet-directory" + DefaultMimeMap[".nns"] = "application/vnd.noblenet-sealer" + DefaultMimeMap[".nnw"] = "application/vnd.noblenet-web" + DefaultMimeMap[".ngdat"] = "application/vnd.nokia.n-gage.data" + DefaultMimeMap[".n-gage"] = "application/vnd.nokia.n-gage.symbian.install" + DefaultMimeMap[".rpst"] = "application/vnd.nokia.radio-preset" + DefaultMimeMap[".rpss"] = "application/vnd.nokia.radio-presets" + DefaultMimeMap[".edm"] = "application/vnd.novadigm.edm" + DefaultMimeMap[".edx"] = "application/vnd.novadigm.edx" + DefaultMimeMap[".ext"] = "application/vnd.novadigm.ext" + DefaultMimeMap[".odc"] = "application/vnd.oasis.opendocument.chart" + DefaultMimeMap[".otc"] = "application/vnd.oasis.opendocument.chart-template" + DefaultMimeMap[".odf"] = "application/vnd.oasis.opendocument.formula" + DefaultMimeMap[".otf"] = "application/vnd.oasis.opendocument.formula-template" + DefaultMimeMap[".odg"] = "application/vnd.oasis.opendocument.graphics" + DefaultMimeMap[".otg"] = "application/vnd.oasis.opendocument.graphics-template" + DefaultMimeMap[".odi"] = "application/vnd.oasis.opendocument.image" + DefaultMimeMap[".oti"] = "application/vnd.oasis.opendocument.image-template" + DefaultMimeMap[".odp"] = "application/vnd.oasis.opendocument.presentation" + DefaultMimeMap[".otp"] = "application/vnd.oasis.opendocument.presentation-template" + DefaultMimeMap[".ods"] = "application/vnd.oasis.opendocument.spreadsheet" + DefaultMimeMap[".ots"] = "application/vnd.oasis.opendocument.spreadsheet-template" + DefaultMimeMap[".odt"] = "application/vnd.oasis.opendocument.text" + DefaultMimeMap[".otm"] = "application/vnd.oasis.opendocument.text-master" + DefaultMimeMap[".ott"] = "application/vnd.oasis.opendocument.text-template" + DefaultMimeMap[".oth"] = "application/vnd.oasis.opendocument.text-web" + DefaultMimeMap[".xo"] = "application/vnd.olpc-sugar" + DefaultMimeMap[".dd2"] = "application/vnd.oma.dd2+xml" + DefaultMimeMap[".oxt"] = "application/vnd.openofficeorg.extension" + DefaultMimeMap[".dp"] = "application/vnd.osgi.dp" + DefaultMimeMap[".prc"] = "application/vnd.palm" + DefaultMimeMap[".pdb"] = "application/vnd.palm" + DefaultMimeMap[".pqa"] = "application/vnd.palm" + DefaultMimeMap[".oprc"] = "application/vnd.palm" + DefaultMimeMap[".str"] = "application/vnd.pg.format" + DefaultMimeMap[".ei6"] = "application/vnd.pg.osasli" + DefaultMimeMap[".efif"] = "application/vnd.picsel" + DefaultMimeMap[".plf"] = "application/vnd.pocketlearn" + DefaultMimeMap[".pbd"] = "application/vnd.powerbuilder6" + DefaultMimeMap[".box"] = "application/vnd.previewsystems.box" + DefaultMimeMap[".mgz"] = "application/vnd.proteus.magazine" + DefaultMimeMap[".qps"] = "application/vnd.publishare-delta-tree" + DefaultMimeMap[".ptid"] = "application/vnd.pvi.ptid1" + DefaultMimeMap[".qxd"] = "application/vnd.quark.quarkxpress" + DefaultMimeMap[".qxt"] = "application/vnd.quark.quarkxpress" + DefaultMimeMap[".qwd"] = "application/vnd.quark.quarkxpress" + DefaultMimeMap[".qwt"] = "application/vnd.quark.quarkxpress" + DefaultMimeMap[".qxl"] = "application/vnd.quark.quarkxpress" + DefaultMimeMap[".qxb"] = "application/vnd.quark.quarkxpress" + DefaultMimeMap[".mxl"] = "application/vnd.recordare.musicxml" + DefaultMimeMap[".rm"] = "application/vnd.rn-realmedia" + DefaultMimeMap[".see"] = "application/vnd.seemail" + DefaultMimeMap[".sema"] = "application/vnd.sema" + DefaultMimeMap[".semd"] = "application/vnd.semd" + DefaultMimeMap[".semf"] = "application/vnd.semf" + DefaultMimeMap[".ifm"] = "application/vnd.shana.informed.formdata" + DefaultMimeMap[".itp"] = "application/vnd.shana.informed.formtemplate" + DefaultMimeMap[".iif"] = "application/vnd.shana.informed.interchange" + DefaultMimeMap[".ipk"] = "application/vnd.shana.informed.package" + DefaultMimeMap[".twd"] = "application/vnd.simtech-mindmapper" + DefaultMimeMap[".twds"] = "application/vnd.simtech-mindmapper" + DefaultMimeMap[".mmf"] = "application/vnd.smaf" + DefaultMimeMap[".sdkm"] = "application/vnd.solent.sdkm+xml" + DefaultMimeMap[".sdkd"] = "application/vnd.solent.sdkm+xml" + DefaultMimeMap[".dxp"] = "application/vnd.spotfire.dxp" + DefaultMimeMap[".sfs"] = "application/vnd.spotfire.sfs" + DefaultMimeMap[".sus"] = "application/vnd.sus-calendar" + DefaultMimeMap[".susp"] = "application/vnd.sus-calendar" + DefaultMimeMap[".svd"] = "application/vnd.svd" + DefaultMimeMap[".xsm"] = "application/vnd.syncml+xml" + DefaultMimeMap[".bdm"] = "application/vnd.syncml.dm+wbxml" + DefaultMimeMap[".xdm"] = "application/vnd.syncml.dm+xml" + DefaultMimeMap[".tao"] = "application/vnd.tao.intent-module-archive" + DefaultMimeMap[".tmo"] = "application/vnd.tmobile-livetv" + DefaultMimeMap[".tpt"] = "application/vnd.trid.tpt" + DefaultMimeMap[".mxs"] = "application/vnd.triscape.mxs" + DefaultMimeMap[".tra"] = "application/vnd.trueapp" + DefaultMimeMap[".ufd"] = "application/vnd.ufdl" + DefaultMimeMap[".ufdl"] = "application/vnd.ufdl" + DefaultMimeMap[".utz"] = "application/vnd.uiq.theme" + DefaultMimeMap[".umj"] = "application/vnd.umajin" + DefaultMimeMap[".unityweb"] = "application/vnd.unity" + DefaultMimeMap[".uoml"] = "application/vnd.uoml+xml" + DefaultMimeMap[".vcx"] = "application/vnd.vcx" + DefaultMimeMap[".vsd"] = "application/vnd.visio" + DefaultMimeMap[".vst"] = "application/vnd.visio" + DefaultMimeMap[".vss"] = "application/vnd.visio" + DefaultMimeMap[".vsw"] = "application/vnd.visio" + DefaultMimeMap[".vis"] = "application/vnd.visionary" + DefaultMimeMap[".vsf"] = "application/vnd.vsf" + DefaultMimeMap[".wbxml"] = "application/vnd.wap.wbxml" + DefaultMimeMap[".wmlc"] = "application/vnd.wap.wmlc" + DefaultMimeMap[".wmlsc"] = "application/vnd.wap.wmlscriptc" + DefaultMimeMap[".wtb"] = "application/vnd.webturbo" + DefaultMimeMap[".wpd"] = "application/vnd.wordperfect" + DefaultMimeMap[".wqd"] = "application/vnd.wqd" + DefaultMimeMap[".stf"] = "application/vnd.wt.stf" + DefaultMimeMap[".xar"] = "application/vnd.xara" + DefaultMimeMap[".xfdl"] = "application/vnd.xfdl" + DefaultMimeMap[".hvd"] = "application/vnd.yamaha.hv-dic" + DefaultMimeMap[".hvs"] = "application/vnd.yamaha.hv-script" + DefaultMimeMap[".hvp"] = "application/vnd.yamaha.hv-voice" + DefaultMimeMap[".saf"] = "application/vnd.yamaha.smaf-audio" + DefaultMimeMap[".spf"] = "application/vnd.yamaha.smaf-phrase" + DefaultMimeMap[".cmp"] = "application/vnd.yellowriver-custom-menu" + DefaultMimeMap[".zaz"] = "application/vnd.zzazz.deck+xml" + DefaultMimeMap[".vxml"] = "application/voicexml+xml" + DefaultMimeMap[".hlp"] = "application/winhlp" + DefaultMimeMap[".wsdl"] = "application/wsdl+xml" + DefaultMimeMap[".wspolicy"] = "application/wspolicy+xml" + DefaultMimeMap[".ace"] = "application/x-ace-compressed" + DefaultMimeMap[".bcpio"] = "application/x-bcpio" + DefaultMimeMap[".torrent"] = "application/x-bittorrent" + DefaultMimeMap[".bz"] = "application/x-bzip" + DefaultMimeMap[".bz2"] = "application/x-bzip2" + DefaultMimeMap[".boz"] = "application/x-bzip2" + DefaultMimeMap[".vcd"] = "application/x-cdlink" + DefaultMimeMap[".chat"] = "application/x-chat" + DefaultMimeMap[".pgn"] = "application/x-chess-pgn" + DefaultMimeMap[".cpio"] = "application/x-cpio" + DefaultMimeMap[".csh"] = "application/x-csh" + DefaultMimeMap[".dcr"] = "application/x-director" + DefaultMimeMap[".dir"] = "application/x-director" + DefaultMimeMap[".dxr"] = "application/x-director" + DefaultMimeMap[".fgd"] = "application/x-director" + DefaultMimeMap[".dvi"] = "application/x-dvi" + DefaultMimeMap[".spl"] = "application/x-futuresplash" + DefaultMimeMap[".gtar"] = "application/x-gtar" + DefaultMimeMap[".hdf"] = "application/x-hdf" + DefaultMimeMap[".latex"] = "application/x-latex" + DefaultMimeMap[".wmd"] = "application/x-ms-wmd" + DefaultMimeMap[".wmz"] = "application/x-ms-wmz" + DefaultMimeMap[".mdb"] = "application/x-msaccess" + DefaultMimeMap[".obd"] = "application/x-msbinder" + DefaultMimeMap[".crd"] = "application/x-mscardfile" + DefaultMimeMap[".clp"] = "application/x-msclip" + DefaultMimeMap[".exe"] = "application/x-msdownload" + DefaultMimeMap[".dll"] = "application/x-msdownload" + DefaultMimeMap[".com"] = "application/x-msdownload" + DefaultMimeMap[".bat"] = "application/x-msdownload" + DefaultMimeMap[".msi"] = "application/x-msdownload" + DefaultMimeMap[".mvb"] = "application/x-msmediaview" + DefaultMimeMap[".m13"] = "application/x-msmediaview" + DefaultMimeMap[".m14"] = "application/x-msmediaview" + DefaultMimeMap[".wmf"] = "application/x-msmetafile" + DefaultMimeMap[".mny"] = "application/x-msmoney" + DefaultMimeMap[".pub"] = "application/x-mspublisher" + DefaultMimeMap[".scd"] = "application/x-msschedule" + DefaultMimeMap[".trm"] = "application/x-msterminal" + DefaultMimeMap[".wri"] = "application/x-mswrite" + DefaultMimeMap[".nc"] = "application/x-netcdf" + DefaultMimeMap[".cdf"] = "application/x-netcdf" + DefaultMimeMap[".p12"] = "application/x-pkcs12" + DefaultMimeMap[".pfx"] = "application/x-pkcs12" + DefaultMimeMap[".p7b"] = "application/x-pkcs7-certificates" + DefaultMimeMap[".spc"] = "application/x-pkcs7-certificates" + DefaultMimeMap[".p7r"] = "application/x-pkcs7-certreqresp" + DefaultMimeMap[".rar"] = "application/x-rar-compressed" + DefaultMimeMap[".sh"] = "application/x-sh" + DefaultMimeMap[".shar"] = "application/x-shar" + DefaultMimeMap[".swf"] = "application/x-shockwave-flash" + DefaultMimeMap[".sit"] = "application/x-stuffit" + DefaultMimeMap[".sitx"] = "application/x-stuffitx" + DefaultMimeMap[".sv4cpio"] = "application/x-sv4cpio" + DefaultMimeMap[".sv4crc"] = "application/x-sv4crc" + DefaultMimeMap[".tar"] = "application/x-tar" + DefaultMimeMap[".tcl"] = "application/x-tcl" + DefaultMimeMap[".tex"] = "application/x-tex" + DefaultMimeMap[".texinfo"] = "application/x-texinfo" + DefaultMimeMap[".texi"] = "application/x-texinfo" + DefaultMimeMap[".ustar"] = "application/x-ustar" + DefaultMimeMap[".src"] = "application/x-wais-source" + DefaultMimeMap[".der"] = "application/x-x509-ca-cert" + DefaultMimeMap[".crt"] = "application/x-x509-ca-cert" + DefaultMimeMap[".xenc"] = "application/xenc+xml" + DefaultMimeMap[".xhtml"] = "application/xhtml+xml" + DefaultMimeMap[".xht"] = "application/xhtml+xml" + DefaultMimeMap[".xml"] = "text/xml" + DefaultMimeMap[".xsl"] = "application/xml" + DefaultMimeMap[".dtd"] = "application/xml-dtd" + DefaultMimeMap[".xop"] = "application/xop+xml" + DefaultMimeMap[".xslt"] = "application/xslt+xml" + DefaultMimeMap[".xspf"] = "application/xspf+xml" + DefaultMimeMap[".mxml"] = "application/xv+xml" + DefaultMimeMap[".xhvml"] = "application/xv+xml" + DefaultMimeMap[".xvml"] = "application/xv+xml" + DefaultMimeMap[".xvm"] = "application/xv+xml" + DefaultMimeMap[".zip"] = "application/zip" + DefaultMimeMap[".au"] = "audio/basic" + DefaultMimeMap[".snd"] = "audio/basic" + DefaultMimeMap[".mid"] = "audio/midi" + DefaultMimeMap[".midi"] = "audio/midi" + DefaultMimeMap[".kar"] = "audio/midi" + DefaultMimeMap[".rmi"] = "audio/midi" + DefaultMimeMap[".mp4a"] = "audio/mp4" + DefaultMimeMap[".mpga"] = "audio/mpeg" + DefaultMimeMap[".mp2"] = "audio/mpeg" + DefaultMimeMap[".mp2a"] = "audio/mpeg" + DefaultMimeMap[".mp3"] = "audio/mpeg" + DefaultMimeMap[".m2a"] = "audio/mpeg" + DefaultMimeMap[".m3a"] = "audio/mpeg" + DefaultMimeMap[".eol"] = "audio/vnd.digital-winds" + DefaultMimeMap[".lvp"] = "audio/vnd.lucent.voice" + DefaultMimeMap[".ecelp4800"] = "audio/vnd.nuera.ecelp4800" + DefaultMimeMap[".ecelp7470"] = "audio/vnd.nuera.ecelp7470" + DefaultMimeMap[".ecelp9600"] = "audio/vnd.nuera.ecelp9600" + DefaultMimeMap[".wav"] = "audio/wav" + DefaultMimeMap[".aif"] = "audio/x-aiff" + DefaultMimeMap[".aiff"] = "audio/x-aiff" + DefaultMimeMap[".aifc"] = "audio/x-aiff" + DefaultMimeMap[".m3u"] = "audio/x-mpegurl" + DefaultMimeMap[".wax"] = "audio/x-ms-wax" + DefaultMimeMap[".wma"] = "audio/x-ms-wma" + DefaultMimeMap[".ram"] = "audio/x-pn-realaudio" + DefaultMimeMap[".ra"] = "audio/x-pn-realaudio" + DefaultMimeMap[".rmp"] = "audio/x-pn-realaudio-plugin" + DefaultMimeMap[".cdx"] = "chemical/x-cdx" + DefaultMimeMap[".cif"] = "chemical/x-cif" + DefaultMimeMap[".cmdf"] = "chemical/x-cmdf" + DefaultMimeMap[".cml"] = "chemical/x-cml" + DefaultMimeMap[".csml"] = "chemical/x-csml" + DefaultMimeMap[".xyz"] = "chemical/x-xyz" + DefaultMimeMap[".bmp"] = "image/bmp" + DefaultMimeMap[".cgm"] = "image/cgm" + DefaultMimeMap[".g3"] = "image/g3fax" + DefaultMimeMap[".gif"] = "image/gif" + DefaultMimeMap[".ief"] = "image/ief" + DefaultMimeMap[".jpeg"] = "image/jpeg" + DefaultMimeMap[".jpg"] = "image/jpeg" + DefaultMimeMap[".jpe"] = "image/jpeg" + DefaultMimeMap[".png"] = "image/png" + DefaultMimeMap[".webp"] = "image/webp" + DefaultMimeMap[".heic"] = "image/heic" + DefaultMimeMap[".btif"] = "image/prs.btif" + DefaultMimeMap[".svg"] = "image/svg+xml" + DefaultMimeMap[".svgz"] = "image/svg+xml" + DefaultMimeMap[".tiff"] = "image/tiff" + DefaultMimeMap[".tif"] = "image/tiff" + DefaultMimeMap[".psd"] = "image/vnd.adobe.photoshop" + DefaultMimeMap[".djvu"] = "image/vnd.djvu" + DefaultMimeMap[".djv"] = "image/vnd.djvu" + DefaultMimeMap[".dwg"] = "image/vnd.dwg" + DefaultMimeMap[".dxf"] = "image/vnd.dxf" + DefaultMimeMap[".fbs"] = "image/vnd.fastbidsheet" + DefaultMimeMap[".fpx"] = "image/vnd.fpx" + DefaultMimeMap[".fst"] = "image/vnd.fst" + DefaultMimeMap[".mmr"] = "image/vnd.fujixerox.edmics-mmr" + DefaultMimeMap[".rlc"] = "image/vnd.fujixerox.edmics-rlc" + DefaultMimeMap[".mdi"] = "image/vnd.ms-modi" + DefaultMimeMap[".npx"] = "image/vnd.net-fpx" + DefaultMimeMap[".wbmp"] = "image/vnd.wap.wbmp" + DefaultMimeMap[".xif"] = "image/vnd.xiff" + DefaultMimeMap[".ras"] = "image/x-cmu-raster" + DefaultMimeMap[".cmx"] = "image/x-cmx" + DefaultMimeMap[".ico"] = "image/x-icon" + DefaultMimeMap[".pcx"] = "image/x-pcx" + DefaultMimeMap[".pic"] = "image/x-pict" + DefaultMimeMap[".pct"] = "image/x-pict" + DefaultMimeMap[".pnm"] = "image/x-portable-anymap" + DefaultMimeMap[".pbm"] = "image/x-portable-bitmap" + DefaultMimeMap[".pgm"] = "image/x-portable-graymap" + DefaultMimeMap[".ppm"] = "image/x-portable-pixmap" + DefaultMimeMap[".rgb"] = "image/x-rgb" + DefaultMimeMap[".xbm"] = "image/x-xbitmap" + DefaultMimeMap[".xpm"] = "image/x-xpixmap" + DefaultMimeMap[".xwd"] = "image/x-xwindowdump" + DefaultMimeMap[".eml"] = "message/rfc822" + DefaultMimeMap[".mime"] = "message/rfc822" + DefaultMimeMap[".mht"] = "message/rfc822" + DefaultMimeMap[".mhtml"] = "message/rfc822" + DefaultMimeMap[".igs"] = "model/iges" + DefaultMimeMap[".iges"] = "model/iges" + DefaultMimeMap[".msh"] = "model/mesh" + DefaultMimeMap[".mesh"] = "model/mesh" + DefaultMimeMap[".silo"] = "model/mesh" + DefaultMimeMap[".dwf"] = "model/vnd.dwf" + DefaultMimeMap[".gdl"] = "model/vnd.gdl" + DefaultMimeMap[".gtw"] = "model/vnd.gtw" + DefaultMimeMap[".mts"] = "model/vnd.mts" + DefaultMimeMap[".vtu"] = "model/vnd.vtu" + DefaultMimeMap[".wrl"] = "model/vrml" + DefaultMimeMap[".vrml"] = "model/vrml" + DefaultMimeMap[".ics"] = "text/calendar" + DefaultMimeMap[".ifb"] = "text/calendar" + DefaultMimeMap[".css"] = "text/css" + DefaultMimeMap[".csv"] = "text/csv" + DefaultMimeMap[".html"] = "text/html" + DefaultMimeMap[".htm"] = "text/html" + DefaultMimeMap[".txt"] = "text/plain" + DefaultMimeMap[".text"] = "text/plain" + DefaultMimeMap[".conf"] = "text/plain" + DefaultMimeMap[".def"] = "text/plain" + DefaultMimeMap[".list"] = "text/plain" + DefaultMimeMap[".log"] = "text/plain" + DefaultMimeMap[".in"] = "text/plain" + DefaultMimeMap[".dsc"] = "text/prs.lines.tag" + DefaultMimeMap[".rtx"] = "text/richtext" + DefaultMimeMap[".sgml"] = "text/sgml" + DefaultMimeMap[".sgm"] = "text/sgml" + DefaultMimeMap[".tsv"] = "text/tab-separated-values" + DefaultMimeMap[".t"] = "text/troff" + DefaultMimeMap[".tr"] = "text/troff" + DefaultMimeMap[".roff"] = "text/troff" + DefaultMimeMap[".man"] = "text/troff" + DefaultMimeMap[".me"] = "text/troff" + DefaultMimeMap[".ms"] = "text/troff" + DefaultMimeMap[".uri"] = "text/uri-list" + DefaultMimeMap[".uris"] = "text/uri-list" + DefaultMimeMap[".urls"] = "text/uri-list" + DefaultMimeMap[".fly"] = "text/vnd.fly" + DefaultMimeMap[".flx"] = "text/vnd.fmi.flexstor" + DefaultMimeMap[".3dml"] = "text/vnd.in3d.3dml" + DefaultMimeMap[".spot"] = "text/vnd.in3d.spot" + DefaultMimeMap[".jad"] = "text/vnd.sun.j2me.app-descriptor" + DefaultMimeMap[".wml"] = "text/vnd.wap.wml" + DefaultMimeMap[".wmls"] = "text/vnd.wap.wmlscript" + DefaultMimeMap[".s"] = "text/x-asm" + DefaultMimeMap[".asm"] = "text/x-asm" + DefaultMimeMap[".c"] = "text/x-c" + DefaultMimeMap[".cc"] = "text/x-c" + DefaultMimeMap[".cxx"] = "text/x-c" + DefaultMimeMap[".cpp"] = "text/x-c" + DefaultMimeMap[".h"] = "text/x-c" + DefaultMimeMap[".hh"] = "text/x-c" + DefaultMimeMap[".dic"] = "text/x-c" + DefaultMimeMap[".f"] = "text/x-fortran" + DefaultMimeMap[".for"] = "text/x-fortran" + DefaultMimeMap[".f77"] = "text/x-fortran" + DefaultMimeMap[".f90"] = "text/x-fortran" + DefaultMimeMap[".p"] = "text/x-pascal" + DefaultMimeMap[".pas"] = "text/x-pascal" + DefaultMimeMap[".java"] = "text/x-java-source" + DefaultMimeMap[".etx"] = "text/x-setext" + DefaultMimeMap[".uu"] = "text/x-uuencode" + DefaultMimeMap[".vcs"] = "text/x-vcalendar" + DefaultMimeMap[".vcf"] = "text/x-vcard" + DefaultMimeMap[".3gp"] = "video/3gpp" + DefaultMimeMap[".3g2"] = "video/3gpp2" + DefaultMimeMap[".h261"] = "video/h261" + DefaultMimeMap[".h263"] = "video/h263" + DefaultMimeMap[".h264"] = "video/h264" + DefaultMimeMap[".jpgv"] = "video/jpeg" + DefaultMimeMap[".jpm"] = "video/jpm" + DefaultMimeMap[".jpgm"] = "video/jpm" + DefaultMimeMap[".mj2"] = "video/mj2" + DefaultMimeMap[".mjp2"] = "video/mj2" + DefaultMimeMap[".mp4"] = "video/mp4" + DefaultMimeMap[".mp4v"] = "video/mp4" + DefaultMimeMap[".mpg4"] = "video/mp4" + DefaultMimeMap[".mpeg"] = "video/mpeg" + DefaultMimeMap[".mpg"] = "video/mpeg" + DefaultMimeMap[".mpe"] = "video/mpeg" + DefaultMimeMap[".m1v"] = "video/mpeg" + DefaultMimeMap[".m2v"] = "video/mpeg" + DefaultMimeMap[".qt"] = "video/quicktime" + DefaultMimeMap[".mov"] = "video/quicktime" + DefaultMimeMap[".fvt"] = "video/vnd.fvt" + DefaultMimeMap[".mxu"] = "video/vnd.mpegurl" + DefaultMimeMap[".m4u"] = "video/vnd.mpegurl" + DefaultMimeMap[".viv"] = "video/vnd.vivo" + DefaultMimeMap[".fli"] = "video/x-fli" + DefaultMimeMap[".wm"] = "video/x-ms-wm" + DefaultMimeMap[".wmv"] = "video/x-ms-wmv" + DefaultMimeMap[".wmx"] = "video/x-ms-wmx" + DefaultMimeMap[".wvx"] = "video/x-ms-wvx" + DefaultMimeMap[".avi"] = "video/x-msvideo" + DefaultMimeMap[".movie"] = "video/x-sgi-movie" + DefaultMimeMap[".ice"] = "x-conference/x-cooltalk" + DefaultMimeMap[".ipa"] = "application/vnd.iphone" + DefaultMimeMap[".apk"] = "application/vnd.android.package-archive" +} + +func GetMimeMap() map[string]string { + once.Do(LoadMimeMap) + return DefaultMimeMap +} diff --git a/bce-sdk-go/util/string.go b/bce-sdk-go/util/string.go new file mode 100644 index 0000000..3bb0b10 --- /dev/null +++ b/bce-sdk-go/util/string.go @@ -0,0 +1,88 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// string.go - define the string util function + +// Package util defines the common utilities including string and time. +package util + +import ( + "bytes" + "crypto/hmac" + "crypto/md5" + "crypto/rand" + "crypto/sha256" + "encoding/base64" + "encoding/hex" + "fmt" + "io" +) + +func HmacSha256Hex(key, str_to_sign string) string { + hasher := hmac.New(sha256.New, []byte(key)) + hasher.Write([]byte(str_to_sign)) + return hex.EncodeToString(hasher.Sum(nil)) +} + +func CalculateContentMD5(data io.Reader, size int64) (string, error) { + hasher := md5.New() + n, err := io.CopyN(hasher, data, size) + if err != nil { + return "", fmt.Errorf("calculate content-md5 occurs error: %v", err) + } + if n != size { + return "", fmt.Errorf("calculate content-md5 writing size %d != size %d", n, size) + } + return base64.StdEncoding.EncodeToString(hasher.Sum(nil)), nil +} + +func UriEncode(uri string, encodeSlash bool) string { + var byte_buf bytes.Buffer + for _, b := range []byte(uri) { + if (b >= 'A' && b <= 'Z') || (b >= 'a' && b <= 'z') || (b >= '0' && b <= '9') || + b == '-' || b == '_' || b == '.' || b == '~' || (b == '/' && !encodeSlash) { + byte_buf.WriteByte(b) + } else { + byte_buf.WriteString(fmt.Sprintf("%%%02X", b)) + } + } + return byte_buf.String() +} + +func NewUUID() string { + var buf [16]byte + for { + if _, err := rand.Read(buf[:]); err == nil { + break + } + } + buf[6] = (buf[6] & 0x0f) | (4 << 4) + buf[8] = (buf[8] & 0xbf) | 0x80 + + res := make([]byte, 36) + hex.Encode(res[0:8], buf[0:4]) + res[8] = '-' + hex.Encode(res[9:13], buf[4:6]) + res[13] = '-' + hex.Encode(res[14:18], buf[6:8]) + res[18] = '-' + hex.Encode(res[19:23], buf[8:10]) + res[23] = '-' + hex.Encode(res[24:], buf[10:]) + return string(res) +} + +func NewRequestId() string { + return NewUUID() +} diff --git a/bce-sdk-go/util/time.go b/bce-sdk-go/util/time.go new file mode 100644 index 0000000..e9f9e3d --- /dev/null +++ b/bce-sdk-go/util/time.go @@ -0,0 +1,46 @@ +/* + * Copyright 2017 Baidu, Inc. + * + * 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. + */ + +// time.go - define the time utility functions for BCE + +package util + +import "time" + +const ( + RFC822Format = "Mon, 02 Jan 2006 15:04:05 MST" + ISO8601Format = "2006-01-02T15:04:05Z" +) + +func NowUTCSeconds() int64 { return time.Now().UTC().Unix() } + +func NowUTCNanoSeconds() int64 { return time.Now().UTC().UnixNano() } + +func FormatRFC822Date(timestamp_second int64) string { + tm := time.Unix(timestamp_second, 0).UTC() + return tm.Format(RFC822Format) +} + +func ParseRFC822Date(time_string string) (time.Time, error) { + return time.Parse(RFC822Format, time_string) +} + +func FormatISO8601Date(timestamp_second int64) string { + tm := time.Unix(timestamp_second, 0).UTC() + return tm.Format(ISO8601Format) +} + +func ParseISO8601Date(time_string string) (time.Time, error) { + return time.Parse(ISO8601Format, time_string) +} diff --git a/cce-network-v2/GO_VERSION b/cce-network-v2/GO_VERSION index bfb47ce..d0d9d7c 100644 --- a/cce-network-v2/GO_VERSION +++ b/cce-network-v2/GO_VERSION @@ -1 +1 @@ -go version go1.21.5 linux/amd64 +go version go1.22.0 linux/amd64 diff --git a/cce-network-v2/Makefile b/cce-network-v2/Makefile index 13994d9..597caf1 100644 --- a/cce-network-v2/Makefile +++ b/cce-network-v2/Makefile @@ -193,8 +193,6 @@ tags: $(GOLANG_SRCFILES) $(BPF_SRCFILES) cscope.files ## Generate tags for Go an clean: ## Perform overall cleanup for CCE. -$(QUIET) for i in $(SUBDIRS); do $(MAKE) $(SUBMAKEOPTS) -C $$i clean; done - -$(QUIET) $(MAKE) $(SUBMAKEOPTS) -C ./contrib/packaging/deb clean - -$(QUIET) $(MAKE) $(SUBMAKEOPTS) -C ./contrib/packaging/rpm clean veryclean: ## Perform complete cleanup for container engine images(including build cache). -$(QUIET) $(CONTAINER_ENGINE) image prune -af @@ -220,13 +218,13 @@ docker-arm: image-suffix = -arm64 docker-arm: $(DOCKER_IMAGES) # use docker build base on profile variable -ifeq ($(PROFILE), dev) -# build docker image with native arch when profile is dev +# build docker image for amd64 and arm64 when GOARCH is amd64 and arm64 +ifeq ($(GOARCH), amd64) +# for amd64 $(DOCKER_IMAGES): build docker build -t registry.baidubce.com/cce-plugin-$(PROFILE)/$(@):$(VERSION) -f deploy/dockerfile/$(@).Dockerfile . docker push registry.baidubce.com/cce-plugin-$(PROFILE)/$(@):$(VERSION) else -# build docker image for amd64 and arm64 when prifile is pro # for amd64 $(DOCKER_IMAGES): build echo "GOARCH=$(GOARCH)" diff --git a/cce-network-v2/cmd/Makefile b/cce-network-v2/cmd/Makefile index 631a1b9..fc25495 100644 --- a/cce-network-v2/cmd/Makefile +++ b/cce-network-v2/cmd/Makefile @@ -19,7 +19,7 @@ $(TARGET): clean: @$(ECHO_CLEAN) - $(QUIET)rm -f $(TARGETS) + $(forea target, $(QUIET)rm -f $(PWD)/output/bin/cmd/$(target)) $(GO) clean $(GOCLEAN) install: diff --git a/cce-network-v2/cmd/agent/cmd/daemon.go b/cce-network-v2/cmd/agent/cmd/daemon.go index 80fcfde..42f16c7 100644 --- a/cce-network-v2/cmd/agent/cmd/daemon.go +++ b/cce-network-v2/cmd/agent/cmd/daemon.go @@ -165,19 +165,6 @@ func NewDaemon(ctx context.Context, cancel context.CancelFunc) (*Daemon, error) return nil, fmt.Errorf("invalid daemon configuration: %s", err) } - if option.Config.ReadCNIConfiguration != "" { - netConf, err = cnitypes.ReadNetConf(option.Config.ReadCNIConfiguration) - if err != nil { - log.WithError(err).Error("Unable to read CNI configuration") - return nil, fmt.Errorf("unable to read CNI configuration: %w", err) - } - - if netConf.MTU != 0 { - configuredMTU = netConf.MTU - log.WithField("mtu", configuredMTU).Info("Overwriting MTU based on CNI configuration") - } - } - set, err := rate.NewAPILimiterSet(option.Config.APIRateLimit, apiRateLimitDefaults, rate.SimpleMetricsObserver) if err != nil { log.WithError(err).Error("unable to configure API rate limiting") diff --git a/cce-network-v2/cmd/agent/cmd/daemon_main.go b/cce-network-v2/cmd/agent/cmd/daemon_main.go index b1f7795..1b98e64 100644 --- a/cce-network-v2/cmd/agent/cmd/daemon_main.go +++ b/cce-network-v2/cmd/agent/cmd/daemon_main.go @@ -27,6 +27,7 @@ import ( "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/api/v1/server" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/api/v1/server/restapi" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/plugins/pluginmanager" "github.com/go-openapi/loads" gops "github.com/google/gops/agent" "github.com/sirupsen/logrus" @@ -360,9 +361,6 @@ func initializeFlags() { flags.String(option.IPv4NodeAddr, "auto", "IPv4 address of node") option.BindEnv(option.IPv4NodeAddr) - flags.String(option.ReadCNIConfiguration, "", "Read to the CNI configuration at specified path to extract per node configuration") - option.BindEnv(option.ReadCNIConfiguration) - flags.Bool(option.Restore, true, "Restores state, if possible, from previous daemon") option.BindEnv(option.Restore) @@ -424,12 +422,9 @@ func initializeFlags() { flags.MarkHidden(option.EndpointGCInterval) option.BindEnv(option.EndpointGCInterval) - flags.String(option.WriteCNIConfigurationWhenReady, "", fmt.Sprintf("Write the CNI configuration as specified via --%s to path when agent is ready", option.ReadCNIConfiguration)) + flags.String(option.WriteCNIConfigurationWhenReady, "", "Write the CNI configuration as specified path when agent is ready") option.BindEnv(option.WriteCNIConfigurationWhenReady) - flags.Bool(option.OverwriteCNIConfigurationWhenStart, true, "Overwrite the CNI configuration when agent starts") - option.BindEnv(option.OverwriteCNIConfigurationWhenStart) - flags.Duration(option.K8sHeartbeatTimeout, 30*time.Second, "Configures the timeout for api-server heartbeat, set to 0 to disable") option.BindEnv(option.K8sHeartbeatTimeout) @@ -500,6 +495,9 @@ func initializeFlags() { flags.Bool(option.EnableEgressPriorityDSCP, false, "enable engress priority by dscp") option.BindEnv(option.EnableEgressPriorityDSCP) + flags.StringSlice(option.ExtCNIPluginsList, []string{}, "external cni plugins list") + option.BindEnv(option.ExtCNIPluginsList) + viper.BindPFlags(flags) } @@ -678,34 +676,19 @@ func runDaemon() { log.WithField("bootstrapTime", time.Since(bootstrapTimestamp)). Info("Daemon initialization completed") - firstWriteCNIConfig := false - if option.Config.OverwriteCNIConfigurationWhenStart { - firstWriteCNIConfig = true - } if option.Config.WriteCNIConfigurationWhenReady != "" { d.controllers.UpdateController(cniUpdateControllerName, controller.ControllerParams{ RunInterval: option.Config.ResourceResyncInterval, DoFunc: func(ctx context.Context) error { // Overwrite the CNI configuration when agent starts, so we should skip read config file which has been existed. - if !firstWriteCNIConfig { - _, err = os.Open(option.Config.WriteCNIConfigurationWhenReady) - if err == nil { - return nil - } - } - firstWriteCNIConfig = false - input, err := os.ReadFile(option.Config.ReadCNIConfiguration) + override, err := pluginmanager.OverwriteCNIConfigList(option.Config.WriteCNIConfigurationWhenReady) if err != nil { - log.WithError(err).Fatal("Unable to read CNI configuration file") + log.WithError(err).Error("Unable to overwrite CNI configuration") } - - if err = os.WriteFile(option.Config.WriteCNIConfigurationWhenReady, input, 0644); err != nil { - log.WithError(err).Fatalf("Unable to write CNI configuration file to %s", option.Config.WriteCNIConfigurationWhenReady) - } else { - log.Infof("Wrote CNI configuration file to %s", option.Config.WriteCNIConfigurationWhenReady) + if override { + log.Infof("Overwrite CNI configuration file to %s", option.Config.WriteCNIConfigurationWhenReady) } - return nil }, }) diff --git a/cce-network-v2/deploy/cce-network-v2/Chart.yaml b/cce-network-v2/deploy/cce-network-v2/Chart.yaml index f75b394..7fc451e 100644 --- a/cce-network-v2/deploy/cce-network-v2/Chart.yaml +++ b/cce-network-v2/deploy/cce-network-v2/Chart.yaml @@ -15,10 +15,10 @@ type: application # This is the chart version. This version number should be incremented each time you make changes # to the chart and its templates, including the app version. # Versions are expected to follow Semantic Versioning (https://semver.org/) -version: 2.9.1 +version: 2.10.0 # This is the version number of the application being deployed. This version number should be # incremented each time you make changes to the application. Versions are not expected to # follow Semantic Versioning. They should reflect the version the application is using. # It is recommended to use it with quotes. -appVersion: "2.9.1" +appVersion: "2.10.0" diff --git a/cce-network-v2/deploy/cce-network-v2/templates/cni-config-template.yaml b/cce-network-v2/deploy/cce-network-v2/templates/cni-config-template.yaml deleted file mode 100644 index 8bd9403..0000000 --- a/cce-network-v2/deploy/cce-network-v2/templates/cni-config-template.yaml +++ /dev/null @@ -1,48 +0,0 @@ -apiVersion: v1 -kind: ConfigMap -metadata: - labels: - addonmanager.kubernetes.io/mode: EnsureExists - name: cni-config-template - namespace: {{ .Release.Namespace }} -data: - primary-eni.temlplate: | - { - "name":"podlink", - "cniVersion":"0.4.0", - "plugins":[ - { - "type":"exclusive-device", - "ipam":{ - "type":"enim" - } - } - {{- range .Values.extplugins }} - ,{ - "type": "{{ .type }}" - } - {{- end }} - ] - } - cce-ptp.template: | - { - "name":"cce", - "cniVersion":"0.4.0", - "plugins":[ - { - "type":"cptp", - "ipam":{ - "type":"cipam", - }, - "mtu": {{ .Values.ccedConfig.mtu }} - } - {{- range .Values.extplugins }} - ,{ - "type": "{{ .type }}" - } - {{- end }} - ,{ - "type": "endpoint-probe" - } - ] - } diff --git a/cce-network-v2/deploy/cce-network-v2/templates/ds-agent.yaml b/cce-network-v2/deploy/cce-network-v2/templates/ds-agent.yaml index 8ca35d0..6b9bcc2 100644 --- a/cce-network-v2/deploy/cce-network-v2/templates/ds-agent.yaml +++ b/cce-network-v2/deploy/cce-network-v2/templates/ds-agent.yaml @@ -77,9 +77,6 @@ spec: name: etc-host - mountPath: /lib/modules name: lib-modules - - mountPath: /etc/cce/cni-config-template - readOnly: true - name: cni-config-template ports: - name: healthz containerPort: 19879 @@ -147,10 +144,6 @@ spec: path: network-v2-config.yaml name: cce-network-v2-config name: cce-network-v2-config - - configMap: - defaultMode: 420 - name: cni-config-template - name: cni-config-template {{- with .Values.tolerations }} tolerations: @@ -163,5 +156,5 @@ spec: updateStrategy: rollingUpdate: - maxUnavailable: 1 + maxUnavailable: 10 type: RollingUpdate \ No newline at end of file diff --git a/cce-network-v2/deploy/cce-network-v2/values.yaml b/cce-network-v2/deploy/cce-network-v2/values.yaml index f7e2cf7..0215e65 100644 --- a/cce-network-v2/deploy/cce-network-v2/values.yaml +++ b/cce-network-v2/deploy/cce-network-v2/values.yaml @@ -138,9 +138,7 @@ ccedConfig: {"syslog.level":"info","syslog.facility":"local5"} # cni 配置,从指定文件读取,写入到另一个路径 - read-cni-conf: "" write-cni-conf-when-ready: "" - overwrite-cni-conf: true # ipam 模式. privatecloudbase: 私有云底座;vpc-eni: BCE VPC ENI @@ -207,4 +205,10 @@ ccedConfig: bcecloud/apis/v1/CreateENI: "rate-limit:5/1s,rate-burst:5,max-wait-duration:30s,parallel-requests:5,log:true" bcecloud/apis/v1/DescribeSubnet: "rate-limit:5/1s,rate-burst:5,max-wait-duration:30s,parallel-requests:5" bcecloud/apis/v1/StatENI: "rate-limit:10/1s,rate-burst:15,max-wait-duration:30s,parallel-requests:10" - # cni 接口限流 \ No newline at end of file + # cni 接口限流 + # 扩展插件列表 + ext-cni-plugins: + - "portmap" + - "endpoint-probe" + # - "cilium-cni" + # - "portmap" \ No newline at end of file diff --git a/cce-network-v2/deploy/dockerfile/cce-network-agent.Dockerfile-arm64 b/cce-network-v2/deploy/dockerfile/cce-network-agent.Dockerfile-arm64 index e2db3c4..1502ca2 100644 --- a/cce-network-v2/deploy/dockerfile/cce-network-agent.Dockerfile-arm64 +++ b/cce-network-v2/deploy/dockerfile/cce-network-agent.Dockerfile-arm64 @@ -10,7 +10,7 @@ WORKDIR /home/cce COPY output/bin/cmd/agent /bin/agent # install cni binaries -COPY tools/cni /cni +COPY tools/cni-arm /cni COPY output/bin/plugins /cni COPY deploy/dockerfile/install-cni.sh install-cni.sh diff --git a/cce-network-v2/docs/other/private-cloud-base.md b/cce-network-v2/docs/other/private-cloud-base.md index fcda93d..d60d5f7 100644 --- a/cce-network-v2/docs/other/private-cloud-base.md +++ b/cce-network-v2/docs/other/private-cloud-base.md @@ -103,7 +103,7 @@ ccedConfig: #### 下载最新安装包代码库 ``` # 下载安装包 -git clone https://github.com/baidubce/baiducloud-cce-cni-driver.git cce-network-plugin +git clone ssh://wangweiwei22@icode.baidu.com:8235/baidu/jpaas/cce-network-plugin baidu/jpaas/cce-network-plugin cd cce-network-plugin/cce-ipam-v2 ``` @@ -274,4 +274,4 @@ status: ipv4: 172.16.8.206 node: vm-13atpvfs-cn-taiyuan-un-fpdpo state: restoring -``` +``` \ No newline at end of file diff --git a/cce-network-v2/docs/release.md b/cce-network-v2/docs/release.md index 93185b3..5b3ef5f 100644 --- a/cce-network-v2/docs/release.md +++ b/cce-network-v2/docs/release.md @@ -6,6 +6,11 @@ v2 版本新架构,支持VPC-ENI 辅助IP和vpc路由。版本发布历史如 1. [Feature] VPC-ENI 支持自动获取节点 eni 配额信息,去掉了自定义 ENI 配额的参数。 2. [Feature] VPC-ENI 支持 ebc 主网卡辅助 IP 模式 3. [Feature] VPC-ENI bbc 升级为主网卡辅助 IP 模式 +4. [Opimize] 增加 CNI 插件日志持久化 +5. [Feature] 重构 CNI 配置文件管理逻辑,支持保留自定义 CNI 插件配置 +6. [Feature] 增加对portmap 插件的支持,默认开启 +7. [BUG] 修复arm64架构下,cni 插件无法执行的问题 +8. [Opimize] 增加 BCE SDK 日志持久化 ### 2.9 (2023/11/10) 新特性功能: diff --git a/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-0.jpg b/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-0.jpg new file mode 100644 index 0000000..34e535e Binary files /dev/null and b/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-0.jpg differ diff --git a/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-1.jpg b/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-1.jpg new file mode 100644 index 0000000..50faa7a Binary files /dev/null and b/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-1.jpg differ diff --git a/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-2.jpg b/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-2.jpg new file mode 100644 index 0000000..9816aa5 Binary files /dev/null and b/cce-network-v2/docs/vpc-eni/images/scale-cluster-bbc-2.jpg differ diff --git a/cce-network-v2/docs/vpc-eni/primary-interface-with-secondary-ip.md b/cce-network-v2/docs/vpc-eni/primary-interface-with-secondary-ip.md new file mode 100644 index 0000000..9d97a39 --- /dev/null +++ b/cce-network-v2/docs/vpc-eni/primary-interface-with-secondary-ip.md @@ -0,0 +1,169 @@ +# 主网卡辅助 IP 模式 +为了达到简单且一致的产品体验,主网卡辅助 IP 模式在不支持 ENI 的机型上,例如 BBC 和部分 EBC 机型,可以利用在主网卡上配置辅助 IP 的方式,实现每个 Pod 都有一个原生于 VPC 的 IP 地址身份的能力。 + +## 优势 +主网卡辅助 IP 模式,在主网卡上配置辅助 IP,然后通过 ENI 的 SecondaryIP 特性,将辅助 IP 绑定到 ENI。辅助 IP 与网卡的主 IP 使用相同的子网,因此可以保证辅助 IP 与主 IP 在 VPC 中的同等地位。 +与 ENI 辅助 IP 模式相比,主网卡辅助 IP 模式下舍弃了策略路由能力,因此这种模式的数据路径更为简洁易懂。且在主网卡辅助 IP 模式下,可以支持所有机型,拥有更强的兼容性。 + +## 使用限制 +* **请保证实例所在子网 IP 地址空间充足**,至少预留 n * c 个辅助 IP 地址容量的子网空间。 + * n 是所有机器的数量。 + * c 是每个机器最大可分配辅助 IP 数量。 + * 子网容量应在购买机器前提前规划,一旦机器加入集群,无法再修改子网。 +* BBC/EBC 每个实例最多支持 39 个辅助 IP 地址。当节点调度了超过 39 个 Pod 时,CNI 无法为 Pod 分配 IP 地址。 +* 节点加入 CCE 集群前,请确保是纯净的节点,即节点上没有运行过任何容器。推荐将节点执行操作系统重装。 +* 使用 VPC-ENI 模式,推荐内核版本为 5.7 以上。 + +# 实现原理 +主网卡辅助 IP 模式在技术实现上为 ENI 增加了一种新的使用模式 `PrimaryWithSecondaryIP` 。BBC 机型默认使用这种模式,而 EBC 机型则根据百度云 EBC 产品的定义,自动决策使用 `PrimaryWithSecondaryIP` 还是 `Secondary`。 +## BBC 机型案例 +BBC 机型默认使用 `PrimaryWithSecondaryIP` 模式,其网络集合对象实例如下: + +```yaml +apiVersion: cce.baidubce.com/v2 +kind: NetResourceSet +metadata: + annotations: + cce.baidubce.com/ip-resource-capacity-synced: "2024-02-21T02:26:28Z" + generation: 3 + labels: + beta.kubernetes.io/arch: amd64 + beta.kubernetes.io/instance-gpu: "false" + beta.kubernetes.io/instance-type: BBC + beta.kubernetes.io/os: linux + cce.baidubce.com/baidu-cgpu-priority: "false" + cce.baidubce.com/gpu-share-device-plugin: disable + cce.baidubce.com/kubelet-dir: 2f7661722f6c69622f6b7562656c6574 + cluster-id: cce-z85m1xdk + cluster-role: node + failure-domain.beta.kubernetes.io/region: bj + name: 10.0.19.7 + ownerReferences: + - apiVersion: v1 + kind: Node + name: 10.0.19.7 + uid: 45341763-2b46-472b-884e-695974a67eaf + resourceVersion: "13952347" + uid: d479844c-5519-4d08-a7bc-f850179d3311 +spec: + addresses: + - ip: 10.0.19.7 + type: InternalIP + eni: + availability-zone: zoneD + instance-type: bbc + maxAllocateENI: 1 + maxIPsPerENI: 40 + preAllocateENI: 0 + useMode: Secondary + vpc-id: vpc-w829y8wpni8i + instance-id: i-1SvcOgBl + ipam: + pool: + 10.0.19.8: + resource: eni-ih1seearb7y8 + subnetID: sbn-kx327kp355ni + 10.0.19.9: + resource: eni-ih1seearb7y8 + subnetID: sbn-kx327kp355ni + 10.0.19.10: + resource: eni-ih1seearb7y8 + subnetID: sbn-kx327kp355ni + 10.0.19.11: + resource: eni-ih1seearb7y8 + subnetID: sbn-kx327kp355ni +status: + enis: + eni-ih1seearb7y8: + cceStatus: ReadyOnNode + id: eni-ih1seearb7y8 + subnetId: sbn-kx327kp355ni + vpcStatus: inuse + ipam: + operator-status: {} + used: + 10.0.19.10: + owner: kube-system/nfd-worker-f244k + resource: eni-ih1seearb7y8 + subnetID: sbn-kx327kp355ni +``` + +上面的实例中,以下字段域需要注意: +* `spec.eni.useMode` 字段为 `Secondary`,表示使用 ENI 辅助 IP 模式。 +* `spec.eni.instance-type` 字段为 `bbc`,表示使用 BBC 机型。 +* `spec.eni.maxIPsPerENI` 字段为 40,表示每个 ENI 的最大辅助 IP 数量 +* `status.enis.eni-ih1seearb7y8` 代表一个 ENI 对象,其中 `id` 为 ENI ID,`subnetId` 为子网 ID。百度云每个主机的主网卡,也是一个抽象的 ENI 对象。 + +### BBC ENI 实例 +BBC 实例的 ENI 对象示例如下: +```yaml +apiVersion: cce.baidubce.com/v2 +kind: ENI +metadata: + creationTimestamp: "2024-02-21T02:26:28Z" + finalizers: + - eni-syncer + generation: 2 + labels: + cce.baidubce.com/eni-type: bbc + cce.baidubce.com/instanceid: i-1SvcOgBl + cce.baidubce.com/node: 10.0.19.7 + cce.baidubce.com/vpc-id: vpc-w829y8wpni8i + name: eni-ih1seearb7y8 + ownerReferences: + - apiVersion: cce.baidubce.com/v2 + kind: NetResourceSet + name: 10.0.19.7 + uid: d479844c-5519-4d08-a7bc-f850179d3311 + resourceVersion: "13952271" + uid: 0d1631b9-68ff-42d0-a1b0-dcb9922fd55f +spec: + id: eni-ih1seearb7y8 + instanceID: i-1SvcOgBl + macAddress: fa:20:20:31:4e:53 + name: eth0 + nodeName: 10.0.19.7 + privateIPSet: + - primary: true + privateIPAddress: 10.0.19.7 + subnetID: sbn-kx327kp355ni + - privateIPAddress: 10.0.19.10 + subnetID: sbn-kx327kp355ni + - privateIPAddress: 10.0.19.11 + subnetID: sbn-kx327kp355ni + - privateIPAddress: 10.0.19.8 + subnetID: sbn-kx327kp355ni + - privateIPAddress: 10.0.19.9 + subnetID: sbn-kx327kp355ni + subnetID: sbn-kx327kp355ni + type: bbc + useMode: PrimaryWithSecondaryIP + vpcID: vpc-w829y8wpni8i + vpcVersion: 1 + zoneName: cn-bj-d +status: + CCEStatus: ReadyOnNode + CCEStatusChangeLog: + - CCEStatus: ReadyOnNode + code: ok + time: "2024-02-21T02:26:47Z" + VPCStatus: inuse + VPCStatusChangeLog: + - VPCStatus: inuse + code: ok + time: "2024-02-21T02:26:28Z" + interfaceIndex: 2 + interfaceName: eth0 + vpcVersion: 1 +``` + +上面的实例中,以下字段域需要注意: +* `spec.useMode` 字段为 `PrimaryWithSecondaryIP`,表示使用主网卡辅助 IP 模式。 +* `spec.type` 字段为 `bbc`,表示使用 BBC 机型。 +* `spec.subnetID` 字段为 ENI 的子网 ID。ENI 的主 IP 一旦确定,子网 ID 不可变更。 +* `spec.privateIPSet` 字段为 ENI 的辅助 IP 列表,其中 `primary: true` 表示该 IP 为主IP. +* `status.interfaceIndex` 字段为 ENI 的接口的网卡设备索引。 +* `status.interfaceName` 字段为 ENI 的接口名称。 +* `status.vpcVersion` 字段为 VPC 的版本号,用于与 VPC 做状态同步使用,默认每 20s 与 VPC 做一次状态同步。 +* `status.VPCStatus` 字段为 VPC 的状态,`inuse` 表示 VPC 记录的网卡可用且在使用中。 +* `status.CCEStatus` 字段为CCE的单机引擎记录的 ENI 状态,`ReadyOnNode` 表示 ENI 记录的网卡可用且在使用中。 diff --git a/cce-network-v2/docs/vpc-eni/vpc-eni-cluster-add-bbc.md b/cce-network-v2/docs/vpc-eni/vpc-eni-cluster-add-bbc.md new file mode 100644 index 0000000..b81084b --- /dev/null +++ b/cce-network-v2/docs/vpc-eni/vpc-eni-cluster-add-bbc.md @@ -0,0 +1,85 @@ +# VPC-ENI 集群添加 BBC 节点操作案例 +## 1. 背景信息 +本案例介绍如何添加一个 VPC-ENI 集群的 BBC 节点。在 CCE 限制内,通过自定义参数扩容集群的方法,将 BBC 节点添加到集群中。 +### 1.1 使用限制 +* 请确认已有节点和集群在同一个 VPC 中。 +* 请确认已有节点所在的子网有足够的空闲 IP 资源,请提前做好资源规划。 + * 加入到 CCE 集群的 BBC 节点最多需要分配 40 个 IP 地址 + * BBC 节点最大仅允许创建 39 个使用独立 IP 地址的容器 +* 一个计算实例最多只能加入一个集群。移除集群后,建议重装操作系统以清理相关残留配置。 +* 请确认在节点加入集群前已经完成了重装操作系统操作,推荐内核版本为 5.7 以上。 +## 2. 操作步骤 +### 2.1 CCE 集群添加节点 +请进入 CCE 控制台,在集群列表中,找到目标集群,点击集群名称,进入集群节点管理页面。 +![点击添加节点按钮](./images/scale-cluster-bbc-0.jpg) +### 2.2 使用自定义参数扩容集群 +点击“使用自定义参数扩容集群”链接,进入自定义参数扩容集群页面。 +![点击使用自定义参数扩容集群按钮](./images/scale-cluster-bbc-1.jpg) +接着会自动弹出出入框,请将以下内容复制到输入框中。 +![复制自定义参数](./images/scale-cluster-bbc-2.jpg) + +### 2.3 自定义参数扩容集群 +在自定义参数扩容集群的输入框中,可以通过以下内容模板,替换关键的实例名和密码信息,将已有的 BBC 节点添加到集群中。 + +```json +[ + { + "instanceSpec": { + "adminPassword": "***", + "existed": true, + "existedOption": { + "existedInstanceID": "i-qke6VO0K", + "rebuild": false + }, + "machineType": "BBC", + "clusterRole": "node", + "deployCustomConfig": { + "kubeletRootDir": "/var/lib/kubelet", + "preUserScript": "", + "postUserScript": "", + "enableCordon": false, + "kubeReserved": { + "cpu": "50m", + "memory": "100Mi" + }, + "systemReserved": { + "cpu": "50m", + "memory": "100Mi" + }, + "relationTag": true, + "containerdConfig": { + "dataRoot": "/home/cce/containerd" + } + }, + "instanceResource": { + "cdsList": [] + }, + "vpcConfig": { + "securityGroupType": "normal", + "securityGroup": { + "customSecurityGroups": [], + "enableCCERequiredSecurityGroup": true, + "enableCCEOptionalSecurityGroup": false + } + }, + "labels": { + "cce.baidubce.com/gpu-share-device-plugin": "disable", + "cce.baidubce.com/baidu-cgpu-priority": "false" + }, + "tags": [], + "taints": [], + "relationTag": true, + "instanceOS": { + "imageType": "System" + }, + } + } +] +``` + +上述模板中,需要替换的关键信息如下: +* `adminPassword`: 必须字段。主机密码,请使用符合密码规则的字符串。如果密码不正确,会导致主机无法加入集群。 +* `existedInstanceID`: 必须字段。待加入集群的节点 ID。请在 弹性裸金属服务器 -> 控制台 -> 实例列表 中,找到待加入集群的节点 ID。 +* `taints`: 可选字段。节点污点标签,请根据需要填写。 +* `labels`: 可选字段。节点标签,请根据需要填写。 +* `deployCustomConfig`: 可选字段。节点自定义配置,请根据需要填写。 diff --git a/cce-network-v2/docs/vpc-eni/vpc-eni.md b/cce-network-v2/docs/vpc-eni/vpc-eni.md index 3b04910..7a46a6e 100644 --- a/cce-network-v2/docs/vpc-eni/vpc-eni.md +++ b/cce-network-v2/docs/vpc-eni/vpc-eni.md @@ -228,6 +228,7 @@ VPC-ENI 模式使用限制如下: * 单网卡上IP数量最少1个,最多40个。 * 云主机可挂载弹性网卡数量=min(主机核数,8)。 * 云主机绑定的网卡上可配置IP数量。 +* 注意 BBC 和部分 EBC 机型不支持挂载 ENI。 详情查看[主网卡辅助 IP 模式](primary-interface-with-secondary-ip.md) | 内存 | IP数量| | -- | -- | @@ -235,4 +236,8 @@ VPC-ENI 模式使用限制如下: |(1-8]G | 8 | | (8-32]G | 16 | | (32-64]G | 30 | -| 大于64G | 40 | \ No newline at end of file +| 大于64G | 40 | + +## 2.3 操作系统限制 +* 节点加入 CCE 集群前,请确保是纯净的节点,即节点上没有运行过任何容器。推荐将节点执行操作系统重装。 +* 使用 VPC-ENI 模式,推荐内核版本为 5.7 以上。 \ No newline at end of file diff --git a/cce-network-v2/docs/vpc-route/vpc-route.md b/cce-network-v2/docs/vpc-route/vpc-route.md index 0257a26..65c9ee9 100644 --- a/cce-network-v2/docs/vpc-route/vpc-route.md +++ b/cce-network-v2/docs/vpc-route/vpc-route.md @@ -1,6 +1,21 @@ # VPC Route 网络 -## 1 关键数据结构 -### 1.1 NetResourceSet +## 1. 功能简介 +VPC-Route 模式,将容器IP分配给VPC路由表,通过VPC路由转发到Pod IP。这种模式的容器网络有以下特点: +* 容器IP范围和 VPC CIDR 范围不同,但是 VPC 内所有实例可以访问容器IP。 +* 单机容器 IP 数量无限,可以灵活的扩容。VPC 路由模式的容器网络,每个节点上可以分配一个或多个 CIDR,每个节点上可以分配的容器IP数量是节点上多个 CIDR 的可用 IP 数量。 +* 使用分布式 IPAM,节点和容器弹性能力强。 +* 性能较高,容器使用 underlay 网络无额外封装性能损耗。 + +> VPC 路由模式的容器网络每个节点都有独立的 CIDR,所以不支持固定 IP 等网络特性。 +## 2. 使用限制 +### 2.1 操作系统限制 +* 节点加入 CCE 集群前,请确保是纯净的节点,即节点上没有运行过任何容器。推荐将节点执行操作系统重装。 +* 使用 VPC-ENI 模式,推荐内核版本为 5.7 以上。 +### 2.2 规格限制 +1. 默认每个VPC的路由表条目最多50条。可以通过配额中心申请提高配额。 + +## 3 关键数据结构 +### 3.1 NetResourceSet ``` apiVersion: cce.baidubce.com/v2 kind: NetResourceSet @@ -46,7 +61,7 @@ status: * * `status.ipam.vpc-router-cidrs`:PodCIDR和VPC路由表之间的同步状态。 -### 1.2 CCEEndpoint +### 3.2 CCEEndpoint ``` apiVersion: cce.baidubce.com/v2 kind: CCEEndpoint @@ -87,18 +102,18 @@ apiVersion: cce.baidubce.com/v2 ``` CCEEndpoint 记录了网络端点的状态信息。 -## 2 控制逻辑 -### 2.1 节点就绪 +## 4 控制逻辑 +### 4.1 节点就绪 只有所有CIDR成功写入VPC路由,节点才就绪。 如果CIDR未成功写入VPC路由,则cce-network-v2-agent Pod的健康检查会失败,并有以下日志: ``` level=error msg="fail to health check manager" error="cluster-pool-watcher's health plugin check failed:no VPCRouteCIDRs have been received yet" subsys=daemon-health ``` -## 3 数据面 +## 5 数据面 vpc 路由使用cptp网络驱动,它具备以下特征。 -### 3.1 容器内 -#### 3.1.1 容器地址 +### 5.1 容器内 +#### 5.1.1 容器地址 使用32/128位的地址,不归属任何子网。 ``` # ip addr @@ -112,7 +127,7 @@ vpc 路由使用cptp网络驱动,它具备以下特征。 valid_lft forever preferred_lft forever ``` -#### 3.1.2 容器路由 +#### 5.1.2 容器路由 ``` # ip route default via 172.10.3.9 dev eth0 @@ -121,15 +136,15 @@ default via 172.10.3.9 dev eth0 ``` 值得注意的是网关地址是宿主机端veth的地址。这个地址是 cce-network-v2-agent 在Pod CIDR中申请的。该机器上所有的容器都使用这个gateway地址。且机器重启后,路由地址不变。 -#### 3.1.3 邻居信息 +#### 5.1.3 邻居信息 容器内只有一条邻居信息,即默认网关的地址。mac地址是host端的veth的地址。 ``` # ip neigh 172.10.3.9 dev eth0 lladdr 06:c5:90:3b:4d:6d PERMANENT ``` -### 3.2 宿主机 -#### 3.2.1 宿主机veth地址 +### 5.2 宿主机 +#### 5.2.1 宿主机veth地址 宿主机上,每个veth的地址都是默认网关的地址 ``` # ip addr @@ -140,7 +155,7 @@ default via 172.10.3.9 dev eth0 inet6 fe80::4c5:90ff:fe3b:4d6d/64 scope link valid_lft forever preferred_lft forever ``` -#### 3.2.2 路由 +#### 5.2.2 路由 ``` # ip r default via 192.168.10.1 dev eth0 @@ -149,7 +164,7 @@ default via 192.168.10.1 dev eth0 172.10.3.21 dev vethda5db5af scope host ``` 宿主机上有一条到容器的路由,关联到host上的veth设备,scope为host。 -#### 3.2.3 邻居表项 +#### 5.2.3 邻居表项 宿主机上有一条到容器的静态邻居表,关联到host上的veth设备,mac地址是容器内的mac地址。 ``` # ip neigh diff --git a/cce-network-v2/pkg/bce/api/cloud/cloud.go b/cce-network-v2/pkg/bce/api/cloud/cloud.go index 337fdab..d862ee2 100644 --- a/cce-network-v2/pkg/bce/api/cloud/cloud.go +++ b/cce-network-v2/pkg/bce/api/cloud/cloud.go @@ -73,10 +73,8 @@ func New( debug bool, ) (Interface, error) { ctx := context.TODO() - - if debug { - sdklog.SetLogHandler(sdklog.STDOUT) - } + // set logrus as bce sdk default logger + sdklog.SetLogger(&bceLogger{}) var auth Auth var err error diff --git a/cce-network-v2/pkg/bce/api/cloud/error.go b/cce-network-v2/pkg/bce/api/cloud/error.go index 5c021d7..65299be 100644 --- a/cce-network-v2/pkg/bce/api/cloud/error.go +++ b/cce-network-v2/pkg/bce/api/cloud/error.go @@ -52,7 +52,9 @@ func ReasonForError(err error) ErrorReason { return ErrorReasonSubnetHasNoMoreIP case caseInsensitiveContains(errMsg, "RateLimit"): return ErrorReasonRateLimit - case caseInsensitiveContains(errMsg, "NoSuchObject") || caseInsensitiveContains(errMsg, "is invalid"): + case caseInsensitiveContains(errMsg, "NoSuchObject"): + return ErrorReasonNoSuchObject + case caseInsensitiveContains(errMsg, "is invalid"): // TODO: remove BadRequest when IaaS fixes their API return ErrorReasonBBCENIPrivateIPNotFound case caseInsensitiveContains(errMsg, "VmMemoryCanNotAttachMoreIpException"): diff --git a/cce-network-v2/pkg/bce/api/cloud/logger.go b/cce-network-v2/pkg/bce/api/cloud/logger.go new file mode 100644 index 0000000..bf40cdc --- /dev/null +++ b/cce-network-v2/pkg/bce/api/cloud/logger.go @@ -0,0 +1,33 @@ +package cloud + +import ( + sdklog "github.com/baidubce/bce-sdk-go/util/log" + "github.com/sirupsen/logrus" +) + +var _ sdklog.SDKLogger = &bceLogger{} + +type bceLogger struct{} + +// Logging implements log.SDKLogger. +func (*bceLogger) Logging(level sdklog.Level, format string, args ...interface{}) { + // convert log level to logrus level + var logrusLevel logrus.Level + switch level { + case sdklog.DEBUG: + logrusLevel = logrus.DebugLevel + case sdklog.INFO: + logrusLevel = logrus.InfoLevel + case sdklog.WARN: + logrusLevel = logrus.WarnLevel + case sdklog.ERROR: + logrusLevel = logrus.ErrorLevel + case sdklog.FATAL: + logrusLevel = logrus.FatalLevel + case sdklog.PANIC: + logrusLevel = logrus.PanicLevel + default: + logrusLevel = logrus.TraceLevel + } + log.Logf(logrusLevel, format, args...) +} diff --git a/cce-network-v2/pkg/bce/bcesync/eni.go b/cce-network-v2/pkg/bce/bcesync/eni.go index a91d222..d3528a1 100644 --- a/cce-network-v2/pkg/bce/bcesync/eni.go +++ b/cce-network-v2/pkg/bce/bcesync/eni.go @@ -161,6 +161,7 @@ func (es *eniSyncher) Init(ctx context.Context) error { } func (es *eniSyncher) StartENISyncer(ctx context.Context, updater syncer.ENIUpdater) syncer.ENIEventHandler { + es.remoteSyncer.setENIUpdater(updater) es.updater = updater es.syncManager.Run() log.WithField(taskLogField, eniControllerName).Infof("ENISyncher is running") @@ -178,7 +179,7 @@ func (es *eniSyncher) Create(resource *ccev2.ENI) error { func (es *eniSyncher) Update(resource *ccev2.ENI) error { var err error - if resource.Spec.Type != ccev2.ENIForBCC && resource.Spec.Type != ccev2.ENIDefaultBCC { + if resource.Spec.Type != ccev2.ENIForBCC && resource.Spec.Type != ccev2.ENIForEBC { return nil } @@ -221,6 +222,12 @@ func (es *eniSyncher) handleENIUpdate(resource *ccev2.ENI, scopeLog *logrus.Entr eniStatus *ccev2.ENIStatus updateError error ) + + // delete old eni + if newObj.Status.VPCStatus == ccev2.VPCENIStatusDeleted { + return nil + } + skipRefresh := es.mangeFinalizer(newObj) if !skipRefresh { if es.remoteSyncer.useENIMachine() { @@ -243,7 +250,6 @@ func (es *eniSyncher) handleENIUpdate(resource *ccev2.ENI, scopeLog *logrus.Entr scopeLog.WithError(err).Error("eni machine failed") return err } - } } @@ -290,24 +296,38 @@ func (*eniSyncher) mangeFinalizer(newObj *ccev2.ENI) bool { if newObj.DeletionTimestamp == nil && len(newObj.Finalizers) == 0 { newObj.Finalizers = append(newObj.Finalizers, FinalizerENI) } + var finalizers []string + if newObj.DeletionTimestamp != nil && len(newObj.Finalizers) != 0 { node, err := k8s.CCEClient().Informers.Cce().V2().NetResourceSets().Lister().Get(newObj.Spec.NodeName) - if kerrors.IsNotFound(err) || - (node != nil && node.DeletionTimestamp != nil) || - (node != nil && len(newObj.GetOwnerReferences()) != 0 && node.GetUID() != newObj.GetOwnerReferences()[0].UID) { - var finalizers []string - for _, f := range newObj.Finalizers { - if f == FinalizerENI { - continue - } - finalizers = append(finalizers, f) - } - newObj.Finalizers = finalizers - log.Infof("remove finalizer from deletable ENI %s on NetResourceSet %s ", newObj.Name, newObj.Spec.NodeName) - return true + if kerrors.IsNotFound(err) { + goto removeFinalizer + } + if node != nil && node.DeletionTimestamp != nil { + goto removeFinalizer + } + if node != nil && len(newObj.GetOwnerReferences()) != 0 && node.GetUID() != newObj.GetOwnerReferences()[0].UID { + goto removeFinalizer + } + + // eni is not inuse + if newObj.Status.VPCStatus != ccev2.VPCENIStatusDeleted && + newObj.Status.VPCStatus != ccev2.VPCENIStatusInuse { + goto removeFinalizer } } return false + +removeFinalizer: + for _, f := range newObj.Finalizers { + if f == FinalizerENI { + continue + } + finalizers = append(finalizers, f) + } + newObj.Finalizers = finalizers + log.Infof("remove finalizer from deletable ENI %s on NetResourceSet %s ", newObj.Name, newObj.Spec.NodeName) + return true } func (es *eniSyncher) Delete(name string) error { @@ -554,12 +574,18 @@ type eniStateMachine struct { // Start state machine flow func (esm *eniStateMachine) start() error { var err error - if esm.resource.Status.VPCStatus != ccev2.VPCENIStatusInuse { + if esm.resource.Status.VPCStatus != ccev2.VPCENIStatusInuse && esm.resource.Status.VPCStatus != ccev2.VPCENIStatusDeleted { // refresh status of ENI esm.vpceni, err = esm.es.remoteSyncer.statENI(esm.ctx, esm.resource.Name) - if err != nil { + if cloud.IsErrorReasonNoSuchObject(err) { + // eni not found, will delete it which not inuse + log.WithField("eniID", esm.resource.Name).Error("not inuse eni not found in vpc, will delete it") + return esm.deleteENI() + + } else if err != nil { return fmt.Errorf("eni state machine failed to refresh eni(%s) status: %v", esm.resource.Name, err) } + switch esm.resource.Status.VPCStatus { case ccev2.VPCENIStatusAvailable: err = esm.attachENI() @@ -611,7 +637,10 @@ func (esm *eniStateMachine) attachENI() error { esm.es.eventRecorder.Eventf(esm.resource, corev1.EventTypeWarning, "AttachENIFailed", "failed attach eni(%s) to %s, will delete it: %v", esm.resource.Spec.ENI.ID, esm.resource.Spec.ENI.InstanceID, err) err2 := esm.deleteENI() - err = fmt.Errorf("failed to attach eni(%s) to instance(%s): %s, delete eni crd: %s", esm.resource.Spec.ENI.ID, esm.resource.Spec.ENI.InstanceID, err.Error(), err2.Error()) + err = fmt.Errorf("failed to attach eni(%s) to instance(%s): %s, will delete eni crd", esm.resource.Spec.ENI.ID, esm.resource.Spec.ENI.InstanceID, err.Error()) + if err2 != nil { + log.WithField("eniID", esm.resource.Name).Errorf("failed to delete eni crd: %v", err2) + } return err } @@ -624,7 +653,7 @@ func (esm *eniStateMachine) attachENI() error { // deleteENI roback to delete eni func (esm *eniStateMachine) deleteENI() error { err := esm.es.bceclient.DeleteENI(esm.ctx, esm.resource.Spec.ENI.ID) - if err != nil { + if err != nil && !cloud.IsErrorReasonNoSuchObject(err) && !cloud.IsErrorENINotFound(err) { esm.es.eventRecorder.Eventf(esm.resource, corev1.EventTypeWarning, "DeleteENIFailed", "failed to delete eni(%s): %v", esm.resource.Spec.ENI.ID, err) return fmt.Errorf("failed to delete eni(%s): %s", esm.resource.Spec.ENI.ID, err.Error()) } @@ -635,7 +664,8 @@ func (esm *eniStateMachine) deleteENI() error { return fmt.Errorf("failed to delete eni(%s) crd resource: %s", esm.resource.Name, err.Error()) } - return fmt.Errorf("eni(%s) delete success", esm.resource.Spec.ENI.ID) + log.WithField("eniID", esm.resource.Name).Info("delete eni crd resource success") + return nil } // attachingENI Processing ENI in the attaching state diff --git a/cce-network-v2/pkg/bce/vpceni/node_bbc.go b/cce-network-v2/pkg/bce/vpceni/node_bbc.go index 51c14a5..5486eea 100644 --- a/cce-network-v2/pkg/bce/vpceni/node_bbc.go +++ b/cce-network-v2/pkg/bce/vpceni/node_bbc.go @@ -232,7 +232,8 @@ func (n *bbcNode) prepareIPAllocation(scopedLog *logrus.Entry) (a *ipam.Allocati // Calculate the number of IPs that can be allocated on the node allocation := &ipam.AllocationAction{} findEni := false - if n.eniQuota != nil { + eniQuota := n.getENIQuota() + if eniQuota != nil { n.manager.ForeachInstance(n.instanceID, func(instanceID, interfaceID string, iface ipamTypes.InterfaceRevision) error { e, ok := iface.Resource.(*eniResource) if !ok { @@ -240,7 +241,7 @@ func (n *bbcNode) prepareIPAllocation(scopedLog *logrus.Entry) (a *ipam.Allocati } findEni = true - allocation.AvailableForAllocationIPv4 = n.eniQuota.GetMaxIP() - len(e.Spec.PrivateIPSet) + allocation.AvailableForAllocationIPv4 = eniQuota.GetMaxIP() - len(e.Spec.PrivateIPSet) allocation.InterfaceID = e.Name allocation.PoolID = ipamTypes.PoolID(e.Spec.SubnetID) return nil diff --git a/cce-network-v2/pkg/bce/vpceni/node_bcc.go b/cce-network-v2/pkg/bce/vpceni/node_bcc.go index 6e36427..9503495 100644 --- a/cce-network-v2/pkg/bce/vpceni/node_bcc.go +++ b/cce-network-v2/pkg/bce/vpceni/node_bcc.go @@ -27,6 +27,7 @@ import ( ipamTypes "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/ipam/types" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/k8s" ccev2 "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/k8s/apis/cce.baidubce.com/v2" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/math" bccapi "github.com/baidubce/bce-sdk-go/services/bcc/api" "github.com/sirupsen/logrus" @@ -51,7 +52,6 @@ func newBCCNode(super *bceNode) *bccNode { bceNode: super, } node.instanceType = string(metadata.InstanceTypeExBCC) - node.refreshBCCInfo() return node } @@ -64,7 +64,17 @@ func (n *bccNode) refreshBCCInfo() error { n.log.Errorf("faild to get bcc instance detail: %v", err) return err } + n.log.WithField("bccInfo", logfields.Repr(bccInfo)).Infof("Get bcc instance detail") n.bccInfo = bccInfo + + // TODO delete this test code block after bcc instance eniQuota is fixed + // The tentative plan is for April 15th + { + if n.bccInfo.Spec == "ebc.la2.c256m1024.2d" { + bccInfo.EniQuota = 0 + } + } + if bccInfo.EniQuota == 0 { n.usePrimaryENIWithSecondaryMode = true } @@ -144,7 +154,7 @@ func (n *bccNode) __prepareIPAllocation(scopedLog *logrus.Entry, checkSubnet boo a = &ipam.AllocationAction{} eniQuota := n.bceNode.getENIQuota() if eniQuota == nil { - return nil, fmt.Errorf("eniQuota is nil") + return nil, fmt.Errorf("eniQuota is nil, please retry later") } eniMax := eniQuota.GetMaxENI() eniCount := 0 @@ -255,7 +265,7 @@ func (n *bccNode) __prepareIPAllocation(scopedLog *logrus.Entry, checkSubnet boo } return nil }) - a.AvailableInterfaces = eniMax - eniCount + a.AvailableInterfaces + a.AvailableInterfaces = math.IntMax(eniMax-eniCount+a.AvailableInterfaces, 0) return } diff --git a/cce-network-v2/pkg/bce/vpceni/node_bcc_eni.go b/cce-network-v2/pkg/bce/vpceni/node_bcc_eni.go index 9f3bcd4..e2ce9a4 100644 --- a/cce-network-v2/pkg/bce/vpceni/node_bcc_eni.go +++ b/cce-network-v2/pkg/bce/vpceni/node_bcc_eni.go @@ -273,7 +273,7 @@ func (n *bccNode) createENIOnCluster(ctx context.Context, scopedLog *logrus.Entr newENI.Spec.ENI.ID = eniID newENI.Name = eniID - n.creatingEni.addCreatingENI(newENI) + n.creatingEni.addCreatingENI(newENI.Name, time.Now()) _, err = k8s.CCEClient().CceV2().ENIs().Create(ctx, newENI, metav1.CreateOptions{}) if err != nil { @@ -320,8 +320,7 @@ func (n *bceNode) createENI(ctx context.Context, resource *ccev2.ENI, scopedLog EnterpriseSecurityGroupIds: resource.Spec.ENI.EnterpriseSecurityGroupIds, Description: defaults.DefaultENIDescription, PrivateIpSet: []enisdk.PrivateIp{{ - Primary: true, - PrivateIpAddress: "", + Primary: true, }}, } if createENIArgs.EnterpriseSecurityGroupIds == nil { @@ -329,19 +328,20 @@ func (n *bceNode) createENI(ctx context.Context, resource *ccev2.ENI, scopedLog } // use the given ip to create a new ENI - var privateIPs []*enisdk.PrivateIp + var privateIPs []enisdk.PrivateIp for i := 0; i < len(resource.Spec.ENI.PrivateIPSet); i++ { - privateIPs = append(privateIPs, &enisdk.PrivateIp{ + privateIPs = append(privateIPs, enisdk.PrivateIp{ PublicIpAddress: resource.Spec.ENI.PrivateIPSet[i].PublicIPAddress, Primary: resource.Spec.ENI.PrivateIPSet[i].Primary, PrivateIpAddress: resource.Spec.ENI.PrivateIPSet[i].PrivateIPAddress, }) } if len(privateIPs) == 0 { - privateIPs = append(privateIPs, &enisdk.PrivateIp{ + privateIPs = append(privateIPs, enisdk.PrivateIp{ Primary: true, }) } + createENIArgs.PrivateIpSet = privateIPs eniID, err := n.manager.bceclient.CreateENI(ctx, createENIArgs) if err != nil { diff --git a/cce-network-v2/pkg/bce/vpceni/node_ebc.go b/cce-network-v2/pkg/bce/vpceni/node_ebc.go index 5ac20e6..98d9426 100644 --- a/cce-network-v2/pkg/bce/vpceni/node_ebc.go +++ b/cce-network-v2/pkg/bce/vpceni/node_ebc.go @@ -35,8 +35,6 @@ func newEBCNode(super *bccNode) *ebcNode { bccNode: super, } node.instanceType = string(metadata.InstanceTypeExEBC) - - node.refreshBCCInfo() return node } diff --git a/cce-network-v2/pkg/bce/vpceni/node_super.go b/cce-network-v2/pkg/bce/vpceni/node_super.go index a040e5e..d974249 100644 --- a/cce-network-v2/pkg/bce/vpceni/node_super.go +++ b/cce-network-v2/pkg/bce/vpceni/node_super.go @@ -165,6 +165,7 @@ func NewNode(node *ipam.NetResource, k8sObj *ccev2.NetResourceSet, manager *Inst default: anode.real = newBCCNode(anode) } + anode.getENIQuota() } return anode @@ -188,8 +189,8 @@ func (n *bceNode) getENIQuota() ENIQuotaManager { // fast path to claculate eni quota when operaor has been restarted // isSetLimiter returns true if the node has set limiter // if the node has set limiter, it will return a limiter from the ENI spec - if n.k8sObj.Labels != nil && n.k8sObj.Labels[k8s.LabelIPResourceCapacitySynced] != "" { - lastResyncTime := n.k8sObj.Labels[k8s.LabelIPResourceCapacitySynced] + if n.k8sObj.Annotations != nil && n.k8sObj.Annotations[k8s.AnnotationIPResourceCapacitySynced] != "" { + lastResyncTime := n.k8sObj.Annotations[k8s.AnnotationIPResourceCapacitySynced] t, err := time.Parse(time.RFC3339, lastResyncTime) if err != nil || t.Add(DayDuration).Before(time.Now()) { goto slowPath @@ -198,9 +199,10 @@ func (n *bceNode) getENIQuota() ENIQuotaManager { eniQuota.SetMaxENI(n.k8sObj.Spec.ENI.MaxAllocateENI) eniQuota.SetMaxIP(n.k8sObj.Spec.ENI.MaxIPsPerENI) // use customer max ip nums if defiend - if operatorOption.Config.BCECustomerMaxIP != 0 && operatorOption.Config.BCECustomerMaxIP == n.eniQuota.GetMaxIP() { + if operatorOption.Config.BCECustomerMaxIP != 0 && operatorOption.Config.BCECustomerMaxIP == eniQuota.GetMaxIP() { goto slowPath } + n.eniQuota = eniQuota return n.eniQuota } @@ -213,7 +215,7 @@ func (n *bceNode) slowCalculateRealENICapacity(scopedLog *logrus.Entry) ENIQuota eniQuota, err := n.real.refreshENIQuota(scopedLog) if err != nil { scopedLog.Errorf("calculate eniQuota failed: %v", err) - return n.eniQuota + return nil } // if eniQuota is empty, it means the node has not set quota @@ -255,18 +257,19 @@ func (n *bceNode) overrideENICapacityToNode(eniQuota ENIQuotaManager) error { k8sObj = k8sObj.DeepCopy() k8sObj.Spec.ENI.MaxAllocateENI = eniQuota.GetMaxENI() k8sObj.Spec.ENI.MaxIPsPerENI = eniQuota.GetMaxIP() - if k8sObj.Labels == nil { - k8sObj.Labels = map[string]string{} + if k8sObj.Annotations == nil { + k8sObj.Annotations = map[string]string{} } now := time.Now().Format(time.RFC3339) - k8sObj.Labels[k8s.LabelIPResourceCapacitySynced] = now + k8sObj.Annotations[k8s.AnnotationIPResourceCapacitySynced] = now updated, err := k8s.CCEClient().CceV2().NetResourceSets().Update(ctx, k8sObj, metav1.UpdateOptions{}) if err == nil { k8sObj = updated n.k8sObj = k8sObj return true, nil } + n.log.Errorf("failed to override nrs %s capacity: %v", n.k8sObj.Name, err) return false, nil }) if err != nil { @@ -289,7 +292,8 @@ func (n *bceNode) UpdatedNode(obj *ccev2.NetResourceSet) { // of the functions AllocateIPs(), ReleaseIPs() and CreateInterface(). func (n *bceNode) ResyncInterfacesAndIPs(ctx context.Context, scopedLog *logrus.Entry) (ipamTypes.AllocationMap, error) { var ( - a = ipamTypes.AllocationMap{} + a = ipamTypes.AllocationMap{} + allENIId []string ) n.waitForENISynced(ctx) @@ -305,11 +309,13 @@ func (n *bceNode) ResyncInterfacesAndIPs(ctx context.Context, scopedLog *logrus. if !ok { return nil } + allENIId = append(allENIId, e.Name) // eni is not ready to use eniSubnet := e.Spec.ENI.SubnetID if e.Status.VPCStatus != ccev2.VPCENIStatusInuse { haveCreatingENI = true + n.creatingEni.addCreatingENI(e.Name, e.CreationTimestamp.Time) return nil } @@ -344,6 +350,7 @@ func (n *bceNode) ResyncInterfacesAndIPs(ctx context.Context, scopedLog *logrus. return nil }) + n.creatingEni.cleanExpiredCreatingENI(allENIId, operatorOption.Config.ResourceResyncInterval*3) // the CreateInterface function will not be called in the primary IP mode // so we need to create a new ENI in the primary IP mode at this time @@ -357,34 +364,27 @@ func (n *bceNode) ResyncInterfacesAndIPs(ctx context.Context, scopedLog *logrus. return a, nil } -func (n *bceNode) alignDualStackIPs(ctx context.Context, scopedLog *logrus.Entry, e *eniResource) { - if operatorOption.Config.EnableIPv6 && operatorOption.Config.EnableIPv4 { - if len(e.Spec.ENI.PrivateIPSet) != len(e.Spec.ENI.IPV6PrivateIPSet) { - scopedLog.Warnf("eni %s ipv4 and ipv6 private ip number not equal", e.Name) - a, err := n.PrepareIPAllocation(scopedLog) - if err != nil { - scopedLog.WithError(err).Errorf("prepare ip allocation failed") - } - err = n.AllocateIPs(ctx, a) - if err != nil { - scopedLog.WithError(err).Errorf("allocate ip failed") - } - } - } -} - // CreateInterface create a new ENI func (n *bceNode) CreateInterface(ctx context.Context, allocation *ipam.AllocationAction, scopedLog *logrus.Entry) (interfaceNum int, msg string, err error) { - availableENICount := 0 + var ( + availableENICount int + allENIId []string + eniQuota = n.getENIQuota() + ) + if eniQuota == nil { + return 0, "", fmt.Errorf("eni quota is nil, please retry later") + } n.manager.ForeachInstance(n.instanceID, func(instanceID, interfaceID string, iface ipamTypes.InterfaceRevision) error { - _, ok := iface.Resource.(*eniResource) + eni, ok := iface.Resource.(*eniResource) if !ok { return nil } availableENICount++ + allENIId = append(allENIId, eni.Name) return nil }) + n.creatingEni.cleanExpiredCreatingENI(allENIId, operatorOption.Config.ResourceResyncInterval*3) if n.creatingEni.hasCreatingENI() { scopedLog.Debugf("skip to creating new eni, concurrent eni creating") @@ -395,8 +395,9 @@ func (n *bceNode) CreateInterface(ctx context.Context, allocation *ipam.Allocati inums, msg, err := n.real.createInterface(ctx, allocation, scopedLog) n.creatingEni.add(-1) - preAllocateENI := n.k8sObj.Spec.ENI.PreAllocateENI - availableENICount - 1 - for i := 0; i < preAllocateENI; i++ { + preAllocateNum := math.IntMin(eniQuota.GetMaxENI()-1, n.k8sObj.Spec.ENI.PreAllocateENI) + preAllocateNum = preAllocateNum - availableENICount + for i := 0; i < preAllocateNum; i++ { inums++ go func() { n.creatingEni.add(1) @@ -464,12 +465,16 @@ func (n *bceNode) PopulateStatusFields(resource *ccev2.NetResourceSet) { addCrossSubnetAddr(addr) } - // if IPv6 is enabled, we need to allocate 2 * maxIPPerENI - capacity := n.eniQuota.GetMaxIP() - if len(enis[i].Spec.IPV6PrivateIPSet) > 0 { - capacity = 2 * capacity + // eni quota may be nil + if eniQuota := n.getENIQuota(); eniQuota != nil { + capacity := eniQuota.GetMaxIP() + // if IPv6 is enabled, we need to allocate 2 * maxIPPerENI + if len(enis[i].Spec.IPV6PrivateIPSet) > 0 { + capacity = 2 * capacity + } + simple.AvailableIPNum = capacity - len(enis[i].Spec.PrivateIPSet) - len(enis[i].Spec.IPV6PrivateIPSet) } - simple.AvailableIPNum = capacity - len(enis[i].Spec.PrivateIPSet) - len(enis[i].Spec.IPV6PrivateIPSet) + simple.AllocatedCrossSubnetIPNum = allocatedCrossSubnetIPNum simple.AllocatedIPNum = len(enis[i].Spec.PrivateIPSet) + len(enis[i].Spec.IPV6PrivateIPSet) @@ -495,7 +500,9 @@ func (n *bceNode) PopulateStatusFields(resource *ccev2.NetResourceSet) { // can be allocated on the node and whether a new network interface // must be attached to the node. func (n *bceNode) PrepareIPAllocation(scopedLog *logrus.Entry) (a *ipam.AllocationAction, err error) { - n.getENIQuota() + if quota := n.getENIQuota(); quota == nil { + return nil, fmt.Errorf("eniQuota is nil, please retry later") + } return n.real.prepareIPAllocation(scopedLog) } @@ -1083,27 +1090,48 @@ var ( type creatingEniSet struct { mutex *lock.Mutex // The node currently being created by ENI should have only one. - creatingENI map[string]*ccev2.ENI + creatingENI map[string]time.Time creatingENINums int } func newCreatingEniSet() *creatingEniSet { return &creatingEniSet{ mutex: &lock.Mutex{}, - creatingENI: map[string]*ccev2.ENI{}, + creatingENI: map[string]time.Time{}, } } -func (c *creatingEniSet) addCreatingENI(eni *ccev2.ENI) { +func (c *creatingEniSet) addCreatingENI(eniID string, createTime time.Time) { + c.mutex.Lock() + defer c.mutex.Unlock() + c.creatingENI[eniID] = createTime +} + +func (c *creatingEniSet) removeCreatingENI(eniID string) { c.mutex.Lock() defer c.mutex.Unlock() - c.creatingENI[eni.Name] = eni + delete(c.creatingENI, eniID) } -func (c *creatingEniSet) removeCreatingENI(eniName string) { +// clean expired creating eni +// eniIDs: slice of eniIDs that are not being expired +// duration: the max time that a creating eni can be expired +func (c *creatingEniSet) cleanExpiredCreatingENI(eniIDs []string, duration time.Duration) { c.mutex.Lock() defer c.mutex.Unlock() - delete(c.creatingENI, eniName) + now := time.Now() + + exsitENIIDs := make(map[string]bool) + for _, eniID := range eniIDs { + exsitENIIDs[eniID] = true + } + for eniID := range c.creatingENI { + if _, ok := exsitENIIDs[eniID]; !ok { + if now.Sub(c.creatingENI[eniID]) > duration { + delete(c.creatingENI, eniID) + } + } + } } func (c *creatingEniSet) add(num int) { diff --git a/cce-network-v2/pkg/k8s/labels.go b/cce-network-v2/pkg/k8s/labels.go index e4224f9..0ba1f16 100644 --- a/cce-network-v2/pkg/k8s/labels.go +++ b/cce-network-v2/pkg/k8s/labels.go @@ -54,8 +54,8 @@ const ( // VPCIDLabel is the label used to store the VPC ID of the node. VPCIDLabel = "cce.baidubce.com/vpc-id" - // LabelIPResourceCapacitySynced is the label used to store the ip resource capacity synced status of the node. - LabelIPResourceCapacitySynced = "cce.baidubce.com/ip-resource-capacity-synced" + // AnnotationIPResourceCapacitySynced is the annotation used to store the ip resource capacity synced status of the node. + AnnotationIPResourceCapacitySynced = "cce.baidubce.com/ip-resource-capacity-synced" // LabelAvailableZone is the label used to store the available zone of the node. LabelAvailableZone = "cce.baidubce.com/available-zone" diff --git a/cce-network-v2/pkg/logging/logging.go b/cce-network-v2/pkg/logging/logging.go index e92b7f9..0d5b45c 100644 --- a/cce-network-v2/pkg/logging/logging.go +++ b/cce-network-v2/pkg/logging/logging.go @@ -20,6 +20,7 @@ import ( "bytes" "flag" "fmt" + "log" "os" "path/filepath" "regexp" @@ -217,6 +218,18 @@ func SetupLogging(loggers []string, logOpts LogOptions, tag string, debug bool) return nil } +func SetupCNILogging(tag string, debug bool) error { + opt := LogOptions(map[string]string{"syslog.level": "info", "syslog.facility": "local5"}) + if debug { + opt["syslog.level"] = "debug" + } + // Logging should always be bootstrapped first. Do not add any code above this! + if err := SetupLogging([]string{"syslog"}, opt, tag, debug); err != nil { + log.Fatalf("failed to setup syslog: %v", err) + } + return nil +} + // GetFormatter returns a configured logrus.Formatter with some specific values // we want to have func GetFormatter(format LogFormat) logrus.Formatter { diff --git a/cce-network-v2/pkg/option/config.go b/cce-network-v2/pkg/option/config.go index 059a13e..d548d55 100644 --- a/cce-network-v2/pkg/option/config.go +++ b/cce-network-v2/pkg/option/config.go @@ -374,6 +374,8 @@ const ( IPPoolMinAllocateIPs = "ippool-min-allocate-ips" IPPoolPreAllocate = "ippool-pre-allocate" IPPoolMaxAboveWatermark = "ippool-max-above-watermark" + + ExtCNIPluginsList = "ext-cni-plugins" ) // Available option for DaemonConfig.Tunnel @@ -388,23 +390,13 @@ const ( TunnelDisabled = "disabled" ) -// Envoy option names const ( - - // ReadCNIConfiguration reads the CNI configuration file and extracts - // CCE relevant information. This can be used to pass per node - // configuration to CCE. - ReadCNIConfiguration = "read-cni-conf" - // WriteCNIConfigurationWhenReady writes the CNI configuration to the // specified location once the agent is ready to serve requests. This // allows to keep a Kubernetes node NotReady until CCE is up and // running and able to schedule endpoints. WriteCNIConfigurationWhenReady = "write-cni-conf-when-ready" - // OverwriteCNIConfigurationWhenStart Overwrite the CNI configuration when agent starts - OverwriteCNIConfigurationWhenStart = "overwrite-cni-conf" - // EnableCCEEndpointSlice enables the cce endpoint slicing feature. EnableCCEEndpointSlice = "enable-cce-endpoint-slice" ) @@ -685,20 +677,12 @@ type DaemonConfig struct { // RunMonitorAgent indicates whether to run the monitor agent RunMonitorAgent bool - // ReadCNIConfiguration reads the CNI configuration file and extracts - // CCE relevant information. This can be used to pass per node - // configuration to CCE. - ReadCNIConfiguration string - // WriteCNIConfigurationWhenReady writes the CNI configuration to the // specified location once the agent is ready to serve requests. This // allows to keep a Kubernetes node NotReady until CCE is up and // running and able to schedule endpoints. WriteCNIConfigurationWhenReady string - // OverwriteCNIConfigurationWhenStart Overwrite the CNI configuration when agent starts - OverwriteCNIConfigurationWhenStart bool - // EnableHealthDatapath enables IPIP health probes data path EnableHealthDatapath bool @@ -777,6 +761,9 @@ type DaemonConfig struct { EnableBandwidthManager bool EnableEgressPriority bool EnableEgressPriorityDSCP bool + + // ExtCNIPluginsList Expand the list of CNI plugins, such as 'sbr-eip' + ExtCNIPluginsList []string } var ( @@ -1009,9 +996,6 @@ func (c *DaemonConfig) Validate() error { if err := c.checkIPAMDelegatedPlugin(); err != nil { return err } - if c.WriteCNIConfigurationWhenReady != "" && c.ReadCNIConfiguration == "" { - return fmt.Errorf("%s must be set when using %s", ReadCNIConfiguration, WriteCNIConfigurationWhenReady) - } return nil } @@ -1152,12 +1136,10 @@ func (c *DaemonConfig) Populate() { c.PProfPort = viper.GetInt(PProfPort) c.ProcFs = viper.GetString(ProcFs) c.PrometheusServeAddr = viper.GetString(PrometheusServeAddr) - c.ReadCNIConfiguration = viper.GetString(ReadCNIConfiguration) c.RunDir = viper.GetString(StateDir) c.TracePayloadlen = viper.GetInt(TracePayloadlen) c.Version = viper.GetString(Version) c.WriteCNIConfigurationWhenReady = viper.GetString(WriteCNIConfigurationWhenReady) - c.OverwriteCNIConfigurationWhenStart = viper.GetBool(OverwriteCNIConfigurationWhenStart) c.CRDWaitTimeout = viper.GetDuration(CRDWaitTimeout) c.EnableBandwidthManager = viper.GetBool(EnableBandwidthManager) c.EnableEgressPriority = viper.GetBool(EnableEgressPriority) @@ -1299,6 +1281,7 @@ func (c *DaemonConfig) Populate() { c.MaxControllerInterval = viper.GetInt(MaxCtrlIntervalName) c.EndpointGCInterval = viper.GetDuration(EndpointGCInterval) c.ResourceResyncInterval = viper.GetDuration(ResourceResyncInterval) + c.ExtCNIPluginsList = viper.GetStringSlice(ExtCNIPluginsList) } func (c *DaemonConfig) checkIPAMDelegatedPlugin() error { diff --git a/cce-network-v2/plugins/cipam/main.go b/cce-network-v2/plugins/cipam/main.go index b7078ec..0b61017 100644 --- a/cce-network-v2/plugins/cipam/main.go +++ b/cce-network-v2/plugins/cipam/main.go @@ -24,13 +24,12 @@ import ( "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/defaults" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/ip" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" - "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/hooks" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/netns" "github.com/containernetworking/plugins/pkg/ns" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" gops "github.com/google/gops/agent" - "github.com/google/uuid" + "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus" plugintypes "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/cni/types" @@ -40,6 +39,8 @@ import ( "github.com/containernetworking/cni/pkg/version" ) +var logger *log.Entry + func main() { skel.PluginMain(cmdAdd, nil, cmdDel, version.All, bv.BuildString("cipam")) } @@ -52,44 +53,46 @@ func cmdAdd(args *skel.CmdArgs) (err error) { routes []*cnitypes.Route ) + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "cipam", + "mod": "ADD", + }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() + n, err = plugintypes.LoadNetConf(args.StdinData) if err != nil { err = fmt.Errorf("unable to parse CNI configuration \"%s\": %s", args.StdinData, err) return } - if innerErr := setupLogging(n); innerErr != nil { - err = fmt.Errorf("unable to setup logging: %w", innerErr) - return - } - logger := logging.DefaultLogger.WithField("mod", "ADD") - logger = logger.WithField("eventUUID", uuid.New()). - WithField("containerID", args.ContainerID) if n.IPAM.EnableDebug { if err := gops.Listen(gops.Options{}); err != nil { - log.WithError(err).Warn("Unable to start gops") + logger.WithError(err).Warn("Unable to start gops") } else { defer gops.Close() } } - logger.Debugf("Processing CNI ADD request %#v", args) - - logger.Debugf("CNI NetConf: %#v", n) - if n.PrevResult != nil { - logger.Debugf("CNI Previous result: %#v", n.PrevResult) - } + logger.WithField("netConf", logfields.Json(n)).Infof("Processing CNI ADD request %#v", args) cniArgs := plugintypes.ArgsSpec{} if err = cnitypes.LoadArgs(args.Args, &cniArgs); err != nil { err = fmt.Errorf("unable to extract CNI arguments: %s", err) return } - logger.Debugf("CNI Args: %#v", cniArgs) c, err := client.NewDefaultClientWithTimeout(defaults.ClientConnectTimeout) if err != nil { err = fmt.Errorf("unable to connect to network-v2-agent: %s", client.Hint(err)) + logger.WithError(err).Error("unable to connect to network-v2-agent") return } @@ -100,24 +103,27 @@ func cmdAdd(args *skel.CmdArgs) (err error) { nns.Path() ns, err := netns.GetProcNSPath(args.Netns) if err != nil { + logger.Warning("unable to get netns path from procfs, use the netns from args") ns = args.Netns } var releaseIPsFunc func(context.Context) ipam, releaseIPsFunc, err = allocateIPsWithCCEAgent(c, cniArgs, args.ContainerID, ns) - // release addresses on failure defer func() { if err != nil && releaseIPsFunc != nil { + logger.WithError(err).Warn("do release IPs") releaseIPsFunc(context.TODO()) } }() - if err != nil { + logger.WithError(err).Error("unable to allocate IP addresses with cce agent") return } + logger.WithField("agentResult", logfields.Json(ipam)).Infof("success allocated IP addresses with cce agent") if !ipv6IsEnabled(ipam) && !ipv4IsEnabled(ipam) { err = fmt.Errorf("IPAM did not provide IPv4 or IPv6 address") + logger.WithError(err).Error("unable to allocate IP addresses with cce agent") return } @@ -137,6 +143,7 @@ func cmdAdd(args *skel.CmdArgs) (err error) { ipConfig, routes, err = prepareIP(ipam, n, false) if err != nil { err = fmt.Errorf("unable to prepare IP addressing for '%s': %s", ipam.IPV4.IP, err) + logger.WithError(err).Error("unable to prepare IP addresses") return } ipConfig.Interface = &zoreInterface @@ -144,10 +151,25 @@ func cmdAdd(args *skel.CmdArgs) (err error) { result.Routes = append(result.Routes, routes...) } + logger.WithField("result", logfields.Json(result)).Info("success to exec ipam add") + return cnitypes.PrintResult(result, current.ImplementedSpecVersion) } -func cmdDel(args *skel.CmdArgs) error { +func cmdDel(args *skel.CmdArgs) (err error) { + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "cipam", + "mod": "DEL", + }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() // Note about when to return errors: kubelet will retry the deletion // for a long time. Therefore, only return an error for errors which // are guaranteed to be recoverable. @@ -157,23 +179,14 @@ func cmdDel(args *skel.CmdArgs) error { return err } - if err := setupLogging(n); err != nil { - return fmt.Errorf("unable to setup logging: %w", err) - } - logger := logging.DefaultLogger.WithField("mod", "DEL") - logger = logger.WithField("eventUUID", uuid.New()). - WithField("containerID", args.ContainerID) - if n.IPAM.EnableDebug { if err := gops.Listen(gops.Options{}); err != nil { - log.WithError(err).Warn("Unable to start gops") + logger.WithError(err).Warn("Unable to start gops") } else { defer gops.Close() } } - logger.Debugf("Processing CNI DEL request %#v", args) - - logger.Debugf("CNI NetConf: %#v", n) + logger.Info("Processing CNI DEL request") cniArgs := plugintypes.ArgsSpec{} if err = cnitypes.LoadArgs(args.Args, &cniArgs); err != nil { @@ -187,7 +200,13 @@ func cmdDel(args *skel.CmdArgs) error { return fmt.Errorf("unable to connect to CCE daemon: %s", client.Hint(err)) } owner := cniArgs.K8S_POD_NAMESPACE + "/" + cniArgs.K8S_POD_NAME - return releaseIP(c, string(owner), args.ContainerID, args.Netns) + err = releaseIP(c, string(owner), args.ContainerID, args.Netns) + if err != nil { + return fmt.Errorf("unable to release IP: %w", err) + } + + logger.Info("success to exec ipam del") + return nil } func allocateIPsWithCCEAgent(client *client.Client, cniArgs plugintypes.ArgsSpec, containerID, netns string) (*models.IPAMResponse, func(context.Context), error) { @@ -299,29 +318,6 @@ func prepareIP(ipam *models.IPAMResponse, n *plugintypes.NetConf, isIPv6 bool) ( }, routes, nil } -func setupLogging(n *plugintypes.NetConf) error { - f := n.IPAM.LogFormat - if f == "" { - f = string(logging.DefaultLogFormat) - } - logOptions := logging.LogOptions{ - logging.FormatOpt: f, - } - err := logging.SetupLogging([]string{}, logOptions, "cipam", n.IPAM.EnableDebug) - if err != nil { - return err - } - - if len(n.IPAM.LogFile) != 0 { - logging.AddHooks(hooks.NewFileRotationLogHook(n.IPAM.LogFile, - hooks.EnableCompression(), - hooks.WithMaxBackups(1), - )) - } - - return nil -} - func ipv6IsEnabled(ipam *models.IPAMResponse) bool { if ipam == nil || ipam.Address.IPV6 == "" { return false diff --git a/cce-network-v2/plugins/cptp/cptp.go b/cce-network-v2/plugins/cptp/cptp.go index e2b97a8..abd9f73 100644 --- a/cce-network-v2/plugins/cptp/cptp.go +++ b/cce-network-v2/plugins/cptp/cptp.go @@ -37,6 +37,7 @@ func containerSet(hostVeth, contVeth *net.Interface, pr *current.Result) error { }(), }) if err != nil { + logger.WithError(err).Errorf("failed to add permanent ARP entry for the gateway %q", ipc.Gateway) return fmt.Errorf("failed to add permanent ARP entry for the gateway %q: %v", ipc.Gateway, err) } } diff --git a/cce-network-v2/plugins/cptp/ipam_linux.go b/cce-network-v2/plugins/cptp/ipam_linux.go index 8ad4cf8..f584a5c 100644 --- a/cce-network-v2/plugins/cptp/ipam_linux.go +++ b/cce-network-v2/plugins/cptp/ipam_linux.go @@ -17,8 +17,8 @@ package main import ( "fmt" "net" - "os" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" current "github.com/containernetworking/cni/pkg/types/100" "github.com/containernetworking/plugins/pkg/ip" "github.com/containernetworking/plugins/pkg/utils/sysctl" @@ -68,7 +68,7 @@ func CPTPConfigureIface(ifName string, res *current.Result) error { // Read current sysctl value value, err := sysctl.Sysctl(ipv6SysctlValueName) if err != nil { - fmt.Fprintf(os.Stderr, "ipam_linux: failed to read sysctl %q: %v\n", ipv6SysctlValueName, err) + logger.WithError(err).Errorf("ipam_linux: failed to read sysctl %s", ipv6SysctlValueName) continue } if value == "0" { @@ -96,6 +96,7 @@ func CPTPConfigureIface(ifName string, res *current.Result) error { Label: "", } if err = netlink.AddrAdd(link, addr); err != nil { + logger.WithError(err).WithField("add", logfields.Repr(addr)).Errorf("failed to add IP addr %v to %q: %v", ipc, ifName, err) return fmt.Errorf("failed to add IP addr %v to %q: %v", ipc, ifName, err) } @@ -135,6 +136,7 @@ func CPTPConfigureIface(ifName string, res *current.Result) error { }, } { if err := netlink.RouteAdd(&r); err != nil { + logger.WithError(err).WithField("route", logfields.Repr(r)).Errorf("failed to add route") return fmt.Errorf("failed to add route %v: %v", r, err) } } @@ -158,6 +160,7 @@ func CPTPConfigureIface(ifName string, res *current.Result) error { } if err = netlink.RouteAddEcmp(&route); err != nil { + logger.WithError(err).WithField("route", logfields.Repr(r)).Errorf("failed to add route") return fmt.Errorf("failed to add route '%v via %v dev %v': %v", r.Dst, gw, ifName, err) } } diff --git a/cce-network-v2/plugins/cptp/ptp.go b/cce-network-v2/plugins/cptp/ptp.go index 36281e7..70bfa92 100644 --- a/cce-network-v2/plugins/cptp/ptp.go +++ b/cce-network-v2/plugins/cptp/ptp.go @@ -24,6 +24,9 @@ import ( "os" "runtime" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" + "github.com/sirupsen/logrus" "github.com/vishvananda/netlink" "github.com/containernetworking/cni/pkg/skel" @@ -37,6 +40,8 @@ import ( bv "github.com/containernetworking/plugins/pkg/utils/buildversion" ) +var logger *logrus.Entry + func init() { // this ensures that main runs only on main thread (thread group leader). // since namespace ops (unshare, setns) are done for a single thread, we @@ -144,10 +149,24 @@ func setupHostVeth(host *current.Interface, container *current.Interface, result return nil } -func cmdAdd(args *skel.CmdArgs) error { +func cmdAdd(args *skel.CmdArgs) (err error) { var pK8Sargs *K8SArgs - pK8Sargs, err := loadK8SArgs(args.Args) + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "cptp", + "mod": "ADD", + }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() + + pK8Sargs, err = loadK8SArgs(args.Args) if err != nil { return fmt.Errorf("failed to load CNI_ARGS: %v", err) } @@ -160,7 +179,8 @@ func cmdAdd(args *skel.CmdArgs) error { // run the IPAM plugin and get back the config to apply r, err := ipam.ExecAdd(conf.IPAM.Type, args.StdinData) if err != nil { - return err + logger.WithError(err).Error("failed to exec IPAM plugin") + return fmt.Errorf("failed to execute IPAM plugin: %w", err) } // Invoke ipam del if err to avoid ip leak @@ -173,8 +193,9 @@ func cmdAdd(args *skel.CmdArgs) error { // Convert whatever the IPAM result was into the current Result type result, err := current.NewResultFromResult(r) if err != nil { - return err + return fmt.Errorf("could not convert result of IPAM plugin: %v", err) } + logger.WithField("ipamResult", result).Infof("got result from IPAM") if len(result.IPs) == 0 { return errors.New("IPAM plugin returned missing IP config") @@ -200,11 +221,11 @@ func cmdAdd(args *skel.CmdArgs) error { hostInterface, containerInterface, err := setupContainerVethLegacy(string(pK8Sargs.K8S_POD_NAME), string(pK8Sargs.K8S_POD_NAMESPACE), netns, args.IfName, conf.MTU, result) if err != nil { - return err + return fmt.Errorf("failed to setup container veth: %w", err) } if err = setupHostVeth(hostInterface, containerInterface, result); err != nil { - return err + return fmt.Errorf("failed to setup host veth: %w", err) } if conf.IPMasq { @@ -212,7 +233,7 @@ func cmdAdd(args *skel.CmdArgs) error { comment := utils.FormatComment(conf.Name, args.ContainerID) for _, ipc := range result.IPs { if err = ip.SetupIPMasq(&ipc.Address, chain, comment); err != nil { - return err + return fmt.Errorf("failed to setup IP masquerade: %w", err) } } } @@ -224,6 +245,7 @@ func cmdAdd(args *skel.CmdArgs) error { result.DNS = conf.DNS } + logger.WithField("result", logfields.Json(result)).Infof("success to exec plugin") return types.PrintResult(result, conf.CNIVersion) } @@ -234,15 +256,30 @@ func dnsConfSet(dnsConf types.DNS) bool { dnsConf.Domain != "" } -func cmdDel(args *skel.CmdArgs) error { +func cmdDel(args *skel.CmdArgs) (err error) { + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "cptp", + "mod": "DEL", + }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() + conf := NetConf{} if err := json.Unmarshal(args.StdinData, &conf); err != nil { return fmt.Errorf("failed to load netconf: %v", err) } if err := ipam.ExecDel(conf.IPAM.Type, args.StdinData); err != nil { - return err + return fmt.Errorf("failed to exec ipam del: %v", err) } + logger.Info("success to executing cipam DEL") if args.Netns == "" { return nil @@ -252,7 +289,7 @@ func cmdDel(args *skel.CmdArgs) error { // so don't return an error if the device is already removed. // If the device isn't there then don't try to clean up IP masq either. var ipnets []*net.IPNet - err := ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { + err = ns.WithNetNSPath(args.Netns, func(_ ns.NetNS) error { var err error ipnets, err = ip.DelLinkByNameAddr(args.IfName) if err != nil && err == ip.ErrLinkNotFound { @@ -268,7 +305,7 @@ func cmdDel(args *skel.CmdArgs) error { if ok { return nil } - return err + return fmt.Errorf("failed to clean container interface: %v", err) } if len(ipnets) != 0 && conf.IPMasq { @@ -276,6 +313,9 @@ func cmdDel(args *skel.CmdArgs) error { comment := utils.FormatComment(conf.Name, args.ContainerID) for _, ipn := range ipnets { err = ip.TeardownIPMasq(ipn, chain, comment) + if err != nil { + logger.WithError(err).Error("failed to teardown ip masquerade") + } } } diff --git a/cce-network-v2/plugins/endpoint-probe/main.go b/cce-network-v2/plugins/endpoint-probe/main.go index d072e60..a869100 100644 --- a/cce-network-v2/plugins/endpoint-probe/main.go +++ b/cce-network-v2/plugins/endpoint-probe/main.go @@ -16,7 +16,6 @@ package main import ( - "context" "encoding/json" "fmt" @@ -27,7 +26,6 @@ import ( "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/datapath/link" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/defaults" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" - "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/hooks" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" @@ -38,8 +36,6 @@ import ( "github.com/sirupsen/logrus" ) -const firstTableID = 100 - var logger *logrus.Entry // PluginConf is the configuration document passed in. @@ -89,50 +85,26 @@ func parseConfig(stdin []byte) (*PluginConf, error) { return &conf, nil } -func setupLogging(n *PluginConf, args *skel.CmdArgs, method string) error { - f := n.LogFormat - if f == "" { - f = string(logging.DefaultLogFormat) - } - logOptions := logging.LogOptions{ - logging.FormatOpt: f, - } - if len(n.LogFile) != 0 { - err := logging.SetupLogging([]string{}, logOptions, "endpoint-probe", n.EnableDebug) - if err != nil { - return err - } - logging.AddHooks(hooks.NewFileRotationLogHook(n.LogFile, - hooks.EnableCompression(), - hooks.WithMaxBackups(1), - )) - } else { - logOptions["syslog.facility"] = "local5" - err := logging.SetupLogging([]string{"syslog"}, logOptions, "endpoint-probe", true) - if err != nil { - return err - } - } +// cmdAdd is called for ADD requests +func cmdAdd(args *skel.CmdArgs) (err error) { + logging.SetupCNILogging("cni", true) logger = logging.DefaultLogger.WithFields(logrus.Fields{ - "containerID": args.ContainerID, - "netns": args.Netns, - "plugin": "endpoint-probe", - "method": method, + "cmdArgs": logfields.Json(args), + "plugin": "endpoint-probe", + "mod": "ADD", }) + defer func() { + if err != nil { + logger.WithError(err).Errorf("cni plugin failed") + } + }() - return nil -} - -// cmdAdd is called for ADD requests -func cmdAdd(args *skel.CmdArgs) error { - conf, err := parseConfig(args.StdinData) + var conf *PluginConf + conf, err = parseConfig(args.StdinData) if err != nil { return fmt.Errorf("endpoint-probe failed to parse config: %v", err) } - err = setupLogging(conf, args, "ADD") - if err != nil { - return fmt.Errorf("endpoint-probe failed to set up logging: %v", err) - } + defer func() { if err != nil { logger.Errorf("cni plugin failed: %v", err) @@ -145,18 +117,21 @@ func cmdAdd(args *skel.CmdArgs) error { return fmt.Errorf("this plugin must be called as chained plugin") } - netns, err := ns.GetNS(args.Netns) + var netns ns.NetNS + netns, err = ns.GetNS(args.Netns) if err != nil { return fmt.Errorf("failed to open netns %q: %v", args.Netns, err) } defer netns.Close() - cctx, err := link.NewContainerContext(args.ContainerID, args.Netns) + var cctx *link.ContainerContext + cctx, err = link.NewContainerContext(args.ContainerID, args.Netns) if err != nil { return fmt.Errorf("failed to create container context: %v", err) } - response, err := probeEndpointFeature(args, cctx.Driver) + var response *models.EndpointProbeResponse + response, err = probeEndpointFeature(args, cctx.Driver) if err != nil { return fmt.Errorf("failed to exec endpoint probe: %v", err) } @@ -164,46 +139,11 @@ func cmdAdd(args *skel.CmdArgs) error { if err != nil { return fmt.Errorf("failed to set bandwidth: %v", err) } + logger.WithField("result", logfields.Json(conf.PrevResult)).Info("success to exec plugin") // Pass through the result for the next plugin return types.PrintResult(conf.PrevResult, conf.CNIVersion) } -func checkExtStatus(ctx context.Context, args *skel.CmdArgs, featureGates []*models.EndpointProbeFeatureGate) (bool, error) { - cniArgs := plugintypes.ArgsSpec{} - if err := types.LoadArgs(args.Args, &cniArgs); err != nil { - return false, fmt.Errorf("unable to extract CNI arguments: %s", err) - } - var ( - extPluginData map[string]map[string]string - err error - owner = string(cniArgs.K8S_POD_NAMESPACE + "/" + cniArgs.K8S_POD_NAME) - containerID = args.ContainerID - ) - - c, err := client.NewDefaultClientWithTimeout(defaults.ClientConnectTimeout) - if err != nil { - err = fmt.Errorf("unable to connect to cce-network-v2-agent: %s", client.Hint(err)) - return false, err - } - param := endpoint.NewGetEndpointExtpluginStatusParams().WithOwner(&owner).WithContainerID(&containerID).WithContext(ctx) - result, err := c.Endpoint.GetEndpointExtpluginStatus(param) - if err != nil { - err = fmt.Errorf("unable to get endpoint extplugin status: %s", client.Hint(err)) - return false, err - } - extPluginData = result.Payload - for _, featureGate := range featureGates { - if featureGate.WaitReady { - pluginData, ok := extPluginData[featureGate.Name] - if !ok { - return false, nil - } - logger.WithField("feature", featureGate).WithField("pluginData", logfields.Repr(pluginData)).Infof("found feature gate") - } - } - return true, nil -} - func probeEndpointFeature(args *skel.CmdArgs, driver string) (*models.EndpointProbeResponse, error) { cniArgs := plugintypes.ArgsSpec{} if err := types.LoadArgs(args.Args, &cniArgs); err != nil { @@ -231,7 +171,13 @@ func probeEndpointFeature(args *skel.CmdArgs, driver string) (*models.EndpointPr // cmdDel is called for DELETE requests func cmdDel(args *skel.CmdArgs) error { - + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "endpoint-probe", + "mod": "DEL", + }) + logger.Infof("success to exec endpoint-probe") return nil } diff --git a/cce-network-v2/plugins/enim/enim.go b/cce-network-v2/plugins/enim/enim.go index 49914b7..6b93a71 100644 --- a/cce-network-v2/plugins/enim/enim.go +++ b/cce-network-v2/plugins/enim/enim.go @@ -27,10 +27,9 @@ import ( "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/defaults" iputils "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/ip" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" - "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/hooks" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" bv "github.com/containernetworking/plugins/pkg/utils/buildversion" gops "github.com/google/gops/agent" - "github.com/google/uuid" "github.com/sirupsen/logrus" "github.com/containernetworking/cni/pkg/skel" @@ -54,15 +53,24 @@ func cmdAdd(args *skel.CmdArgs) (err error) { inter *current.Interface ) + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "enim", + "mod": "ADD", + }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() n, err = plugintypes.LoadNetConf(args.StdinData) if err != nil { err = fmt.Errorf("unable to parse CNI configuration \"%s\": %s", args.StdinData, err) return } - if innerErr := setupLogging(n, args, "ADD"); innerErr != nil { - err = fmt.Errorf("unable to setup logging: %w", innerErr) - return - } if n.IPAM.EnableDebug { if err := gops.Listen(gops.Options{}); err != nil { @@ -72,9 +80,8 @@ func cmdAdd(args *skel.CmdArgs) (err error) { } } - logger.Debugf("Processing CNI ADD request %#v", args) + logger.Info("processing CNI ADD request") - logger.Debugf("CNI NetConf: %#v", n) if n.PrevResult != nil { logger.Debugf("CNI Previous result: %#v", n.PrevResult) } @@ -135,22 +142,31 @@ func cmdAdd(args *skel.CmdArgs) (err error) { } func cmdDel(args *skel.CmdArgs) error { + var err error + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "enim", + "mod": "DEL", + }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() + // Note about when to return errors: kubelet will retry the deletion // for a long time. Therefore, only return an error for errors which // are guaranteed to be recoverable. - n, err := plugintypes.LoadNetConf(args.StdinData) + var n *plugintypes.NetConf + n, err = plugintypes.LoadNetConf(args.StdinData) if err != nil { err = fmt.Errorf("unable to parse CNI configuration \"%s\": %s", args.StdinData, err) return err } - if err := setupLogging(n, args, "DEL"); err != nil { - return fmt.Errorf("unable to setup logging: %w", err) - } - logger := logging.DefaultLogger.WithField("mod", "DEL") - logger = logger.WithField("eventUUID", uuid.New()). - WithField("containerID", args.ContainerID) - if n.IPAM.EnableDebug { if err := gops.Listen(gops.Options{}); err != nil { logger.WithError(err).Warn("Unable to start gops") @@ -158,23 +174,23 @@ func cmdDel(args *skel.CmdArgs) error { defer gops.Close() } } - logger.Debugf("Processing CNI DEL request %#v", args) - - logger.Debugf("CNI NetConf: %#v", n) + logger.Infof("Processing CNI DEL request %#v", args) cniArgs := plugintypes.ArgsSpec{} if err = cnitypes.LoadArgs(args.Args, &cniArgs); err != nil { return fmt.Errorf("unable to extract CNI arguments: %s", err) } - logger.Debugf("CNI Args: %#v", cniArgs) - c, err := client.NewDefaultClientWithTimeout(defaults.ClientConnectTimeout) + var c *client.Client + c, err = client.NewDefaultClientWithTimeout(defaults.ClientConnectTimeout) if err != nil { // this error can be recovered from return fmt.Errorf("unable to connect to CCE daemon: %s", client.Hint(err)) } owner := cniArgs.K8S_POD_NAMESPACE + "/" + cniArgs.K8S_POD_NAME - return releaseENI(c, string(owner), args.ContainerID, args.Netns) + + err = releaseENI(c, string(owner), args.ContainerID, args.Netns) + return err } func allocateENIWithCCEAgent(client *client.Client, cniArgs plugintypes.ArgsSpec, containerID, netns string) ( @@ -261,40 +277,6 @@ func wrapperENI(ipam *models.IPAMResponse, n *plugintypes.NetConf, isIPv6 bool) }, routes, inter, nil } -func setupLogging(n *plugintypes.NetConf, args *skel.CmdArgs, method string) error { - f := n.IPAM.LogFormat - if f == "" { - f = string(logging.DefaultLogFormat) - } - logOptions := logging.LogOptions{ - logging.FormatOpt: f, - } - if len(n.IPAM.LogFile) != 0 { - err := logging.SetupLogging([]string{}, logOptions, "enim", n.IPAM.EnableDebug) - if err != nil { - return err - } - logging.AddHooks(hooks.NewFileRotationLogHook(n.IPAM.LogFile, - hooks.EnableCompression(), - hooks.WithMaxBackups(1), - )) - } else { - logOptions["syslog.facility"] = "local5" - err := logging.SetupLogging([]string{"syslog"}, logOptions, "enim", true) - if err != nil { - return err - } - } - logger = logging.DefaultLogger.WithFields(logrus.Fields{ - "containerID": args.ContainerID, - "netns": args.Netns, - "plugin": "enim", - "method": method, - }) - - return nil -} - func ipv6IsEnabled(ipam *models.IPAMResponse) bool { if ipam == nil || ipam.Address.IPV6 == "" { return false diff --git a/cce-network-v2/plugins/exclusive-device/exclusive-device.go b/cce-network-v2/plugins/exclusive-device/exclusive-device.go index b939347..22fd7ad 100644 --- a/cce-network-v2/plugins/exclusive-device/exclusive-device.go +++ b/cce-network-v2/plugins/exclusive-device/exclusive-device.go @@ -24,7 +24,6 @@ import ( "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/datapath/link" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" - "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/hooks" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" @@ -49,11 +48,6 @@ var logger *logrus.Entry // NetConf for exclusive-device config, look the README to learn how to use those parameters type NetConf struct { types.NetConf - - // Add plugin-specific flags here - EnableDebug bool `json:"enable-debug"` - LogFormat string `json:"log-format"` - LogFile string `json:"log-file"` } func init() { @@ -73,41 +67,21 @@ func loadConf(bytes []byte) (*NetConf, error) { return n, nil } -func setupLogging(n *NetConf, args *skel.CmdArgs, method string) error { - f := n.LogFormat - if f == "" { - f = string(logging.DefaultLogFormat) - } - logOptions := logging.LogOptions{ - logging.FormatOpt: f, - } - if len(n.LogFile) != 0 { - err := logging.SetupLogging([]string{}, logOptions, "exclude-device", n.EnableDebug) - if err != nil { - return err - } - logging.AddHooks(hooks.NewFileRotationLogHook(n.LogFile, - hooks.EnableCompression(), - hooks.WithMaxBackups(1), - )) - } else { - logOptions["syslog.facility"] = "local5" - err := logging.SetupLogging([]string{"syslog"}, logOptions, "exclude-device", true) - if err != nil { - return err - } - } +func cmdAdd(args *skel.CmdArgs) (err error) { + logging.SetupCNILogging("cni", true) logger = logging.DefaultLogger.WithFields(logrus.Fields{ - "containerID": args.ContainerID, - "netns": args.Netns, - "plugin": "exclude-device", - "method": method, + "cmdArgs": logfields.Json(args), + "plugin": "exclusive-device", + "mod": "ADD", }) + defer func() { + if err != nil { + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") + } + }() - return nil -} - -func cmdAdd(args *skel.CmdArgs) error { cfg, err := loadConf(args.StdinData) if err != nil { return err @@ -116,16 +90,6 @@ func cmdAdd(args *skel.CmdArgs) error { return fmt.Errorf("ipam must be specifed") } - err = setupLogging(cfg, args, "ADD") - if err != nil { - return fmt.Errorf("exclusive-device failed to set up logging: %v", err) - } - defer func() { - if err != nil { - logger.Errorf("cni plugin failed: %v", err) - } - }() - // run the IPAM plugin and get back the config to apply r, err := ipam.ExecAdd(cfg.IPAM.Type, args.StdinData) if err != nil { @@ -194,6 +158,7 @@ func cmdAdd(args *skel.CmdArgs) error { newResult.IPs[0].Interface = &defaultIndex newResult.DNS = cfg.DNS + logger.WithField("result", newResult).Infof("successfully exec plugin") return types.PrintResult(newResult, cfg.CNIVersion) } @@ -203,13 +168,17 @@ func cmdDel(args *skel.CmdArgs) error { return err } - err = setupLogging(cfg, args, "DEL") - if err != nil { - return fmt.Errorf("exclusive-device failed to set up logging: %v", err) - } + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "exclusive-device", + "mod": "DEL", + }) defer func() { if err != nil { - logger.Errorf("cni plugin failed: %v", err) + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") } }() diff --git a/cce-network-v2/plugins/pluginmanager/plugin_manager.go b/cce-network-v2/plugins/pluginmanager/plugin_manager.go new file mode 100644 index 0000000..fe0bf41 --- /dev/null +++ b/cce-network-v2/plugins/pluginmanager/plugin_manager.go @@ -0,0 +1,234 @@ +package pluginmanager + +import ( + "encoding/json" + "fmt" + "os" + + cniTypes "github.com/containernetworking/cni/pkg/types" + "k8s.io/apimachinery/pkg/apis/meta/v1/unstructured" + + ccev2 "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/k8s/apis/cce.baidubce.com/v2" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" + "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/option" +) + +const ( + pluginNameEndpointProbe = "endpoint-probe" + pluginNameCipam = "cipam" + pluginNameCptp = "cptp" + pluginNameEnim = "enim" + pluginNameExclusiveDevice = "exclusive-device" + pluginNameSbrEIP = "sbr-eip" + + // external plugins + pluginNamePortMap = "portmap" + // cilium cni chain plugin + pluginNameCiliumCNI = "cilium-cni" + + // 0.4.0 is the version of CNI spec + defaultCNIVersion = "0.4.0" +) + +var ( + ccePlugins = map[string]CniPlugin{ + pluginNameEndpointProbe: NewCNIPlugin(pluginNameEndpointProbe, nil), + pluginNameCptp: newPtpPlugin(), + pluginNameExclusiveDevice: NewCNIPlugin(pluginNameExclusiveDevice, CniPlugin{ + "ipam": pluginNameEnim, + }), + pluginNameSbrEIP: NewCNIPlugin(pluginNameSbrEIP, nil), + + // exteral plugins + pluginNameCiliumCNI: NewCNIPlugin(pluginNameCiliumCNI, nil), + + // portmap cni plugin is not enabled by default.It is only manually enabled for users + // who want to use portmap feature. + // TODO: if Cilium is enabled, it comes with port map capabilities and no longer + // requires this portmap plugin. + pluginNamePortMap: NewCNIPlugin(pluginNamePortMap, map[string]interface{}{ + "capabilities": map[string]bool{ + "portMappings": true, + }, + "externalSetMarkChain": "KUBE-MARK-MASQ", + }), + } + + log = logging.NewSubysLogger("plugin-manager") +) + +type CniListConfig struct { + cniTypes.NetConf `json:",inline"` + Plugins []CniPlugin `json:"plugins"` +} + +type CniPlugin map[string]interface{} + +func NewCNIPlugin(name string, config CniPlugin) CniPlugin { + plugin := make(CniPlugin) + plugin["type"] = name + for k, v := range config { + plugin[k] = v + } + return plugin +} + +func (plugin CniPlugin) GetType() string { + v, _, _ := unstructured.NestedString(plugin, "type") + return v +} + +// Automatically generate network plugin configuration files for CCE +// 1. defautl cptp plugin +// +// { +// "name":"cce", +// "cniVersion":"0.4.0", +// "plugins":[ +// { +// "type":"cptp", +// "ipam":{ +// "type":"cipam", +// }, +// "mtu": {{ .Values.ccedConfig.mtu }} +// } +// {{- range .Values.extplugins }} +// ,{ +// "type": "{{ .type }}" +// } +// {{- end }} +// ,{ +// "type": "endpoint-probe" +// } +// ] +// } +// +// 2. primary eni plugin +// +// { +// "name":"podlink", +// "cniVersion":"0.4.0", +// "plugins":[ +// { +// "type":"exclusive-device", +// "ipam":{ +// "type":"enim" +// } +// } +// {{- range .Values.extplugins }} +// ,{ +// "type": "{{ .type }}" +// } +// {{- end }} +// ] +// } +func defaultCNIPlugin() *CniListConfig { + result := &CniListConfig{ + NetConf: cniTypes.NetConf{ + CNIVersion: defaultCNIVersion, + Name: "cce", + }, + } + + // primary eni plugin + if option.Config.ENI.UseMode == string(ccev2.ENIUseModePrimaryIP) { + result.Plugins = append(result.Plugins, ccePlugins[pluginNameExclusiveDevice]) + } else { + // use cptp plugin defalt + result.Plugins = append(result.Plugins, newPtpPlugin()) + } + + // add list of extension CNI plugins defined by CCE + for _, pluginName := range option.Config.ExtCNIPluginsList { + if _, ok := ccePlugins[pluginName]; !ok { + log.Errorf("ignored unknown plugin %s", pluginName) + } else { + result.Plugins = append(result.Plugins, ccePlugins[pluginName]) + } + } + + return result +} + +// read cni configlist from user defined path +func readExistsCNIConfigList(path string) (result *CniListConfig, err error) { + result = &CniListConfig{} + byets, err := os.ReadFile(path) + if os.IsNotExist(err) { + err = nil + log.Infof("cni configlist file %s not exists, this file will be ignored", path) + return + } + if err != nil { + err = fmt.Errorf("failed to read cni configlist file %s: %w", path, err) + return + } + + err = json.Unmarshal(byets, &result) + if err != nil { + err = fmt.Errorf("failed to unmarshal cni configlist file %s: %w", path, err) + } + return +} + +func OverwriteCNIConfigList(path string) (override bool, err error) { + exsistConfig, err := readExistsCNIConfigList(path) + if err != nil { + log.WithError(err).Warnf("ignore cni configlist file %s", path) + err = nil + } + // merge exsistConfig and defaultCNIPlugin + defaultConfig := defaultCNIPlugin() + + // search for user defined plugins + if exsistConfig != nil { + for i := range exsistConfig.Plugins { + plugin := exsistConfig.Plugins[i] + if _, ok := ccePlugins[plugin.GetType()]; !ok { + log.Infof("detected user defined plugin %s", plugin.GetType()) + defaultConfig.Plugins = append(defaultConfig.Plugins, plugin) + } + } + } + + if jsonEqual(exsistConfig.Plugins, defaultConfig.Plugins) { + return false, nil + } + + // write to cni configlist file + byets, err := json.MarshalIndent(defaultConfig, "", " ") + if err != nil { + err = fmt.Errorf("failed to marshal cni configlist: %w", err) + return + } + + log.Infof("cni config is: %s", string(byets)) + err = os.WriteFile(path, byets, 0644) + if err != nil { + err = fmt.Errorf("failed to write cni configlist: %w", err) + return + } + + return true, nil +} + +// create new cptp plugin template +func newPtpPlugin() CniPlugin { + plugin := NewCNIPlugin(pluginNameCptp, CniPlugin{ + "ipam": NewCNIPlugin(pluginNameCipam, nil), + "mtu": option.Config.MTU, + }) + return plugin +} + +func jsonEqual(a, b interface{}) bool { + aBytes, err := json.Marshal(a) + if err != nil { + return false + } + bBytes, err := json.Marshal(b) + if err != nil { + return false + } + return string(aBytes) == string(bBytes) +} diff --git a/cce-network-v2/plugins/sbr-eip/sbr_eip.go b/cce-network-v2/plugins/sbr-eip/sbr_eip.go index 8056809..eac2d2f 100644 --- a/cce-network-v2/plugins/sbr-eip/sbr_eip.go +++ b/cce-network-v2/plugins/sbr-eip/sbr_eip.go @@ -27,7 +27,6 @@ import ( plugintypes "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/cni/types" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/defaults" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging" - "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/hooks" "github.com/baidubce/baiducloud-cce-cni-driver/cce-network-v2/pkg/logging/logfields" "github.com/containernetworking/cni/pkg/skel" "github.com/containernetworking/cni/pkg/types" @@ -127,40 +126,6 @@ func parseConfig(stdin []byte) (*PluginConf, error) { return &conf, nil } -func setupLogging(n *PluginConf, args *skel.CmdArgs, method string) error { - f := n.LogFormat - if f == "" { - f = string(logging.DefaultLogFormat) - } - logOptions := logging.LogOptions{ - logging.FormatOpt: f, - } - if len(n.LogFile) != 0 { - err := logging.SetupLogging([]string{}, logOptions, "sbr-eip", n.EnableDebug) - if err != nil { - return err - } - logging.AddHooks(hooks.NewFileRotationLogHook(n.LogFile, - hooks.EnableCompression(), - hooks.WithMaxBackups(1), - )) - } else { - logOptions["syslog.facility"] = "local5" - err := logging.SetupLogging([]string{"syslog"}, logOptions, "sbr-eip", true) - if err != nil { - return err - } - } - logger = logging.DefaultLogger.WithFields(logrus.Fields{ - "containerID": args.ContainerID, - "netns": args.Netns, - "plugin": "sbr-eip", - "method": method, - }) - - return nil -} - // getIPCfgs finds the IPs on the supplied interface, returning as IPConfig structures func getIPCfgs(iface string, prevResult *current.Result) ([]*current.IPConfig, error) { if len(prevResult.IPs) == 0 { @@ -190,20 +155,25 @@ func getIPCfgs(iface string, prevResult *current.Result) ([]*current.IPConfig, e } // cmdAdd is called for ADD requests -func cmdAdd(args *skel.CmdArgs) error { - conf, err := parseConfig(args.StdinData) - if err != nil { - return fmt.Errorf("sbnr-eip failed to parse config: %v", err) - } - err = setupLogging(conf, args, "ADD") - if err != nil { - return fmt.Errorf("sbr-eip failed to set up logging: %v", err) - } +func cmdAdd(args *skel.CmdArgs) (err error) { + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "sbr-eip", + "mod": "ADD", + }) defer func() { if err != nil { - logger.Errorf("cni plugin failed: %v", err) + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") } }() + + conf, err := parseConfig(args.StdinData) + if err != nil { + return fmt.Errorf("sbnr-eip failed to parse config: %v", err) + } logger.Debugf("configure SBR for new interface %s - previous result: %v", args.IfName, conf.PrevResult) @@ -461,19 +431,18 @@ func doRoutes(ipCfg *current.IPConfig, iface string) error { } // cmdDel is called for DELETE requests -func cmdDel(args *skel.CmdArgs) error { - // We care a bit about config because it sets log level. - conf, err := parseConfig(args.StdinData) - if err != nil { - return err - } - err = setupLogging(conf, args, "DEL") - if err != nil { - return fmt.Errorf("sbr-eip failed to set up logging: %v", err) - } +func cmdDel(args *skel.CmdArgs) (err error) { + logging.SetupCNILogging("cni", true) + logger = logging.DefaultLogger.WithFields(logrus.Fields{ + "cmdArgs": logfields.Json(args), + "plugin": "sbr-eip", + "mod": "ADD", + }) defer func() { if err != nil { - logger.Errorf("cni plugin failed: %v", err) + logger.WithError(err).Error("failed to exec plugin") + } else { + logger.Info("successfully to exec plugin") } }() diff --git a/cce-network-v2/tools/cni-arm/loopback b/cce-network-v2/tools/cni-arm/loopback new file mode 100755 index 0000000..23c43c2 Binary files /dev/null and b/cce-network-v2/tools/cni-arm/loopback differ diff --git a/cce-network-v2/tools/cni-arm/portmap b/cce-network-v2/tools/cni-arm/portmap new file mode 100755 index 0000000..23c2114 Binary files /dev/null and b/cce-network-v2/tools/cni-arm/portmap differ diff --git a/cce-network-v2/tools/cni-plugins-linux-arm64-v1.4.0.tgz b/cce-network-v2/tools/cni-plugins-linux-arm64-v1.4.0.tgz new file mode 100644 index 0000000..51bc3a4 Binary files /dev/null and b/cce-network-v2/tools/cni-plugins-linux-arm64-v1.4.0.tgz differ diff --git a/go.work b/go.work index bf853e0..b2aa69d 100644 --- a/go.work +++ b/go.work @@ -1,5 +1,8 @@ go 1.20 -use ./cce-network-v2 +use ( + ./cce-network-v2 + ./eip-operator + ./bce-sdk-go +) -use ./eip-operator diff --git a/go.work.sum b/go.work.sum index 0887e1e..fcc0ce9 100644 --- a/go.work.sum +++ b/go.work.sum @@ -51,6 +51,8 @@ github.com/armon/go-metrics v0.3.10/go.mod h1:4O98XIr/9W0sxpJ8UaYkvjk10Iff7SnFrb github.com/armon/go-radix v0.0.0-20180808171621-7fddfc383310 h1:BUAU3CGlLvorLI26FmByPp2eC2qla6E1Tw+scpcg/to= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5 h1:0CwZNZbxp69SHPdPJAN/hZIm0C4OItdklCFmMRWYpio= github.com/armon/go-socks5 v0.0.0-20160902184237-e75332964ef5/go.mod h1:wHh0iHkYZB8zMSxRWpUBQtwG5a7fFgvEO+odwuTv2gs= +github.com/baidubce/bce-sdk-go v0.9.165 h1:Erzw2lQ95Np9llvKtPNSZci3dbQK6OHn5kNFxUmBpnQ= +github.com/baidubce/bce-sdk-go v0.9.165/go.mod h1:zbYJMQwE4IZuyrJiFO8tO8NbtYiKTFTbwh4eIsqjVdg= github.com/bgentry/speakeasy v0.1.0 h1:ByYyxL9InA1OWqxJqqp2A5pYHUrCiAL6K3J+LKSsQkY= github.com/bketelsen/crypt v0.0.4 h1:w/jqZtC9YD4DS/Vp9GhWfWcCpuAL58oTnLoI8vE9YHU= github.com/blang/semver v3.5.1+incompatible h1:cQNTCjp13qL8KC3Nbxr/y2Bqb63oX6wdnnjpJbkM4JQ= @@ -219,6 +221,8 @@ github.com/klauspost/compress v1.13.6 h1:P76CopJELS0TiO2mebmnzgWaajssP/EszplttgQ github.com/konsorten/go-windows-terminal-sequences v1.0.3 h1:CE8S1cTafDpPvMhIxNJKvHsGVBgn1xWYf1NbHQhywc8= github.com/kr/fs v0.1.0 h1:Jskdu9ieNAYnjxsi0LbQp1ulIKZV1LAFgK1tWhpZgl8= github.com/kr/logfmt v0.0.0-20140226030751-b84e30acd515 h1:T+h1c/A9Gawja4Y9mFVWj2vyii2bbUNDw3kt9VxK2EY= +github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= +github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/pty v1.1.5 h1:hyz3dwM5QLc1Rfoz4FuWJQG5BN7tc6K1MndAUnGpQr4= github.com/markbates/oncer v0.0.0-20181203154359-bf2de49a0be2 h1:JgVTCPf0uBVcUSWpyXmGpgOc62nK5HWUBKAGc3Qqa5k= github.com/markbates/safe v1.0.1 h1:yjZkbvRM6IzKj9tlu/zMJLS0n/V351OZWRnF3QfaUxI= @@ -263,6 +267,8 @@ github.com/prometheus/client_golang v1.12.2/go.mod h1:3Z9XVyYiZYEO+YQWt3RD2R3jrb github.com/prometheus/client_model v0.2.1-0.20210607210712-147c58e9608a/go.mod h1:LDGWKZIo7rky3hgvBe+caln+Dr3dPggB5dvjtD7w9+w= github.com/prometheus/tsdb v0.7.1 h1:YZcsG11NqnK4czYLrWd9mpEuAJIHVQLwdrleYfszMAA= github.com/rogpeppe/fastuuid v1.2.0 h1:Ppwyp6VYCF1nvBTXL3trRso7mXMlRrw9ooo375wvi2s= +github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8= +github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs= github.com/ryanuber/columnize v0.0.0-20160712163229-9b3edd62028f h1:UFr9zpz4xgTnIE5yIMtWAMngCdZ9p/+q6lTbgelo80M= github.com/sagikazarmark/crypt v0.6.0 h1:REOEXCs/NFY/1jOCEouMuT4zEniE5YoXbvpC5X/TLF8= github.com/sagikazarmark/crypt v0.6.0/go.mod h1:U8+INwJo3nBv1m6A/8OBXAq7Jnpspk5AxSgDyEQcea8= @@ -284,6 +290,7 @@ github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802 h1:uruHq4 github.com/tmc/grpc-websocket-proxy v0.0.0-20201229170055-e5319fda7802/go.mod h1:ncp9v5uamzpCO7NfCPTXjqaC+bZgJeR0sMTm6dMHP7U= github.com/urfave/cli v1.20.0 h1:fDqGv3UG/4jbVl/QkFwEdddtEDjh/5Ov6X+0B/3bPaw= github.com/vishvananda/netlink v1.1.1-0.20220125195016-0639e7e787ba/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= +github.com/vishvananda/netlink v1.2.1-beta.2.0.20220608195807-1a118fe229fc/go.mod h1:twkDnbuQxJYemMlGd4JFIcuhgX83tXhKS2B/PRMpOho= github.com/xdg-go/pbkdf2 v1.0.0 h1:Su7DPu48wXMwC3bs7MCNG+z4FhcyEuz5dlvchbq0B0c= github.com/xdg-go/scram v1.1.1 h1:VOMT+81stJgXW3CpHyqHN3AXDYIMsx56mEFrB37Mb/E= github.com/xdg-go/stringprep v1.0.3 h1:kdwGpVNwPFtjs98xCGkHjQtGKh86rDcRZN17QEMCOIs= @@ -383,6 +390,8 @@ golang.org/x/sys v0.0.0-20220919091848-fb04ddd9f9c8/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.1.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.3.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.14.1-0.20231108175955-e4099bfacb8c h1:3kC/TjQ+xzIblQv39bCOyRk8fbEeJcDHwbyxPUU2BpA= +golang.org/x/sys v0.14.1-0.20231108175955-e4099bfacb8c/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= golang.org/x/term v0.3.0/go.mod h1:q750SLmJuPmVoN1blW3UFBPREJfb1KmY3vwxfr+nFDA= golang.org/x/text v0.5.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20220210224613-90d013bbcef8/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=