From bc1fd7bd8734d878258fcacd79e04afe6b619bfe Mon Sep 17 00:00:00 2001 From: duanliguo Date: Tue, 14 Jul 2020 12:39:37 +0800 Subject: [PATCH] Add rds service and some features in bbc and bcc --- README.md | 4 +- bce/config.go | 2 +- doc/RDS.md | 743 +++++++++++++++++++++++++++++++++++ init.go | 1 + services/bbc/client_test.go | 2 + services/bbc/model.go | 27 +- services/bcc/api/instance.go | 279 ++++++++++++- services/bcc/api/model.go | 82 +++- services/bcc/api/other.go | 1 + services/bcc/api/util.go | 44 +++ services/bcc/client.go | 194 ++++++++- services/bcc/client_test.go | 118 +++++- services/rds/client.go | 50 +++ services/rds/client_test.go | 212 ++++++++++ services/rds/model.go | 193 +++++++++ services/rds/rds.go | 291 ++++++++++++++ services/rds/util.go | 35 ++ services/sts/client.go | 2 + 18 files changed, 2249 insertions(+), 31 deletions(-) create mode 100644 doc/RDS.md create mode 100644 services/rds/client.go create mode 100644 services/rds/client_test.go create mode 100644 services/rds/model.go create mode 100644 services/rds/rds.go create mode 100644 services/rds/util.go diff --git a/README.md b/README.md index 854f8841..187a07e7 100644 --- a/README.md +++ b/README.md @@ -46,6 +46,7 @@ bce-sdk-go | |--cfc //函数计算 | |--eip //弹性公网IP | |--etGateway //专线网关 +| |--rds //云数据库 | |--scs //SCS服务目录 | |--sts //STS服务目录 | |--vca //VCA服务目录 @@ -235,9 +236,10 @@ SSL证书服务 | CERT | github.com/baidubce/bce-sdk-go/services/cert | [CERT.md 函数计算 | CFC | github.com/baidubce/bce-sdk-go/services/cfc | [CFC.md](./doc/CFC.md) 弹性公网IP | EIP | github.com/baidubce/bce-sdk-go/services/eip | [EIP.md](./doc/EIP.md) 专线网关 | EtGateway | github.com/baidubce/bce-sdk-go/services/etGateway | [ETGateway.md](./doc/ETGateway.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) 安全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) \ No newline at end of file +VPN网关 | VPN | github.com/baidubce/bce-sdk-go/services/vpn | [VPN.md](./doc/VPN.md) diff --git a/bce/config.go b/bce/config.go index fda6badd..6a5a4121 100644 --- a/bce/config.go +++ b/bce/config.go @@ -26,7 +26,7 @@ import ( // Constants and default values for the package bce const ( - SDK_VERSION = "0.9.12" + SDK_VERSION = "0.9.15" URI_PREFIX = "/" // now support uri without prefix "v1" so just set root path DEFAULT_DOMAIN = "baidubce.com" DEFAULT_PROTOCOL = "http" diff --git a/doc/RDS.md b/doc/RDS.md new file mode 100644 index 00000000..016253c4 --- /dev/null +++ b/doc/RDS.md @@ -0,0 +1,743 @@ +# RDS服务 + +# 概述 + +本文档主要介绍RDS GO SDK的使用。在使用本文档前,您需要先了解RDS的一些基本知识,并已开通了RDS服务。若您还不了解RDS,可以参考[产品描述](https://cloud.baidu.com/doc/RDS/s/ujwvyzdzg)和[操作指南](https://cloud.baidu.com/doc/RDS/s/Qjwvz0ikk)。 + +# 初始化 + +## 确认Endpoint + +在确认您使用SDK时配置的Endpoint时,可先阅读开发人员指南中关于[RDS服务域名](https://cloud.baidu.com/doc/RDS/s/Ejwvz0uoq)的部分,理解Endpoint相关的概念。百度云目前开放了多区域支持,请参考[区域选择说明](https://cloud.baidu.com/doc/Reference/s/2jwvz23xx/)。 + +目前支持“华北-北京”、“华南-广州”、“华东-苏州”和“金融华中-武汉”四个区域。对应信息为: + +访问区域 | 对应Endpoint | 协议 +---|---|--- +BJ | rds.bj.baidubce.com | HTTP and HTTPS +GZ | rds.gz.baidubce.com | HTTP and HTTPS +SU | rds.su.baidubce.com | HTTP and HTTPS +FWH| rds.fwh.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(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`参数需要用指定区域的域名来进行定义,如服务所在区域为北京,则为`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"}, + }, + // CPU核数,必选 + CpuCount: 1, + //套餐内存大小,单位GB,必选 + MemoryCapacity: 1, + //套餐磁盘大小,单位GB,每5G递增,必选 + VolumeCapacity: 5, + //批量创建云数据库 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: ["cn-bj-a"], + //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: ["cn-bj-a"], + //与主实例 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: ["cn-bj-a"], + //与主实例 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 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" + +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" + +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语言以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/init.go b/init.go index 4a7323f4..52321abb 100644 --- a/init.go +++ b/init.go @@ -35,6 +35,7 @@ import ( _ "github.com/baidubce/bce-sdk-go/services/dcc" _ "github.com/baidubce/bce-sdk-go/services/eip" _ "github.com/baidubce/bce-sdk-go/services/etGateway" + _ "github.com/baidubce/bce-sdk-go/services/rds" _ "github.com/baidubce/bce-sdk-go/services/scs" _ "github.com/baidubce/bce-sdk-go/services/sts" _ "github.com/baidubce/bce-sdk-go/services/vca" diff --git a/services/bbc/client_test.go b/services/bbc/client_test.go index 9e4903e5..6c500c82 100644 --- a/services/bbc/client_test.go +++ b/services/bbc/client_test.go @@ -93,6 +93,7 @@ func ExpectEqual(alert func(format string, args ...interface{}), } func TestCreateInstance(t *testing.T) { + InternalIps := []string{"ip"} createInstanceArgs := &CreateInstanceArgs{ FlavorId: BBC_TestFlavorId, ImageId: BBC_TestImageId, @@ -107,6 +108,7 @@ func TestCreateInstance(t *testing.T) { }, DeploySetId: BBC_TestDeploySetId, Name: BBC_TestName, + InternalIps: InternalIps, } res, err := BBC_CLIENT.CreateInstance(createInstanceArgs) fmt.Println(res) diff --git a/services/bbc/model.go b/services/bbc/model.go index 27396d3c..5cc2cb33 100644 --- a/services/bbc/model.go +++ b/services/bbc/model.go @@ -57,19 +57,20 @@ const ( ) 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"` - Billing Billing `json:"billing"` - Name string `json:"name,omitempty"` - AdminPass string `json:"adminPass,omitempty"` - DeploySetId string `json:"deploySetId,omitempty"` - ClientToken string `json:"-"` - SecurityGroupId string `json:"securityGroupId,omitempty"` + 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"` + Billing Billing `json:"billing"` + Name string `json:"name,omitempty"` + AdminPass string `json:"adminPass,omitempty"` + DeploySetId string `json:"deploySetId,omitempty"` + ClientToken string `json:"-"` + SecurityGroupId string `json:"securityGroupId,omitempty"` + InternalIps []string `json:"internalIps,omitempty"` } type Billing struct { diff --git a/services/bcc/api/instance.go b/services/bcc/api/instance.go index bbefbbff..b2301b81 100644 --- a/services/bcc/api/instance.go +++ b/services/bcc/api/instance.go @@ -127,6 +127,9 @@ func ListInstances(cli bce.Client, args *ListInstanceArgs) (*ListInstanceResult, 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") @@ -536,12 +539,14 @@ func GetInstanceVNC(cli bce.Client, instanceId string) (*GetInstanceVNCResult, e // - reqBody: the request body to renew instance // RETURNS: // - error: nil if success otherwise the specific error -func InstancePurchaseReserved(cli bce.Client, instanceId, clientToken string, reqBody *bce.Body) error { +func InstancePurchaseReserved(cli bce.Client, instanceId, relatedRenewFlag, clientToken string, + reqBody *bce.Body) 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 != "" { @@ -670,3 +675,275 @@ func BatchDelIp(cli bce.Client, reqBody *bce.Body) error { 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 +} + diff --git a/services/bcc/api/model.go b/services/bcc/api/model.go index 5d96981b..97f0fc40 100644 --- a/services/bcc/api/model.go +++ b/services/bcc/api/model.go @@ -51,12 +51,14 @@ const ( type StorageType string const ( - StorageTypeStd1 StorageType = "std1" - StorageTypeHP1 StorageType = "hp1" - StorageTypeCloudHP1 StorageType = "cloud_hp1" - StorageTypeLocal StorageType = "local" - StorageTypeSATA StorageType = "sata" - StorageTypeSSD StorageType = "ssd" + 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 PaymentTimingType string @@ -64,6 +66,7 @@ type PaymentTimingType string const ( PaymentTimingPrePaid PaymentTimingType = "Prepaid" PaymentTimingPostPaid PaymentTimingType = "Postpaid" + PaymentTimingBidding PaymentTimingType = "bidding" ) // Instance define instance model @@ -95,6 +98,7 @@ type InstanceModel struct { KeypairName string `json:"keypairName"` DedicatedHostId string `json:"dedicatedHostId"` Tags []model.TagModel `json:"tags"` + Ipv6 string `json:"ipv6"` } type Reservation struct { @@ -146,8 +150,13 @@ type CreateInstanceArgs struct { CdsAutoRenew bool `json:"cdsAutoRenew"` RelationTag bool `json:"relationTag,omitempty"` Tags []model.TagModel `json:"tags,omitempty"` - KeypairId string `json:"keypairId,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"` + InternalIps []string `json:"internalIps,omitempty"` ClientToken string `json:"-"` } @@ -177,6 +186,8 @@ type CreateInstanceBySpecArgs struct { AutoRenewTimeUnit string `json:"autoRenewTimeUnit"` AutoRenewTime int `json:"autoRenewTime"` CdsAutoRenew bool `json:"cdsAutoRenew"` + AspId string `json:"aspId"` + InternalIps []string `json:"internalIps,omitempty"` ClientToken string `json:"-"` } @@ -190,6 +201,7 @@ type ListInstanceArgs struct { InternalIp string DedicatedHostId string ZoneName string + KeypairId string } type ListInstanceResult struct { @@ -208,16 +220,19 @@ type ResizeInstanceArgs struct { CpuCount int `json:"cpuCount"` MemoryCapacityInGB int `json:"memoryCapacityInGB"` EphemeralDisks []EphemeralDisk `json:"ephemeralDisks,omitempty"` + Spec string `json:"spec"` ClientToken string `json:"-"` } type RebuildInstanceArgs struct { ImageId string `json:"imageId"` AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId"` } type StopInstanceArgs struct { - ForceStop bool `json:"forceStop"` + ForceStop bool `json:"forceStop"` + StopWithNoCharge bool `json:"stopWithNoCharge"` } type ChangeInstancePassArgs struct { @@ -241,10 +256,21 @@ type GetInstanceVNCResult struct { } 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"` @@ -347,6 +373,7 @@ type VolumeModel struct { SourceSnapshotId string `json:"sourceSnapshotId"` SnapshotNum string `json:"snapshotNum"` Tags []model.TagModel `json:"tags"` + Encrypted bool `json:"encrypted"` } type VolumeAttachmentModel struct { @@ -369,6 +396,7 @@ type CreateCDSVolumeArgs struct { CdsSizeInGB int `json:"cdsSizeInGB,omitempty"` StorageType StorageType `json:"storageType,omitempty"` Billing *Billing `json:"billing"` + EncryptKey string `json:"encryptKey"` ClientToken string `json:"-"` } @@ -385,8 +413,9 @@ type AttachVolumeArgs struct { } type ResizeCSDVolumeArgs struct { - NewCdsSizeInGB int `json:"newCdsSizeInGB"` - ClientToken string `json:"-"` + NewCdsSizeInGB int `json:"newCdsSizeInGB"` + NewVolumeType StorageType `json:"newVolumeType"` + ClientToken string `json:"-"` } type RollbackCSDVolumeArgs struct { @@ -719,3 +748,36 @@ type AzIntstanceStatis struct { type GetDeploySetResult struct { DeploySetModel } + +type RebuildBatchInstanceArgs struct { + ImageId string `json:"imageId"` + AdminPass string `json:"adminPass"` + KeypairId string `json:"keypairId"` + InstanceIds []string `json:"instanceIds"` +} + +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"` +} diff --git a/services/bcc/api/other.go b/services/bcc/api/other.go index 2d2875fc..f9727d29 100644 --- a/services/bcc/api/other.go +++ b/services/bcc/api/other.go @@ -81,3 +81,4 @@ func ListZone(cli bce.Client) (*ListZoneResult, error) { return jsonBody, nil } + diff --git a/services/bcc/api/util.go b/services/bcc/api/util.go index a1bf91d5..de5ae788 100644 --- a/services/bcc/api/util.go +++ b/services/bcc/api/util.go @@ -43,6 +43,14 @@ const ( REQUEST_VNC_SUFFIX = "/vnc" REQUEST_VOLUME_URI = "/volume" REQUEST_ZONE_URI = "/zone" + REQUEST_FLAVOR_SPEC_URI = "/instance/flavorSpec" + REQUEST_INSTANCE_PRICE_URI = "/instance/price" + REQUEST_INSTANCE_BY_SPEC_URI = "/instanceBySpec" + REQUEST_REBUILD_URI = "/rebuild" + REQUEST_TAG_URI = "/tag" + REQUEST_NOCHARGE_URI = "/noCharge" + REQUEST_BID_URI = "/bid" + REQUEST_CANCEL_BIDORDER_URI = "/cancelBidOrder" ) func getInstanceUri() string { @@ -137,3 +145,39 @@ func getZoneUri() string { func getChangeSubnetUri() string { return URI_PREFIX + REQUEST_SUBNET_URI + "/changeSubnet" } + +func getFlavorSpecUri() string { + return URI_PREFIX + REQUEST_FLAVOR_SPEC_URI +} + +func getPriceBySpecUri() string { + return URI_PREFIX + REQUEST_INSTANCE_PRICE_URI +} + +func getResizeInstanceBySpec(id string) string { + return URI_PREFIX + REQUEST_INSTANCE_BY_SPEC_URI + "/" + id +} + +func getRebuildBatchInstanceUri() string { + return URI_PREFIX + REQUEST_INSTANCE_URI + REQUEST_REBUILD_URI +} + +func getChangeToPrepaidUri(id string) string { + return URI_PREFIX + REQUEST_INSTANCE_URI + "/" + id +} + +func getbindInstanceToTagsUri(id string) string { + return URI_PREFIX + REQUEST_INSTANCE_URI + "/" + id + REQUEST_TAG_URI +} + +func GetInstanceNoChargeListUri() string { + return URI_PREFIX + REQUEST_INSTANCE_URI + REQUEST_NOCHARGE_URI +} + +func GetCreateBidInstanceUri() string { + return URI_PREFIX + REQUEST_INSTANCE_URI + REQUEST_BID_URI +} + +func GetCancelBidOrderUri() string { + return URI_PREFIX + REQUEST_INSTANCE_URI + REQUEST_CANCEL_BIDORDER_URI +} diff --git a/services/bcc/client.go b/services/bcc/client.go index 0a564e15..6a176016 100644 --- a/services/bcc/client.go +++ b/services/bcc/client.go @@ -206,6 +206,32 @@ 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: @@ -389,6 +415,7 @@ func (c *Client) GetInstanceVNC(instanceId string) (*api.GetInstanceVNCResult, e func (c *Client) InstancePurchaseReserved(instanceId string, args *api.PurchaseReservedArgs) error { // this api only support Prepaid instance args.Billing.PaymentTiming = api.PaymentTimingPrePaid + relatedRenewFlag := args.RelatedRenewFlag jsonBytes, jsonErr := json.Marshal(args) if jsonErr != nil { @@ -399,7 +426,7 @@ func (c *Client) InstancePurchaseReserved(instanceId string, args *api.PurchaseR return err } - return api.InstancePurchaseReserved(c, instanceId, args.ClientToken, body) + return api.InstancePurchaseReserved(c, instanceId, relatedRenewFlag, args.ClientToken, body) } // DeleteInstanceWithRelateResource - delete an instance and all eip/cds relate it @@ -976,4 +1003,169 @@ func (c *Client) ModifyDeploySet(deploySetId string, args *api.ModifyDeploySetAr // - error: nil if success otherwise the specific error func (c *Client) DeleteDeploySet(deploySetId string) error { return api.DeleteDeploySet(c, deploySetId) +} + +// 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 { + 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) +} + +// 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) } \ No newline at end of file diff --git a/services/bcc/client_test.go b/services/bcc/client_test.go index 7528e162..657252c1 100644 --- a/services/bcc/client_test.go +++ b/services/bcc/client_test.go @@ -9,6 +9,7 @@ import ( "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" ) @@ -36,7 +37,7 @@ func init() { for i := 0; i < 7; i++ { f = filepath.Dir(f) } - conf := filepath.Join(f, "config.json") + conf := filepath.Join(f, "/go_conf.json") fmt.Println(conf) fp, err := os.Open(conf) if err != nil { @@ -80,9 +81,9 @@ func ExpectEqual(alert func(format string, args ...interface{}), } func TestCreateInstance(t *testing.T) { + InternalIps := []string{"ip"} createInstanceArgs := &api.CreateInstanceArgs{ - DeployId: "DeployId", - ImageId: "ImageId", + ImageId: "ImageId", Billing: api.Billing{ PaymentTiming: api.PaymentTimingPostPaid, }, @@ -97,6 +98,8 @@ func TestCreateInstance(t *testing.T) { RelationTag: true, PurchaseCount: 1, Name: "sdkTest", + KeypairId: "KeypairId", + InternalIps: InternalIps, } createResult, err := BCC_CLIENT.CreateInstance(createInstanceArgs) ExpectEqual(t.Errorf, err, nil) @@ -168,7 +171,7 @@ func TestResizeInstance(t *testing.T) { } func TestStopInstance(t *testing.T) { - err := BCC_CLIENT.StopInstance(BCC_TestBccId, true) + err := BCC_CLIENT.StopInstance(BCC_TestBccId, true, true) ExpectEqual(t.Errorf, err, nil) } @@ -258,6 +261,7 @@ func TestCreateCDSVolume(t *testing.T) { Billing: &api.Billing{ PaymentTiming: api.PaymentTimingPostPaid, }, + EncryptKey: "EncryptKey", } result, err := BCC_CLIENT.CreateCDSVolume(args) @@ -368,6 +372,7 @@ func TestDetachCDSVolume(t *testing.T) { func TestResizeCDSVolume(t *testing.T) { args := &api.ResizeCSDVolumeArgs{ NewCdsSizeInGB: 100, + NewVolumeType: api.StorageTypeHdd, } err := BCC_CLIENT.ResizeCDSVolume(BCC_TestCdsId, args) @@ -587,3 +592,108 @@ func TestDeleteDeploySet(t *testing.T) { fmt.Println(err) 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 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, + }, + }, + } + err := BCC_CLIENT.InstancePurchaseReserved(BCC_TestBccId, api.RelatedRenewFlagCDS, purchaseReservedArgs) + ExpectEqual(t.Errorf, err, nil) +} diff --git a/services/rds/client.go b/services/rds/client.go new file mode 100644 index 00000000..f1f98677 --- /dev/null +++ b/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 +} \ No newline at end of file diff --git a/services/rds/client_test.go b/services/rds/client_test.go new file mode 100644 index 00000000..1fa86cae --- /dev/null +++ b/services/rds/client_test.go @@ -0,0 +1,212 @@ +package rds + +import ( + "encoding/json" + "github.com/baidubce/bce-sdk-go/util" + "os" + "path/filepath" + "reflect" + "runtime" + "testing" + "time" + + "github.com/baidubce/bce-sdk-go/util/log" +) + +var ( + RDS_CLIENT *Client + RDS_ID 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 +} + +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) + + 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) { + args := &CreateRdsArgs{ + Engine: "mysql", + EngineVersion: "5.6", + CpuCount: 1, + MemoryCapacity: 1, + VolumeCapacity: 5, + Billing: Billing{ + PaymentTiming: "Postpaid", + }, + ClientToken: getClientToken(), + } + result, err := RDS_CLIENT.CreateRds(args) + ExpectEqual(t.Errorf, nil, err) + + RDS_ID = result.InstanceIds[0] + 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) + 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_ID) + 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_DeleteAccount(t *testing.T) { + err := RDS_CLIENT.DeleteAccount(RDS_ID,ACCOUNT_NAME) + 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_DeleteRds(t *testing.T) { + time.Sleep(30*time.Second) + isAvailable(RDS_ID) + err := RDS_CLIENT.DeleteRds(RDS_ID) + 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 + } + } +} \ No newline at end of file diff --git a/services/rds/model.go b/services/rds/model.go new file mode 100644 index 00000000..6f9acc06 --- /dev/null +++ b/services/rds/model.go @@ -0,0 +1,193 @@ +/* + * 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"` + 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"` +} + +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 CreateResult struct { + InstanceIds []string `json:"instanceIds"` +} + +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"` +} + +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"` +} + +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"` + Category string `json:"category"` + InstanceStatus string `json:"instanceStatus"` + CpuCount int `json:"cpuCount"` + MemoryCapacity float64 `json:"memoryCapacity"` + VolumeCapacity int `json:"volumeCapacity"` + 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"` + PaymentTiming string `json:"paymentTiming"` +} + +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 string `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"` +} + +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"` + Remark string `json:"remark"` + 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"` +} diff --git a/services/rds/rds.go b/services/rds/rds.go new file mode 100644 index 00000000..dd27ea34 --- /dev/null +++ b/services/rds/rds.go @@ -0,0 +1,291 @@ +/* + * 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" +) + +// 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). + 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",""). + 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",""). + 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", ""). + 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). + 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 +} + +// 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(getRdsUriWithInstanceId(instanceId) + "/account/" + accountName). + Do() +} \ No newline at end of file diff --git a/services/rds/util.go b/services/rds/util.go new file mode 100644 index 00000000..2b075242 --- /dev/null +++ b/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 +} \ No newline at end of file diff --git a/services/sts/client.go b/services/sts/client.go index 060ef1d0..3e88c2d0 100644 --- a/services/sts/client.go +++ b/services/sts/client.go @@ -43,6 +43,7 @@ func (c *Client) GetSessionToken(duration int, acl string) (*api.GetSessionToken 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 { @@ -64,6 +65,7 @@ func NewStsClient(ak, sk, endpoint string) (*Client, error) { Retry: bce.DEFAULT_RETRY_POLICY, ConnectionTimeoutInMillis: bce.DEFAULT_CONNECTION_TIMEOUT_IN_MILLIS} v1Signer := &auth.BceV1Signer{} + client := &Client{bce.NewBceClient(defaultConf, v1Signer)} return client, nil }