init model

This commit is contained in:
ioito
2019-07-25 13:50:51 +08:00
parent 90d6adff23
commit f316d298ad
77 changed files with 35938 additions and 21 deletions
+141
View File
@@ -0,0 +1,141 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 shell
import (
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/modules"
"yunion.io/x/onecloud/pkg/mcclient/options"
)
func init() {
type DBInstanceListOptions struct {
options.BaseListOptions
BillingType string `help:"billing type" choices:"postpaid|prepaid"`
}
R(&DBInstanceListOptions{}, "dbinstance-list", "List DB instance", func(s *mcclient.ClientSession, opts *DBInstanceListOptions) error {
params, err := options.ListStructToParams(opts)
if err != nil {
return err
}
result, err := modules.DBInstance.List(s, params)
if err != nil {
return err
}
printList(result, modules.DBInstance.GetColumns(s))
return nil
})
type DBInstanceNetworkListOptions struct {
options.BaseListOptions
DBInstance string `help:"ID or Name of DBInstance" json:"dbinstance"`
Network string `help:"Network ID or name"`
}
R(&DBInstanceNetworkListOptions{}, "dbinstance-network-list", "List DB instance networks", func(s *mcclient.ClientSession, opts *DBInstanceNetworkListOptions) error {
params, err := options.ListStructToParams(opts)
if err != nil {
return err
}
var result *modules.ListResult
if len(opts.DBInstance) > 0 {
result, err = modules.DBInstanceNetworks.ListDescendent(s, opts.DBInstance, params)
} else if len(opts.Network) > 0 {
result, err = modules.DBInstanceNetworks.ListDescendent2(s, opts.Network, params)
} else {
result, err = modules.DBInstanceNetworks.List(s, params)
}
if err != nil {
return err
}
printList(result, modules.DBInstanceNetworks.GetColumns(s))
return nil
})
type DBInstanceParameterListOptions struct {
options.BaseListOptions
DBInstance string `help:"ID or Name of DBInstance" json:"dbinstance"`
}
R(&DBInstanceParameterListOptions{}, "dbinstance-parameter-list", "List DB instance parameters", func(s *mcclient.ClientSession, opts *DBInstanceParameterListOptions) error {
params, err := options.ListStructToParams(opts)
if err != nil {
return err
}
result, err := modules.DBInstanceParameters.List(s, params)
if err != nil {
return err
}
printList(result, modules.DBInstanceParameters.GetColumns(s))
return nil
})
type DBInstanceDatabaseListOptions struct {
options.BaseListOptions
DBInstance string `help:"ID or Name of DBInstance" json:"dbinstance"`
}
R(&DBInstanceDatabaseListOptions{}, "dbinstance-database-list", "List DB instance databases", func(s *mcclient.ClientSession, opts *DBInstanceDatabaseListOptions) error {
params, err := options.ListStructToParams(opts)
if err != nil {
return err
}
result, err := modules.DBInstanceDatabases.List(s, params)
if err != nil {
return err
}
printList(result, modules.DBInstanceDatabases.GetColumns(s))
return nil
})
type DBInstanceBackupListOptions struct {
options.BaseListOptions
DBInstance string `help:"ID or Name of DBInstance" json:"dbinstance"`
}
R(&DBInstanceBackupListOptions{}, "dbinstance-backup-list", "List DB instance backups", func(s *mcclient.ClientSession, opts *DBInstanceBackupListOptions) error {
params, err := options.ListStructToParams(opts)
if err != nil {
return err
}
result, err := modules.DBInstanceBackups.List(s, params)
if err != nil {
return err
}
printList(result, modules.DBInstanceBackups.GetColumns(s))
return nil
})
type DBInstanceAccountListOptions struct {
options.BaseListOptions
DBInstance string `help:"ID or Name of DBInstance" json:"dbinstance"`
}
R(&DBInstanceAccountListOptions{}, "dbinstance-account-list", "List DB instance accounts", func(s *mcclient.ClientSession, opts *DBInstanceAccountListOptions) error {
params, err := options.ListStructToParams(opts)
if err != nil {
return err
}
result, err := modules.DBInstanceAccounts.List(s, params)
if err != nil {
return err
}
printList(result, modules.DBInstanceAccounts.GetColumns(s))
return nil
})
}
+42
View File
@@ -0,0 +1,42 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 shell
import (
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/onecloud/pkg/mcclient/modules"
"yunion.io/x/onecloud/pkg/mcclient/options"
)
func init() {
type ServiceIpListOptions struct {
Limit int64 `help:"Limit, default 0, i.e. no limit" default:"20"`
Offset int64 `help:"Offset, default 0, i.e. no offset"`
ServiceType string `help:"Filter by type"`
ServiceId string `help:"Filter by Service Id"`
}
R(&ServiceIpListOptions{}, "serviceip-list", "List serviceip", func(s *mcclient.ClientSession, args *ServiceIpListOptions) error {
params, err := options.ListStructToParams(args)
if err != nil {
return err
}
serviceips, err := modules.ServiceIp.List(s, params)
if err != nil {
return err
}
printList(serviceips, modules.ServiceIp.GetColumns(s))
return nil
})
}
+23
View File
@@ -0,0 +1,23 @@
get:
summary: 获取指定RDS实例详情信息
parameters:
- $ref: '../parameters/dbinstance.yaml#/dbinstanceId'
responses:
200:
description: RDS实例信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceResponse'
tags:
- dbinstance
delete:
summary: 删除指定RDS实例
parameters:
- $ref: '../parameters/dbinstance.yaml#/dbinstanceId'
responses:
200:
description: 被删除RDS实例的信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceResponse'
tags:
- dbinstance
+23
View File
@@ -0,0 +1,23 @@
get:
summary: 获取指定RDS实例用户详情信息
parameters:
- $ref: '../parameters/dbinstance.yaml#/accountId'
responses:
200:
description: RDS实例用户信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceAccountResponse'
tags:
- dbinstanceaccount
delete:
summary: 删除指定RDS实例用户
parameters:
- $ref: '../parameters/dbinstance.yaml#/accountId'
responses:
200:
description: 被删除RDS实例的用户信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceAccountResponse'
tags:
- dbinstanceaccount
+14
View File
@@ -0,0 +1,14 @@
get:
summary: 按指定条件列出RDS实例用户列表
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
- $ref: '../parameters/dbinstance.yaml#/dbinstance'
responses:
200:
description: RDS实例用户列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceAccountListResponse'
tags:
- dbinstanceaccount
+23
View File
@@ -0,0 +1,23 @@
get:
summary: 获取指定RDS实例备份详情信息
parameters:
- $ref: '../parameters/dbinstance.yaml#/backupId'
responses:
200:
description: RDS实例备份信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceBackupResponse'
tags:
- dbinstancebackup
delete:
summary: 删除指定RDS实例备份
parameters:
- $ref: '../parameters/dbinstance.yaml#/backupId'
responses:
200:
description: 被删除RDS实例的备份信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceBackupResponse'
tags:
- dbinstancebackup
+14
View File
@@ -0,0 +1,14 @@
get:
summary: 按指定条件列出RDS实例备份列表
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
- $ref: '../parameters/dbinstance.yaml#/dbinstance'
responses:
200:
description: RDS实例备份列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceBackupListResponse'
tags:
- dbinstancebackup
+23
View File
@@ -0,0 +1,23 @@
get:
summary: 获取指定RDS实例数据库详情信息
parameters:
- $ref: '../parameters/dbinstance.yaml#/databaseId'
responses:
200:
description: RDS实例数据库信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceDatabaseResponse'
tags:
- dbinstancedatabase
delete:
summary: 删除指定RDS实例数据库
parameters:
- $ref: '../parameters/dbinstance.yaml#/databaseId'
responses:
200:
description: 被删除RDS实例的数据库信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceDatabaseResponse'
tags:
- dbinstancedatabase
+14
View File
@@ -0,0 +1,14 @@
get:
summary: 按指定条件列出RDS实例数据库列表
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
- $ref: '../parameters/dbinstance.yaml#/dbinstance'
responses:
200:
description: RDS实例数据库列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceDatabaseListResponse'
tags:
- dbinstancedatabase
+12
View File
@@ -0,0 +1,12 @@
get:
summary: 列出指定RDS实例网络信息
parameters:
- $ref: "../parameters/dbinstance.yaml#/dbinstanceId"
responses:
200:
description: RDS实例网络列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceNetworkListResponse'
tags:
- dbinstance
+13
View File
@@ -0,0 +1,13 @@
get:
summary: 按指定条件列出RDS实例网络信息
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
responses:
200:
description: RDS实例网络列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceNetworkListResponse'
tags:
- dbinstancenetwork
+23
View File
@@ -0,0 +1,23 @@
get:
summary: 获取指定RDS实例参数详情信息
parameters:
- $ref: '../parameters/dbinstance.yaml#/parameterId'
responses:
200:
description: RDS实例信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceParameterResponse'
tags:
- dbinstanceparameter
delete:
summary: 删除指定RDS实例参数
parameters:
- $ref: '../parameters/dbinstance.yaml#/parameterId'
responses:
200:
description: 被删除RDS实例的参数信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceParameterResponse'
tags:
- dbinstanceparameter
+14
View File
@@ -0,0 +1,14 @@
get:
summary: 按指定条件列出RDS实例参数列表
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
- $ref: '../parameters/dbinstance.yaml#/dbinstance'
responses:
200:
description: RDS实例参数列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceParameterListResponse'
tags:
- dbinstanceparameter
+20
View File
@@ -0,0 +1,20 @@
get:
summary: 按指定条件列出RDS实例
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
- $ref: '../parameters/common.yaml#/provider'
- $ref: '../parameters/common.yaml#/account'
- $ref: '../parameters/common.yaml#/cloudprovider'
- $ref: '../parameters/common.yaml#/billing_type'
- $ref: '../parameters/common.yaml#/cloudregion'
- $ref: '../parameters/common.yaml#/zone'
- $ref: '../parameters/common.yaml#/vpc'
responses:
200:
description: RDS实例列表信息
schema:
$ref: '../schemas/dbinstance.yaml#/DBInstanceListResponse'
tags:
- dbinstance
+34
View File
@@ -377,3 +377,37 @@ paths:
$ref: "./ansibleplaybook/ansibleplaybook-run.yaml"
/ansibleplaybooks/{ansibleplaybookId}/stop:
$ref: "./ansibleplaybook/ansibleplaybook-stop.yaml"
/dbinstances:
$ref: "./dbinstance/dbinstances.yaml"
/dbinstances/{dbinstanceId}:
$ref: "./dbinstance/dbinstance.yaml"
/dbinstances/{dbinstanceId}/networks:
$ref: "./dbinstance/dbinstancenetwork.yaml"
/dbinstancenetworks:
$ref: "./dbinstance/dbinstancenetworks.yaml"
/dbinstanceparameters:
$ref: "./dbinstance/dbinstanceparameters.yaml"
/dbinstanceparameters/{parameterId}:
$ref: "./dbinstance/dbinstanceparameter.yaml"
/dbinstancedatabases:
$ref: "./dbinstance/dbinstancedatabases.yaml"
/dbinstancedatabases/{databaseId}:
$ref: "./dbinstance/dbinstancedatabase.yaml"
/dbinstancebackups:
$ref: "./dbinstance/dbinstancebackups.yaml"
/dbinstancebackups/{backupId}:
$ref: "./dbinstance/dbinstancebackup.yaml"
/dbinstanceaccounts:
$ref: "./dbinstance/dbinstanceaccounts.yaml"
/dbinstanceaccounts/{accountId}:
$ref: "./dbinstance/dbinstanceaccount.yaml"
/serviceips:
$ref: "./serviceip/serviceips.yaml"
/serviceips/{serviceipId}:
$ref: "./serviceip/serviceip.yaml"
+42
View File
@@ -0,0 +1,42 @@
dbinstanceId:
name: dbinstanceId
required: true
in: path
type: string
description: RDS实例名称或ID,建议使用ID
parameterId:
name: parameterId
required: true
in: path
type: string
description: RDS实例参数名称或ID,建议使用ID
databaseId:
name: databaseId
required: true
in: path
type: string
description: RDS实例数据库名称或ID,建议使用ID
backupId:
name: backupId
required: true
in: path
type: string
description: RDS实例备份名称或ID,建议使用ID
accountId:
name: accountId
required: true
in: path
type: string
description: RDS实例用户名称或ID,建议使用ID
dbinstance:
name: dbinstance
in: query
type: string
description: 根据RDS实例名称或ID过滤资源
+19
View File
@@ -0,0 +1,19 @@
serviceipId:
name: serviceipId
required: true
in: path
type: string
description: 服务IP名称或ID,建议使用ID
service_type:
name: service_type
in: query
type: string
enum: [dbinstance]
description: 根据服务类型过滤资源
service_id:
name: service_id
in: query
type: string
description: 根据服务ID过滤资源
+49
View File
@@ -22,6 +22,55 @@ ResourceBaseResponse:
description: 已删除
readOnly: true
ManagedResourceBaseResponse:
type: object
properties:
managed_id:
type: string
example: 3209e9b5-c32a-4e4d-84e5-650d7ecb9d8e
description: 子订阅ID
readOnly: true
CloudregionResourceBaseResponse:
type: object
properties:
cloudregion_id:
type: string
example: 5fbbdfaa-46ba-433a-81be-b3581ac55bfa
description: 区域ID
cloudregion:
type: string
example: 阿里云 马来西亚(吉隆坡)
description: 区域名称
ZoneResourceBaseResponse:
type: object
properties:
zone_id:
type: string
example: d0e8d9c2-a21d-447e-8984-50838f4cd3fa
description: 可用区区域ID
zone:
type: string
example: 阿里云 中东东部1 可用区A
description: 可用区域名称
BillingResourceBaseResponse:
type: object
properties:
billing_type:
type: string
example: prepaid
default: postpaid
description: 计费类型, 预付费、后付费
expired_at:
type: string
example: "2019-12-17T16:00:00.000000Z"
description: 到期时间
readOnly: true
ProjectizedResourceBaseResponse:
type: object
properties:
+280
View File
@@ -0,0 +1,280 @@
DBInstance:
allOf:
- $ref: "./common.yaml#/VirtualResourceBaseResponse"
- $ref: "./common.yaml#/BillingResourceBaseResponse"
- $ref: "./common.yaml#/ManagedResourceBaseResponse"
- $ref: "./common.yaml#/CloudregionResourceBaseResponse"
- $ref: "./common.yaml#/ZoneResourceBaseResponse"
- $ref: "./common.yaml#/ExternalizedResourceBaseResponse"
- type: object
description: RDS实例
properties:
disk_size_gb:
type: integer
example: 20
description: RDS实例存储大小
engine:
type: string
example: MySQL
description: RDS实例引擎
readOnly: true
engine_version:
type: string
example: "5.7"
description: RDS实例引擎版本
instance_type:
type: string
example: mysql.n1.micro.1
description: RDS实例规格
port:
type: integer
example: 3306
description: RDS实例连接端口
vcpu_count:
type: integer
example: 1
description: RDS实例CPU核数
vmem_size_mb:
type: integer
example: 1024
description: RDS实例内存大小
vpc_id:
type: string
example: 5d0a3589-4ec5-4509-8e53-6505457577b0
description: RDS实例VPC ID
vpc:
type: string
example: vpc-2zecuo9v4idebme295ofy
description: RDS实例VPC ID
DBInstanceListResponse:
type: object
properties:
limit:
type: integer
example: 20
dbinstances:
type: array
items:
$ref: '#/DBInstance'
total:
type: integer
example: 124
DBInstanceResponse:
type: object
properties:
dbinstance:
type: object
$ref: '#/DBInstance'
DBInstanceNetwork:
allOf:
- $ref: "./common.yaml#/ResourceBaseResponse"
- type: object
description: RDS实例网络
properties:
dbinstance_id:
type: string
example: "20f8b552-1b86-4595-89e3-49d123b25215"
description: RDS实例ID
ip_addr:
type: string
example: 10.10.140.141
description: 实例内网IP地址
network_id:
type: string
example: "38897a74-17b4-4c21-86b3-4f8528ced003"
description: 实例子网ID
DBInstanceNetworkListResponse:
type: object
properties:
limit:
type: integer
example: 20
dbinstancenetworks:
type: array
items:
$ref: '#/DBInstanceNetwork'
total:
type: integer
example: 124
DBInstanceNetworkResponse:
type: object
properties:
dbinstancenetwork:
type: object
$ref: '#/DBInstanceNetwork'
DBInstanceParameter:
allOf:
- $ref: "./common.yaml#/StandaloneResponse"
- $ref: "./common.yaml#/ExternalizedResourceBaseResponse"
- type: object
description: RDS实例参数
properties:
key:
type: string
example: read_buffer_size
description: RDS实例参数
value:
type: string
example: "131072"
description: RDS实例参数值
readOnly: true
dbinstance_id:
type: string
example: d0fe1519-8de5-4e13-844a-7367f4210f83
description: RDS实例ID
readOnly: true
DBInstanceParameterListResponse:
type: object
properties:
limit:
type: integer
example: 20
dbinstanceparameters:
type: array
items:
$ref: '#/DBInstanceParameter'
total:
type: integer
example: 124
DBInstanceParameterResponse:
type: object
properties:
dbinstanceparameter:
type: object
$ref: '#/DBInstanceParameter'
DBInstanceDatabase:
allOf:
- $ref: "./common.yaml#/StatusStandaloneResponse"
- $ref: "./common.yaml#/ExternalizedResourceBaseResponse"
- type: object
description: RDS实例参数
properties:
character_set:
type: string
example: utf8
description: RDS实例参数
dbinstance_id:
type: string
example: d0fe1519-8de5-4e13-844a-7367f4210f83
description: RDS实例ID
readOnly: true
DBInstanceDatabaseListResponse:
type: object
properties:
limit:
type: integer
example: 20
dbinstancedatabases:
type: array
items:
$ref: '#/DBInstanceDatabase'
total:
type: integer
example: 124
DBInstanceDatabaseResponse:
type: object
properties:
dbinstancedatabase:
type: object
$ref: '#/DBInstanceDatabase'
DBInstanceBackup:
allOf:
- $ref: "./common.yaml#/StatusStandaloneResponse"
- $ref: "./common.yaml#/ExternalizedResourceBaseResponse"
- type: object
description: RDS实例参数
properties:
start_time:
type: string
example: "2019-06-22T02:31:08.000000Z"
description: RDS实例备份开始时间
end_time:
type: string
example: "2019-06-22T02:33:24.000000Z"
description: RDS实例备份结束时间
backup_type:
type: string
example: full_backup
description: RDS实例备份类型,增量 or 全量
intranet_download_url:
type: string
example: http://rdsbak-bj-v3.oss-cn-beijing-internal.aliyuncs.com/custins1131839/hins6172779_data_20190622103022.tar.gz?OSSAccessKeyId=Kid&Expires=1561814291&Signature=4YxhdryPvGHbPzZkt3TW6Z4kfa4%3D
desritpion: 内网下载URL
download_url:
type: string
example: https://rdsbak-bj-v3.oss-cn-beijing.aliyuncs.com/custins1131839/hins6172779_data_20190622103022.tar.gz?OSSAccessKeyId=Kid&Expires=1561814291&Signature=4YxhdryPvGHbPzZjt3TW6Z4kfa4%3D
description: 外网下载URL
backup_size_mb:
type: integer
example: 21
description: 备份大小
dbinstance_id:
type: string
example: d0fe1519-8de5-4e13-844a-7367f4210f83
description: RDS实例ID
readOnly: true
DBInstanceBackupListResponse:
type: object
properties:
limit:
type: integer
example: 20
dbinstancebackups:
type: array
items:
$ref: '#/DBInstanceBackup'
total:
type: integer
example: 124
DBInstanceBackupResponse:
type: object
properties:
dbinstancebackup:
type: object
$ref: '#/DBInstanceBackup'
DBInstanceAccount:
allOf:
- $ref: "./common.yaml#/StandaloneResponse"
- $ref: "./common.yaml#/ExternalizedResourceBaseResponse"
DBInstanceAccountListResponse:
type: object
properties:
limit:
type: integer
example: 20
dbinstanceaccounts:
type: array
items:
$ref: '#/DBInstanceAccount'
total:
type: integer
example: 124
DBInstanceAccountResponse:
type: object
properties:
dbinstanceaccount:
type: object
$ref: '#/DBInstanceAccount'
+48
View File
@@ -0,0 +1,48 @@
ServiceIp:
allOf:
- $ref: "./common.yaml#/ResourceBaseResponse"
- type: object
description: 服务IP信息
properties:
id:
type: string
example: 80d8e168-fc51-45f8-8d8d-f072ed27b390
description: 资源UUID
service_id:
type: string
example: 53c2dc1e-d799-40fc-8c16-d49ded656930
description: 服务ID
service_type:
type: string
example: dbinstance
description: 服务类型
ip_addr:
type: string
example: "100.118.3.23"
description: 服务IP地址
url:
type: string
example: rr-2zej70lc855hk07rq.mysql.rds.aliyuncs.com
description: 服务域名地址
ServiceIpListResponse:
type: object
properties:
limit:
type: integer
example: 20
serviceips:
type: array
items:
$ref: '#/ServiceIp'
total:
type: integer
example: 124
ServiceIpResponse:
type: object
properties:
serviceip:
type: object
$ref: '#/ServiceIp'
+11
View File
@@ -0,0 +1,11 @@
get:
summary: 获取服务IP详细信息
parameters:
- $ref: '../parameters/serviceip.yaml#/serviceipId'
responses:
200:
description: 服务IP详细信息
schema:
$ref: '../schemas/serviceip.yaml#/ServiceIpResponse'
tags:
- serviceip
+15
View File
@@ -0,0 +1,15 @@
get:
summary: 按指定条件列出服务的IP信息列表
parameters:
- $ref: '../parameters/common.yaml#/limit'
- $ref: '../parameters/common.yaml#/offset'
- $ref: '../parameters/serviceip.yaml#/service_type'
- $ref: '../parameters/serviceip.yaml#/service_id'
responses:
200:
description: 服务IP信息列表
schema:
$ref: '../schemas/serviceip.yaml#/ServiceIpListResponse'
tags:
- serviceip
+44
View File
@@ -0,0 +1,44 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 compute
const (
DBINSTANCE_DEPLOYING = "deploying" //部署中
DBINSTANCE_RUNNING = "running" //使用中
DBINSTANCE_REBOOTING = "rebooting" //重启中
DBINSTANCE_MIGRATING = "migrating" //迁移中
DBINSTANCE_RESTORING = "restoring" //备份恢复中
DBINSTANCE_IMPORTING = "importing" //数据导入中
DBINSTANCE_CLONING = "cloning" //克隆中
DBINSTANCE_DELETING = "deleting" //删除中
DBINSTANCE_UNKNOWN = "unknown"
DBINSTANCE_BACKUP_READY = "ready"
DBINSTANCE_BACKUP_CREATING = "creating"
DBINSTANCE_BACKUP_DELETING = "deleting"
DBINSTANCE_BACKUP_FAILED = "failed"
DBINSTANCE_BACKUP_UNKNOWN = "unknown"
BACKUP_TYPE_FULL_BACKUP = "full_backup"
BACKUP_TYPE_INCREMENTALBACKUP = "incremental_backup"
BACKUP_TYPE_UNKNOWN = "unknown"
DBINSTANCE_DATABASE_CREATING = "creating"
DBINSTANCE_DATABASE_RUNNING = "running"
DBINSTANCE_DATABASE_DELETING = "deleting"
DBINSTANCE_USER_UNAVAILABLE = "unavailable"
DBINSTANCE_USER_AVAILABLE = "available"
)
+11
View File
@@ -0,0 +1,11 @@
package cloudprovider
type SDBInstanceNetwork struct {
IP string
NetworkId string
}
type SExtraIp struct {
IP string
URL string
}
+3 -2
View File
@@ -20,6 +20,7 @@ import (
"time"
"strings"
"yunion.io/x/pkg/errors"
)
@@ -47,8 +48,8 @@ type SListObjectResult struct {
type ICloudBucket interface {
IVirtualResource
GetGlobalId() string
GetName() string
//GetGlobalId() string
//GetName() string
GetAcl() string
GetLocation() string
GetIRegion() ICloudRegion
+62 -14
View File
@@ -41,6 +41,8 @@ type ICloudResource interface {
}
type IVirtualResource interface {
ICloudResource
GetProjectId() string
}
@@ -116,6 +118,8 @@ type ICloudRegion interface {
IBucketExist(name string) (bool, error)
GetIBucketById(name string) (ICloudBucket, error)
GetIDBInstances() ([]ICloudDBInstance, error)
GetProvider() string
}
@@ -222,7 +226,6 @@ type ICloudHost interface {
}
type ICloudVM interface {
ICloudResource
IBillingResource
IVirtualResource
@@ -291,7 +294,6 @@ type ICloudNic interface {
}
type ICloudEIP interface {
ICloudResource
IBillingResource
IVirtualResource
@@ -315,7 +317,7 @@ type ICloudEIP interface {
type ICloudSecurityGroup interface {
ICloudResource
IVirtualResource
//IVirtualResource
GetDescription() string
GetRules() ([]secrules.SecurityRule, error)
@@ -340,7 +342,6 @@ type ICloudRoute interface {
}
type ICloudDisk interface {
ICloudResource
IBillingResource
IVirtualResource
@@ -377,7 +378,6 @@ type ICloudDisk interface {
}
type ICloudSnapshot interface {
ICloudResource
IVirtualResource
GetSize() int32
@@ -387,7 +387,6 @@ type ICloudSnapshot interface {
}
type ICloudSnapshotPolicy interface {
ICloudResource
IVirtualResource
GetRetentionDays() int
@@ -425,7 +424,6 @@ type ICloudWire interface {
}
type ICloudNetwork interface {
ICloudResource
IVirtualResource
GetIWire() ICloudWire
@@ -455,7 +453,6 @@ type ICloudHostNetInterface interface {
}
type ICloudLoadbalancer interface {
ICloudResource
IVirtualResource
GetAddress() string
@@ -486,7 +483,6 @@ type ICloudLoadbalancer interface {
}
type ICloudLoadbalancerListener interface {
ICloudResource
IVirtualResource
GetListenerType() string
@@ -538,7 +534,6 @@ type ICloudLoadbalancerListener interface {
}
type ICloudLoadbalancerListenerRule interface {
ICloudResource
IVirtualResource
GetDomain() string
@@ -549,7 +544,6 @@ type ICloudLoadbalancerListenerRule interface {
}
type ICloudLoadbalancerBackendGroup interface {
ICloudResource
IVirtualResource
IsDefault() bool
@@ -564,7 +558,6 @@ type ICloudLoadbalancerBackendGroup interface {
}
type ICloudLoadbalancerBackend interface {
ICloudResource
IVirtualResource
GetWeight() int
@@ -576,7 +569,6 @@ type ICloudLoadbalancerBackend interface {
}
type ICloudLoadbalancerCertificate interface {
ICloudResource
IVirtualResource
Sync(name, privateKey, publickKey string) error
@@ -589,7 +581,6 @@ type ICloudLoadbalancerCertificate interface {
}
type ICloudLoadbalancerAcl interface {
ICloudResource
IVirtualResource
GetAclEntries() []SLoadbalancerAccessControlListEntry
@@ -700,3 +691,60 @@ type ICloudInterfaceAddress interface {
GetIP() string
IsPrimary() bool
}
type ICloudDBInstance interface {
IVirtualResource
IBillingResource
GetPort() int
GetEngine() string
GetEngineVersion() string
//实例规格
GetInstanceType() string
GetVcpuCount() int
GetVmemSizeMB() int //MB
GetDiskSizeGB() int
GetMaintainTime() string
GetIZoneId() string
GetIVpcId() string
GetDBNetwork() (*SDBInstanceNetwork, error)
GetExtraIps() ([]SExtraIp, error)
GetIDBInstanceParameters() ([]ICloudDBInstanceParameter, error)
GetIDBInstanceBackups() ([]ICloudDBInstanceBackup, error)
GetIDBInstanceDatabases() ([]ICloudDBInstanceDatabase, error)
GetIDBInstanceAccounts() ([]ICloudDBInstanceAccount, error)
}
type ICloudDBInstanceParameter interface {
GetGlobalId() string
GetKey() string
GetValue() string
GetDescription() string
}
type ICloudDBInstanceBackup interface {
ICloudResource
GetStartTime() time.Time
GetEndTime() time.Time
GetBackupSizeMb() int
GetDBNames() string
GetDownloadURL() string
GetIntranetDownloadURL() string
GetBackupType() string
}
type ICloudDBInstanceDatabase interface {
ICloudResource
GetCharacterSet() string
}
type ICloudDBInstanceAccount interface {
ICloudResource
}
+1
View File
@@ -1097,6 +1097,7 @@ func (self *SCloudprovider) RealDelete(ctx context.Context, userCred mcclient.To
LoadbalancerAclManager,
LoadbalancerCertificateManager,
NatGatewayManager,
DBInstanceManager,
VpcManager,
ElasticipManager,
NetworkInterfaceManager,
+142
View File
@@ -867,6 +867,146 @@ func syncLoadbalancerBackends(ctx context.Context, userCred mcclient.TokenCreden
}
}
func syncRegionDBInstances(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, provider *SCloudprovider, localRegion *SCloudregion, remoteRegion cloudprovider.ICloudRegion, syncRange *SSyncRange) {
instances, err := remoteRegion.GetIDBInstances()
if err != nil {
msg := fmt.Sprintf("GetIDBInstances for region %s failed %s", remoteRegion.GetName(), err)
log.Errorf(msg)
return
}
localInstances, remoteInstances, result := DBInstanceManager.SyncDBInstances(ctx, userCred, provider.GetOwnerId(), provider, localRegion, instances)
syncResults.Add(DBInstanceManager, result)
msg := result.Result()
log.Infof("SyncDBInstances for region %s result: %s", localRegion.Name, msg)
if result.IsError() {
return
}
db.OpsLog.LogEvent(provider, db.ACT_SYNC_HOST_COMPLETE, msg, userCred)
for i := 0; i < len(localInstances); i++ {
func() {
lockman.LockObject(ctx, &localInstances[i])
defer lockman.ReleaseObject(ctx, &localInstances[i])
syncDBInstanceNetwork(ctx, userCred, syncResults, &localInstances[i], remoteInstances[i])
syncDBInstanceExtraIps(ctx, userCred, syncResults, &localInstances[i], remoteInstances[i])
syncDBInstanceParameters(ctx, userCred, syncResults, &localInstances[i], remoteInstances[i])
syncDBInstanceBackups(ctx, userCred, syncResults, &localInstances[i], remoteInstances[i])
syncDBInstanceDatabases(ctx, userCred, syncResults, &localInstances[i], remoteInstances[i])
syncDBInstanceAccounts(ctx, userCred, syncResults, &localInstances[i], remoteInstances[i])
}()
}
}
func syncDBInstanceNetwork(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, localInstance *SDBInstance, remoteInstance cloudprovider.ICloudDBInstance) {
network, err := remoteInstance.GetDBNetwork()
if err != nil {
msg := fmt.Sprintf("GetDBNetwork for dbinstance %s failed %s", remoteInstance.GetName(), err)
log.Errorf(msg)
return
}
result := DBInstanceNetworkManager.SyncDBInstanceNetwork(ctx, userCred, localInstance, network)
syncResults.Add(DBInstanceNetworkManager, result)
msg := result.Result()
log.Infof("SyncDBInstanceNetwork for dbinstance %s result: %s", localInstance.Name, msg)
if result.IsError() {
return
}
}
func syncDBInstanceExtraIps(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, localInstance *SDBInstance, remoteInstance cloudprovider.ICloudDBInstance) {
ips, err := remoteInstance.GetExtraIps()
if err != nil {
msg := fmt.Sprintf("GetExtraIps for dbinstance %s failed %s", remoteInstance.GetName(), err)
log.Errorf(msg)
return
}
result := ServiceIpManager.SyncExtraIps(ctx, userCred, localInstance, ips)
syncResults.Add(ServiceIpManager, result)
msg := result.Result()
log.Infof("SyncExtraIps for dbinstance %s result: %s", localInstance.Name, msg)
if result.IsError() {
return
}
}
func syncDBInstanceParameters(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, localInstance *SDBInstance, remoteInstance cloudprovider.ICloudDBInstance) {
parameters, err := remoteInstance.GetIDBInstanceParameters()
if err != nil {
msg := fmt.Sprintf("GetIDBInstanceParameters for dbinstance %s failed %s", remoteInstance.GetName(), err)
log.Errorf(msg)
return
}
result := DBInstanceParameterManager.SyncDBInstanceParameters(ctx, userCred, localInstance, parameters)
syncResults.Add(DBInstanceParameterManager, result)
msg := result.Result()
log.Infof("SyncDBInstanceParameters for dbinstance %s result: %s", localInstance.Name, msg)
if result.IsError() {
return
}
}
func syncDBInstanceBackups(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, localInstance *SDBInstance, remoteInstance cloudprovider.ICloudDBInstance) {
backups, err := remoteInstance.GetIDBInstanceBackups()
if err != nil {
msg := fmt.Sprintf("GetIDBInstanceBackups for dbinstance %s failed %s", remoteInstance.GetName(), err)
log.Errorf(msg)
return
}
result := DBInstanceBackupManager.SyncDBInstanceBackups(ctx, userCred, localInstance, backups)
syncResults.Add(DBInstanceBackupManager, result)
msg := result.Result()
log.Infof("SyncDBInstanceBackups for dbinstance %s result: %s", localInstance.Name, msg)
if result.IsError() {
return
}
}
func syncDBInstanceDatabases(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, localInstance *SDBInstance, remoteInstance cloudprovider.ICloudDBInstance) {
databases, err := remoteInstance.GetIDBInstanceDatabases()
if err != nil {
msg := fmt.Sprintf("GetIDBInstanceDatabases for dbinstance %s failed %s", remoteInstance.GetName(), err)
log.Errorf(msg)
return
}
result := DBInstanceDatabaseManager.SyncDBInstanceDatabases(ctx, userCred, localInstance, databases)
syncResults.Add(DBInstanceDatabaseManager, result)
msg := result.Result()
log.Infof("SyncDBInstanceDatabases for dbinstance %s result: %s", localInstance.Name, msg)
if result.IsError() {
return
}
}
func syncDBInstanceAccounts(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, localInstance *SDBInstance, remoteInstance cloudprovider.ICloudDBInstance) {
accounts, err := remoteInstance.GetIDBInstanceAccounts()
if err != nil {
msg := fmt.Sprintf("GetIDBInstanceAccounts for dbinstance %s failed %s", remoteInstance.GetName(), err)
log.Errorf(msg)
return
}
result := DBInstanceAccountManager.SyncDBInstanceAccounts(ctx, userCred, localInstance, accounts)
syncResults.Add(DBInstanceDatabaseManager, result)
msg := result.Result()
log.Infof("SyncDBInstanceAccounts for dbinstance %s result: %s", localInstance.Name, msg)
if result.IsError() {
return
}
}
func syncRegionSnapshots(ctx context.Context, userCred mcclient.TokenCredential, syncResults SSyncResultSet, provider *SCloudprovider, localRegion *SCloudregion, remoteRegion cloudprovider.ICloudRegion, syncRange *SSyncRange) {
snapshots, err := remoteRegion.GetISnapshots()
if err != nil {
@@ -1017,6 +1157,8 @@ func syncPublicCloudProviderInfo(
syncRegionNetworkInterfaces(ctx, userCred, syncResults, provider, localRegion, remoteRegion, syncRange)
syncRegionDBInstances(ctx, userCred, syncResults, provider, localRegion, remoteRegion, syncRange)
log.Debugf("storageCachePairs count %d", len(storageCachePairs))
for i := range storageCachePairs {
// always sync private cloud cached images
+190
View File
@@ -0,0 +1,190 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/cloudcommon/validators"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/sqlchemy"
)
type SDBInstanceAccountManager struct {
db.SStatusStandaloneResourceBaseManager
}
var DBInstanceAccountManager *SDBInstanceAccountManager
func init() {
DBInstanceAccountManager = &SDBInstanceAccountManager{
SStatusStandaloneResourceBaseManager: db.NewStatusStandaloneResourceBaseManager(
SDBInstanceAccount{},
"dbinstanceaccounts_tbl",
"dbinstanceaccount",
"dbinstanceaccounts",
),
}
DBInstanceAccountManager.SetVirtualObject(DBInstanceAccountManager)
}
type SDBInstanceAccount struct {
db.SStatusStandaloneResourceBase
db.SExternalizedResourceBase
DBInstanceId string `width:"36" charset:"ascii" name:"dbinstance_id" nullable:"false" list:"user" create:"required" index:"true"`
}
func (manager *SDBInstanceAccountManager) GetContextManagers() [][]db.IModelManager {
return [][]db.IModelManager{
{DBInstanceManager},
}
}
func (self *SDBInstanceAccountManager) AllowListItems(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowList(userCred, self)
}
func (self *SDBInstanceAccountManager) AllowCreateItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowCreate(userCred, self)
}
func (self *SDBInstanceAccount) AllowGetDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowGet(userCred, self)
}
func (self *SDBInstanceAccount) AllowUpdateItem(ctx context.Context, userCred mcclient.TokenCredential) bool {
return db.IsAdminAllowUpdate(userCred, self)
}
func (self *SDBInstanceAccount) AllowDeleteItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowDelete(userCred, self)
}
func (manager *SDBInstanceAccountManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
q, err := manager.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
if err != nil {
return nil, err
}
data := query.(*jsonutils.JSONDict)
return validators.ApplyModelFilters(q, data, []*validators.ModelFilterOptions{
{Key: "dbinstance", ModelKeyword: "dbinstance", OwnerId: userCred},
})
}
func (manager *SDBInstanceAccountManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
return nil, httperrors.NewNotImplementedError("Not Implemented")
}
func (manager *SDBInstanceAccountManager) getDBInstanceAccountsByInstance(instance *SDBInstance) ([]SDBInstanceAccount, error) {
accounts := []SDBInstanceAccount{}
q := manager.Query().Equals("dbinstance_id", instance.Id)
err := db.FetchModelObjects(manager, q, &accounts)
if err != nil {
return nil, errors.Wrap(err, "getDBInstanceAccountsByInstance.FetchModelObjects")
}
return accounts, nil
}
func (manager *SDBInstanceAccountManager) SyncDBInstanceAccounts(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, cloudAccounts []cloudprovider.ICloudDBInstanceAccount) compare.SyncResult {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
result := compare.SyncResult{}
dbAccounts, err := manager.getDBInstanceAccountsByInstance(instance)
if err != nil {
result.Error(err)
return result
}
removed := make([]SDBInstanceAccount, 0)
commondb := make([]SDBInstanceAccount, 0)
commonext := make([]cloudprovider.ICloudDBInstanceAccount, 0)
added := make([]cloudprovider.ICloudDBInstanceAccount, 0)
if err := compare.CompareSets(dbAccounts, cloudAccounts, &removed, &commondb, &commonext, &added); err != nil {
result.Error(err)
return result
}
for i := 0; i < len(removed); i++ {
err := removed[i].Delete(ctx, userCred)
if err != nil {
result.DeleteError(err)
} else {
result.Delete()
}
}
for i := 0; i < len(commondb); i++ {
err := commondb[i].SyncWithCloudDBInstanceAccount(ctx, userCred, commonext[i])
if err != nil {
result.UpdateError(err)
} else {
result.Update()
}
}
for i := 0; i < len(added); i++ {
err = manager.newFromCloudDBInstanceAccount(ctx, userCred, instance, added[i])
if err != nil {
result.AddError(err)
} else {
result.Add()
}
}
return result
}
func (self *SDBInstanceAccount) SyncWithCloudDBInstanceAccount(ctx context.Context, userCred mcclient.TokenCredential, extAccount cloudprovider.ICloudDBInstanceAccount) error {
_, err := db.UpdateWithLock(ctx, self, func() error {
self.Status = extAccount.GetStatus()
return nil
})
if err != nil {
return errors.Wrapf(err, "SyncWithCloudDBInstanceAccount.UpdateWithLock")
}
return nil
}
func (manager *SDBInstanceAccountManager) newFromCloudDBInstanceAccount(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, extAccount cloudprovider.ICloudDBInstanceAccount) error {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
account := SDBInstanceAccount{}
account.SetModelManager(manager, &account)
newName, err := db.GenerateName(manager, instance.GetOwnerId(), extAccount.GetName())
if err != nil {
return errors.Wrap(err, "newFromCloudDBInstanceAccount.GenerateName")
}
account.Name = newName
account.DBInstanceId = instance.Id
account.Status = extAccount.GetStatus()
account.ExternalId = extAccount.GetGlobalId()
err = manager.TableSpec().Insert(&account)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBInstanceAccount.Insert")
}
return nil
}
+212
View File
@@ -0,0 +1,212 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/cloudcommon/validators"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/sqlchemy"
)
type SDBInstanceBackupManager struct {
db.SStatusStandaloneResourceBaseManager
}
var DBInstanceBackupManager *SDBInstanceBackupManager
func init() {
DBInstanceBackupManager = &SDBInstanceBackupManager{
SStatusStandaloneResourceBaseManager: db.NewStatusStandaloneResourceBaseManager(
SDBInstanceBackup{},
"dbinstancebackups_tbl",
"dbinstancebackup",
"dbinstancebackups",
),
}
DBInstanceBackupManager.SetVirtualObject(DBInstanceBackupManager)
}
type SDBInstanceBackup struct {
db.SStatusStandaloneResourceBase
db.SExternalizedResourceBase
StartTime time.Time `list:"user"`
EndTime time.Time `list:"user"`
BackupType string `width:"32" charset:"ascii" nullable:"true" list:"user"`
IntranetDownloadURL string `width:"256" charset:"ascii" nullable:"true" list:"user"`
DownloadURL string `width:"256" charset:"ascii" nullable:"true" list:"user"`
DBNames string `width:"512" charset:"ascii" nullable:"true" list:"user"`
BackupSizeMb int `nullable:"false" list:"user"`
DBInstanceId string `width:"36" charset:"ascii" name:"dbinstance_id" nullable:"false" list:"user" create:"required" index:"true"`
}
func (manager *SDBInstanceBackupManager) GetContextManagers() [][]db.IModelManager {
return [][]db.IModelManager{
{DBInstanceManager},
}
}
func (self *SDBInstanceBackupManager) AllowListItems(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowList(userCred, self)
}
func (self *SDBInstanceBackupManager) AllowCreateItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowCreate(userCred, self)
}
func (self *SDBInstanceBackup) AllowGetDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowGet(userCred, self)
}
func (self *SDBInstanceBackup) AllowUpdateItem(ctx context.Context, userCred mcclient.TokenCredential) bool {
return db.IsAdminAllowUpdate(userCred, self)
}
func (self *SDBInstanceBackup) AllowDeleteItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowDelete(userCred, self)
}
func (manager *SDBInstanceBackupManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
q, err := manager.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
if err != nil {
return nil, err
}
data := query.(*jsonutils.JSONDict)
return validators.ApplyModelFilters(q, data, []*validators.ModelFilterOptions{
{Key: "dbinstance", ModelKeyword: "dbinstance", OwnerId: userCred},
})
}
func (manager *SDBInstanceBackupManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
return nil, httperrors.NewNotImplementedError("Not Implemented")
}
func (manager *SDBInstanceBackupManager) getDBInstanceBackupsByInstance(instance *SDBInstance) ([]SDBInstanceBackup, error) {
backups := []SDBInstanceBackup{}
q := manager.Query().Equals("dbinstance_id", instance.Id)
err := db.FetchModelObjects(manager, q, &backups)
if err != nil {
return nil, errors.Wrap(err, "getDBInstanceBackupsByInstance.FetchModelObjects")
}
return backups, nil
}
func (manager *SDBInstanceBackupManager) SyncDBInstanceBackups(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, cloudBackups []cloudprovider.ICloudDBInstanceBackup) compare.SyncResult {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
result := compare.SyncResult{}
dbBackups, err := manager.getDBInstanceBackupsByInstance(instance)
if err != nil {
result.Error(err)
return result
}
removed := make([]SDBInstanceBackup, 0)
commondb := make([]SDBInstanceBackup, 0)
commonext := make([]cloudprovider.ICloudDBInstanceBackup, 0)
added := make([]cloudprovider.ICloudDBInstanceBackup, 0)
if err := compare.CompareSets(dbBackups, cloudBackups, &removed, &commondb, &commonext, &added); err != nil {
result.Error(err)
return result
}
for i := 0; i < len(removed); i++ {
err := removed[i].Delete(ctx, userCred)
if err != nil {
result.DeleteError(err)
} else {
result.Delete()
}
}
for i := 0; i < len(commondb); i++ {
err := commondb[i].SyncWithCloudDBInstanceBackup(ctx, userCred, commonext[i])
if err != nil {
result.UpdateError(err)
} else {
result.Update()
}
}
for i := 0; i < len(added); i++ {
err = manager.newFromCloudDBInstanceBackup(ctx, userCred, instance, added[i])
if err != nil {
result.AddError(err)
} else {
result.Add()
}
}
return result
}
func (self *SDBInstanceBackup) SyncWithCloudDBInstanceBackup(ctx context.Context, userCred mcclient.TokenCredential, extBackup cloudprovider.ICloudDBInstanceBackup) error {
_, err := db.UpdateWithLock(ctx, self, func() error {
self.Status = extBackup.GetStatus()
self.StartTime = extBackup.GetStartTime()
self.EndTime = extBackup.GetEndTime()
self.IntranetDownloadURL = extBackup.GetIntranetDownloadURL()
self.DownloadURL = extBackup.GetDownloadURL()
self.BackupSizeMb = extBackup.GetBackupSizeMb()
self.DBNames = extBackup.GetDBNames()
self.BackupType = extBackup.GetBackupType()
return nil
})
if err != nil {
return errors.Wrapf(err, "SyncWithCloudDBInstancebackup.UpdateWithLock")
}
return nil
}
func (manager *SDBInstanceBackupManager) newFromCloudDBInstanceBackup(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, extBackup cloudprovider.ICloudDBInstanceBackup) error {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
backup := SDBInstanceBackup{}
backup.SetModelManager(manager, &backup)
newName, err := db.GenerateName(manager, instance.GetOwnerId(), extBackup.GetName())
if err != nil {
return errors.Wrap(err, "newFromCloudDBInstanceBackup.GenerateName")
}
backup.Name = newName
backup.DBInstanceId = instance.Id
backup.Status = extBackup.GetStatus()
backup.StartTime = extBackup.GetStartTime()
backup.EndTime = extBackup.GetEndTime()
backup.IntranetDownloadURL = extBackup.GetIntranetDownloadURL()
backup.DownloadURL = extBackup.GetDownloadURL()
backup.BackupSizeMb = extBackup.GetBackupSizeMb()
backup.DBNames = extBackup.GetDBNames()
backup.BackupType = extBackup.GetBackupType()
backup.ExternalId = extBackup.GetGlobalId()
err = manager.TableSpec().Insert(&backup)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBInstanceBackup.Insert")
}
return nil
}
+190
View File
@@ -0,0 +1,190 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/cloudcommon/validators"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/sqlchemy"
)
type SDBInstanceDatabaseManager struct {
db.SStatusStandaloneResourceBaseManager
}
var DBInstanceDatabaseManager *SDBInstanceDatabaseManager
func init() {
DBInstanceDatabaseManager = &SDBInstanceDatabaseManager{
SStatusStandaloneResourceBaseManager: db.NewStatusStandaloneResourceBaseManager(
SDBInstanceDatabase{},
"dbinstancedatabases_tbl",
"dbinstancedatabase",
"dbinstancedatabases",
),
}
DBInstanceDatabaseManager.SetVirtualObject(DBInstanceDatabaseManager)
}
type SDBInstanceDatabase struct {
db.SStatusStandaloneResourceBase
db.SExternalizedResourceBase
CharacterSet string `width:"32" charset:"ascii" nullable:"true" list:"user"`
DBInstanceId string `width:"36" charset:"ascii" name:"dbinstance_id" nullable:"false" list:"user" create:"required" index:"true"`
}
func (manager *SDBInstanceDatabaseManager) GetContextManagers() [][]db.IModelManager {
return [][]db.IModelManager{
{DBInstanceManager},
}
}
func (self *SDBInstanceDatabaseManager) AllowListItems(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowList(userCred, self)
}
func (self *SDBInstanceDatabaseManager) AllowCreateItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowCreate(userCred, self)
}
func (self *SDBInstanceDatabase) AllowGetDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowGet(userCred, self)
}
func (self *SDBInstanceDatabase) AllowUpdateItem(ctx context.Context, userCred mcclient.TokenCredential) bool {
return db.IsAdminAllowUpdate(userCred, self)
}
func (self *SDBInstanceDatabase) AllowDeleteItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowDelete(userCred, self)
}
func (manager *SDBInstanceDatabaseManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
q, err := manager.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
if err != nil {
return nil, err
}
data := query.(*jsonutils.JSONDict)
return validators.ApplyModelFilters(q, data, []*validators.ModelFilterOptions{
{Key: "dbinstance", ModelKeyword: "dbinstance", OwnerId: userCred},
})
}
func (manager *SDBInstanceDatabaseManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
return nil, httperrors.NewNotImplementedError("Not Implemented")
}
func (manager *SDBInstanceDatabaseManager) getDBInstanceDatabasesByInstance(instance *SDBInstance) ([]SDBInstanceDatabase, error) {
databases := []SDBInstanceDatabase{}
q := manager.Query().Equals("dbinstance_id", instance.Id)
err := db.FetchModelObjects(manager, q, &databases)
if err != nil {
return nil, errors.Wrap(err, "getDBInstanceDatabasesByInstance.FetchModelObjects")
}
return databases, nil
}
func (manager *SDBInstanceDatabaseManager) SyncDBInstanceDatabases(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, cloudDatabases []cloudprovider.ICloudDBInstanceDatabase) compare.SyncResult {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
result := compare.SyncResult{}
dbDatabases, err := manager.getDBInstanceDatabasesByInstance(instance)
if err != nil {
result.Error(err)
return result
}
removed := make([]SDBInstanceDatabase, 0)
commondb := make([]SDBInstanceDatabase, 0)
commonext := make([]cloudprovider.ICloudDBInstanceDatabase, 0)
added := make([]cloudprovider.ICloudDBInstanceDatabase, 0)
if err := compare.CompareSets(dbDatabases, cloudDatabases, &removed, &commondb, &commonext, &added); err != nil {
result.Error(err)
return result
}
for i := 0; i < len(removed); i++ {
err := removed[i].Delete(ctx, userCred)
if err != nil {
result.DeleteError(err)
} else {
result.Delete()
}
}
for i := 0; i < len(commondb); i++ {
err := commondb[i].SyncWithCloudDBInstanceDatabase(ctx, userCred, commonext[i])
if err != nil {
result.UpdateError(err)
} else {
result.Update()
}
}
for i := 0; i < len(added); i++ {
err = manager.newFromCloudDBInstanceDatabase(ctx, userCred, instance, added[i])
if err != nil {
result.AddError(err)
} else {
result.Add()
}
}
return result
}
func (self *SDBInstanceDatabase) SyncWithCloudDBInstanceDatabase(ctx context.Context, userCred mcclient.TokenCredential, extDatabase cloudprovider.ICloudDBInstanceDatabase) error {
_, err := db.UpdateWithLock(ctx, self, func() error {
self.Status = extDatabase.GetStatus()
self.Name = extDatabase.GetName()
self.CharacterSet = extDatabase.GetCharacterSet()
return nil
})
if err != nil {
return errors.Wrapf(err, "SyncWithCloudDBInstanceDatabase.UpdateWithLock")
}
return nil
}
func (manager *SDBInstanceDatabaseManager) newFromCloudDBInstanceDatabase(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, extDatabase cloudprovider.ICloudDBInstanceDatabase) error {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
database := SDBInstanceDatabase{}
database.SetModelManager(manager, &database)
database.Name = extDatabase.GetName()
database.DBInstanceId = instance.Id
database.Status = extDatabase.GetStatus()
database.CharacterSet = extDatabase.GetCharacterSet()
database.ExternalId = extDatabase.GetGlobalId()
err := manager.TableSpec().Insert(&database)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBInstanceDatabase.Insert")
}
return nil
}
+57
View File
@@ -0,0 +1,57 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"yunion.io/x/log"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/pkg/errors"
)
type SDBInstanceJointsManager struct {
db.SVirtualJointResourceBaseManager
}
func NewDBInstanceJointsManager(dt interface{}, tableName string, keyword string, keywordPlural string, slave db.IVirtualModelManager) SDBInstanceJointsManager {
log.Errorf("NewDBInstanceJointsManager: %v", DBInstanceManager)
return SDBInstanceJointsManager{
SVirtualJointResourceBaseManager: db.NewVirtualJointResourceBaseManager(
dt,
tableName,
keyword,
keywordPlural,
DBInstanceManager,
slave,
),
}
}
type SDBInstanceJointsBase struct {
db.SVirtualJointResourceBase
DBInstanceId string `width:"36" charset:"ascii" name:"dbinstance_id" nullable:"false" list:"user" create:"required" index:"true"`
}
func (self *SDBInstanceJointsBase) getDBInstance() (*SDBInstance, error) {
instance, err := DBInstanceManager.FetchById(self.DBInstanceId)
if err != nil {
return nil, errors.Wrapf(err, "getDBInstance.FetchById")
}
return instance.(*SDBInstance), nil
}
func (manager *SDBInstanceJointsManager) GetMasterFieldName() string {
return "dbinstance_id"
}
+164
View File
@@ -0,0 +1,164 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"database/sql"
"fmt"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/pkg/util/netutils"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/mcclient"
)
type SDBInstanceNetworkManager struct {
SDBInstanceJointsManager
}
var DBInstanceNetworkManager *SDBInstanceNetworkManager
func init() {
db.InitManager(func() {
DBInstanceNetworkManager = &SDBInstanceNetworkManager{
SDBInstanceJointsManager: NewDBInstanceJointsManager(
SDBInstanceNetwork{},
"dbinstancenetworks_tbl",
"dbinstancenetwork",
"dbinstancenetworks",
NetworkManager,
),
}
DBInstanceNetworkManager.SetVirtualObject(DBInstanceNetworkManager)
DBInstanceNetworkManager.TableSpec().AddIndex(true, "ip_addr", "dbinstance_id")
})
}
type SDBInstanceNetwork struct {
SDBInstanceJointsBase
NetworkId string `width:"36" charset:"ascii" nullable:"true" list:"user"`
IpAddr string `width:"16" charset:"ascii" nullable:"false" list:"user"`
}
func (manager *SDBInstanceNetworkManager) GetSlaveFieldName() string {
return "network_id"
}
func (joint *SDBInstanceNetwork) Master() db.IStandaloneModel {
return db.JointMaster(joint)
}
func (joint *SDBInstanceNetwork) Slave() db.IStandaloneModel {
return db.JointSlave(joint)
}
func (self *SDBInstanceNetwork) Detach(ctx context.Context, userCred mcclient.TokenCredential) error {
return db.DetachJoint(ctx, userCred, self)
}
func (self *SDBInstanceNetwork) AllowDeleteItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return false
}
func (manager *SDBInstanceNetworkManager) SyncDBInstanceNetwork(ctx context.Context, userCred mcclient.TokenCredential, dbinstance *SDBInstance, network *cloudprovider.SDBInstanceNetwork) compare.SyncResult {
result := compare.SyncResult{}
dbNetwork, err := dbinstance.GetDBNetwork()
if err != nil && err != sql.ErrNoRows {
result.Error(err)
return result
}
if dbNetwork == nil {
err = manager.newFromCloudDBNetwork(ctx, userCred, dbinstance, network)
if err != nil {
result.AddError(err)
} else {
result.Add()
}
} else {
err = dbNetwork.syncWithCloudDBNetwork(ctx, userCred, dbinstance, network)
if err != nil {
result.UpdateError(err)
} else {
result.Update()
}
}
return result
}
func (self *SDBInstanceNetwork) syncWithCloudDBNetwork(ctx context.Context, userCred mcclient.TokenCredential, dbinstance *SDBInstance, network *cloudprovider.SDBInstanceNetwork) error {
_, err := db.UpdateWithLock(ctx, self, func() error {
_localnetwork, err := db.FetchByExternalId(NetworkManager, network.NetworkId)
if err != nil {
return errors.Wrapf(err, "FetchByExternalId")
}
localnetwork := _localnetwork.(*SNetwork)
self.NetworkId = localnetwork.Id
ipAdd, err := netutils.NewIPV4Addr(network.IP)
if err != nil {
return errors.Wrapf(err, "NewIPV4Addr")
}
if !localnetwork.IsAddressInRange(ipAdd) {
return fmt.Errorf("IP %s not in network %s(%s) address range", network.IP, localnetwork.Name, localnetwork.Id)
}
self.IpAddr = network.IP
return nil
})
if err != nil {
return errors.Wrapf(err, "syncWithCloudDBNetwork.UpdateWithLock")
}
return nil
}
func (manager *SDBInstanceNetworkManager) newFromCloudDBNetwork(ctx context.Context, userCred mcclient.TokenCredential, dbinstance *SDBInstance, network *cloudprovider.SDBInstanceNetwork) error {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
dbNetwork := SDBInstanceNetwork{}
dbNetwork.SetModelManager(manager, &dbNetwork)
dbNetwork.DBInstanceId = dbinstance.Id
_localnetwork, err := db.FetchByExternalId(NetworkManager, network.NetworkId)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBNetwork.FetchByExternalId")
}
localnetwork := _localnetwork.(*SNetwork)
ipAdd, err := netutils.NewIPV4Addr(network.IP)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBNetwork.NewIPV4Addr")
}
if !localnetwork.IsAddressInRange(ipAdd) {
return fmt.Errorf("IP %s not in network %s(%s) address range", network.IP, localnetwork.Name, localnetwork.Id)
}
dbNetwork.NetworkId = localnetwork.Id
dbNetwork.IpAddr = network.IP
err = manager.TableSpec().Insert(&dbNetwork)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBNetwork.Insert")
}
return nil
}
+191
View File
@@ -0,0 +1,191 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"fmt"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/cloudcommon/validators"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/sqlchemy"
)
type SDBInstanceParameterManager struct {
db.SStandaloneResourceBaseManager
}
var DBInstanceParameterManager *SDBInstanceParameterManager
func init() {
DBInstanceParameterManager = &SDBInstanceParameterManager{
SStandaloneResourceBaseManager: db.NewStandaloneResourceBaseManager(
SDBInstanceParameter{},
"dbinstanceparameters_tbl",
"dbinstanceparameter",
"dbinstanceparameters",
),
}
DBInstanceParameterManager.SetVirtualObject(DBInstanceParameterManager)
}
type SDBInstanceParameter struct {
db.SStandaloneResourceBase
db.SExternalizedResourceBase
DBInstanceId string `width:"36" charset:"ascii" name:"dbinstance_id" nullable:"false" list:"user" create:"required" index:"true"`
Key string `width:"64" charset:"ascii" nullable:"false" list:"user" update:"user" create:"required"`
Value string `width:"16" charset:"ascii" nullable:"false" list:"user" update:"user" create:"required"`
}
func (manager *SDBInstanceParameterManager) GetContextManagers() [][]db.IModelManager {
return [][]db.IModelManager{
{DBInstanceManager},
}
}
func (self *SDBInstanceParameterManager) AllowListItems(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowList(userCred, self)
}
func (self *SDBInstanceParameterManager) AllowCreateItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowCreate(userCred, self)
}
func (self *SDBInstanceParameter) AllowGetDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowGet(userCred, self)
}
func (self *SDBInstanceParameter) AllowUpdateItem(ctx context.Context, userCred mcclient.TokenCredential) bool {
return db.IsAdminAllowUpdate(userCred, self)
}
func (self *SDBInstanceParameter) AllowDeleteItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowDelete(userCred, self)
}
func (manager *SDBInstanceParameterManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
q, err := manager.SStandaloneResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
if err != nil {
return nil, err
}
data := query.(*jsonutils.JSONDict)
return validators.ApplyModelFilters(q, data, []*validators.ModelFilterOptions{
{Key: "dbinstance", ModelKeyword: "dbinstance", OwnerId: userCred},
})
}
func (manager *SDBInstanceParameterManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
return nil, httperrors.NewNotImplementedError("Not Implemented")
}
func (manager *SDBInstanceParameterManager) getDBInstanceParametersByInstance(instance *SDBInstance) ([]SDBInstanceParameter, error) {
parameters := []SDBInstanceParameter{}
q := manager.Query().Equals("dbinstance_id", instance.Id)
err := db.FetchModelObjects(manager, q, &parameters)
if err != nil {
return nil, errors.Wrap(err, "getDBInstanceParametersByInstance.FetchModelObjects")
}
return parameters, nil
}
func (manager *SDBInstanceParameterManager) SyncDBInstanceParameters(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, cloudParameters []cloudprovider.ICloudDBInstanceParameter) compare.SyncResult {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, instance.GetOwnerId()))
result := compare.SyncResult{}
dbParameters, err := manager.getDBInstanceParametersByInstance(instance)
if err != nil {
result.Error(err)
return result
}
removed := make([]SDBInstanceParameter, 0)
commondb := make([]SDBInstanceParameter, 0)
commonext := make([]cloudprovider.ICloudDBInstanceParameter, 0)
added := make([]cloudprovider.ICloudDBInstanceParameter, 0)
if err := compare.CompareSets(dbParameters, cloudParameters, &removed, &commondb, &commonext, &added); err != nil {
result.Error(err)
return result
}
for i := 0; i < len(removed); i++ {
err := removed[i].Delete(ctx, userCred)
if err != nil {
result.DeleteError(err)
} else {
result.Delete()
}
}
for i := 0; i < len(commondb); i++ {
err := commondb[i].SyncWithCloudDBInstanceParameter(ctx, userCred, commonext[i])
if err != nil {
result.UpdateError(err)
} else {
result.Update()
}
}
for i := 0; i < len(added); i++ {
err = manager.newFromCloudDBInstanceParameter(ctx, userCred, instance, added[i])
if err != nil {
result.AddError(err)
} else {
result.Add()
}
}
return result
}
func (self *SDBInstanceParameter) SyncWithCloudDBInstanceParameter(ctx context.Context, userCred mcclient.TokenCredential, extParameter cloudprovider.ICloudDBInstanceParameter) error {
_, err := db.UpdateWithLock(ctx, self, func() error {
self.Key = extParameter.GetKey()
self.Value = extParameter.GetValue()
return nil
})
if err != nil {
return errors.Wrapf(err, "SyncWithCloudDBInstanceParameter.UpdateWithLock")
}
return nil
}
func (manager *SDBInstanceParameterManager) newFromCloudDBInstanceParameter(ctx context.Context, userCred mcclient.TokenCredential, instance *SDBInstance, extParameter cloudprovider.ICloudDBInstanceParameter) error {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
parameter := SDBInstanceParameter{}
parameter.SetModelManager(manager, &parameter)
parameter.Name = fmt.Sprintf("%s-%s", instance.Name, extParameter.GetKey())
parameter.DBInstanceId = instance.Id
parameter.Description = extParameter.GetDescription()
parameter.Key = extParameter.GetKey()
parameter.Value = extParameter.GetValue()
parameter.ExternalId = extParameter.GetGlobalId()
err := manager.TableSpec().Insert(&parameter)
if err != nil {
return errors.Wrapf(err, "newFromCloudDBInstanceParameter.Insert")
}
return nil
}
+441
View File
@@ -0,0 +1,441 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"database/sql"
"yunion.io/x/jsonutils"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/cloudcommon/validators"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/httperrors"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/sqlchemy"
)
type SDBInstanceManager struct {
db.SVirtualResourceBaseManager
}
var DBInstanceManager *SDBInstanceManager
func init() {
DBInstanceManager = &SDBInstanceManager{
SVirtualResourceBaseManager: db.NewVirtualResourceBaseManager(
SDBInstance{},
"dbinstances_tbl",
"dbinstance",
"dbinstances",
),
}
DBInstanceManager.SetVirtualObject(DBInstanceManager)
}
type SDBInstance struct {
db.SVirtualResourceBase
db.SExternalizedResourceBase
SManagedResourceBase
SBillingResourceBase
SCloudregionResourceBase
SZoneResourceBase
VcpuCount int `nullable:"false" default:"1" list:"user" create:"optional"` // Column(TINYINT, nullable=False, default=1)
VmemSizeMb int `nullable:"false" list:"user" create:"required"` // Column(Integer, nullable=False)
DiskSizeGB int `nullable:"false" list:"user" create:"required"`
Port int `nullable:"false" list:"user" create:"required"`
Engine string `width:"16" charset:"ascii" nullable:"false" list:"user" create:"required"`
EngineVersion string `width:"16" charset:"ascii" nullable:"false" list:"user" create:"required"`
InstanceType string `width:"64" charset:"ascii" nullable:"true" list:"user" create:"optional"`
MaintainTime string `width:"64" charset:"ascii" nullable:"true" list:"user" create:"optional"`
VpcId string `width:"36" charset:"ascii" nullable:"false" list:"user" create:"optional"`
}
func (manager *SDBInstanceManager) GetContextManagers() [][]db.IModelManager {
return [][]db.IModelManager{
{CloudregionManager},
}
}
func (self *SDBInstanceManager) AllowListItems(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowList(userCred, self)
}
func (self *SDBInstanceManager) AllowCreateItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowCreate(userCred, self)
}
func (self *SDBInstance) AllowGetDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return db.IsAdminAllowGet(userCred, self)
}
func (self *SDBInstance) AllowUpdateItem(ctx context.Context, userCred mcclient.TokenCredential) bool {
return db.IsAdminAllowUpdate(userCred, self)
}
func (self *SDBInstance) AllowDeleteItem(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, data jsonutils.JSONObject) bool {
return db.IsAdminAllowDelete(userCred, self)
}
func (man *SDBInstanceManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
q, err := man.SVirtualResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
if err != nil {
return nil, err
}
data := query.(*jsonutils.JSONDict)
q, err = validators.ApplyModelFilters(q, data, []*validators.ModelFilterOptions{
{Key: "vpc", ModelKeyword: "vpc", OwnerId: userCred},
{Key: "zone", ModelKeyword: "zone", OwnerId: userCred},
{Key: "cloudregion", ModelKeyword: "cloudregion", OwnerId: userCred},
})
if err != nil {
return nil, err
}
q, err = managedResourceFilterByAccount(q, query, "", nil)
if err != nil {
return nil, err
}
return q, nil
}
func (man *SDBInstanceManager) ValidateCreateData(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, query jsonutils.JSONObject, data *jsonutils.JSONDict) (*jsonutils.JSONDict, error) {
return nil, httperrors.NewNotImplementedError("Not Implemented")
}
func (self *SDBInstance) GetExtraDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*jsonutils.JSONDict, error) {
extra, err := self.SVirtualResourceBase.GetExtraDetails(ctx, userCred, query)
if err != nil {
return nil, err
}
return self.getMoreDetails(ctx, userCred, query, extra), nil
}
func (self *SDBInstance) GetVpc() (*SVpc, error) {
vpc, err := VpcManager.FetchById(self.VpcId)
if err != nil {
return nil, err
}
return vpc.(*SVpc), nil
}
func (self *SDBInstance) getMoreDetails(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject, extra *jsonutils.JSONDict) *jsonutils.JSONDict {
accountInfo := self.SManagedResourceBase.GetCustomizeColumns(ctx, userCred, query)
if accountInfo != nil {
extra.Update(accountInfo)
}
regionInfo := self.SCloudregionResourceBase.GetCustomizeColumns(ctx, userCred, query)
if regionInfo != nil {
extra.Update(regionInfo)
}
zoneInfo := self.SZoneResourceBase.GetCustomizeColumns(ctx, userCred, query)
if zoneInfo != nil {
extra.Update(zoneInfo)
}
vpc, _ := self.GetVpc()
if vpc != nil {
extra.Add(jsonutils.NewString(vpc.Name), "vpc")
}
return extra
}
func (self *SDBInstance) GetCustomizeColumns(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) *jsonutils.JSONDict {
extra := self.SStatusStandaloneResourceBase.GetCustomizeColumns(ctx, userCred, query)
return self.getMoreDetails(ctx, userCred, query, extra)
}
func (manager *SDBInstanceManager) getDBInstancesByProviderId(providerId string) ([]SDBInstance, error) {
instances := []SDBInstance{}
err := fetchByManagerId(manager, providerId, &instances)
if err != nil {
return nil, errors.Wrapf(err, "getDBInstancesByProviderId.fetchByManagerId")
}
return instances, nil
}
func (manager *SDBInstanceManager) getDBInstancesByRegion(region *SCloudregion, provider *SCloudprovider) ([]SDBInstance, error) {
dbInstances := []SDBInstance{}
q := manager.Query().Equals("cloudregion_id", region.Id)
if provider != nil {
q = q.Equals("manager_id", provider.Id)
}
err := db.FetchModelObjects(manager, q, &dbInstances)
if err != nil {
return nil, err
}
return dbInstances, nil
}
func (self *SDBInstance) GetDBAccounts() ([]SDBInstanceAccount, error) {
accounts := []SDBInstanceAccount{}
q := DBInstanceAccountManager.Query().Equals("dbinstance_id", self.Id)
err := db.FetchModelObjects(DBInstanceAccountManager, q, &accounts)
if err != nil {
return nil, errors.Wrap(err, "GetDBAccounts.FetchModelObjects")
}
return accounts, nil
}
func (self *SDBInstance) GetDBBackups() ([]SDBInstanceBackup, error) {
backups := []SDBInstanceBackup{}
q := DBInstanceBackupManager.Query().Equals("dbinstance_id", self.Id)
err := db.FetchModelObjects(DBInstanceBackupManager, q, &backups)
if err != nil {
return nil, errors.Wrap(err, "GetDBBackups.FetchModelObjects")
}
return backups, nil
}
func (self *SDBInstance) GetDBDatabases() ([]SDBInstanceDatabase, error) {
databases := []SDBInstanceDatabase{}
q := DBInstanceDatabaseManager.Query().Equals("dbinstance_id", self.Id)
err := db.FetchModelObjects(DBInstanceDatabaseManager, q, &databases)
if err != nil {
return nil, errors.Wrap(err, "GetDBDatabases.FetchModelObjects")
}
return databases, nil
}
func (self *SDBInstance) GetDBParameters() ([]SDBInstanceParameter, error) {
parameters := []SDBInstanceParameter{}
q := DBInstanceParameterManager.Query().Equals("dbinstance_id", self.Id)
err := db.FetchModelObjects(DBInstanceParameterManager, q, &parameters)
if err != nil {
return nil, errors.Wrap(err, "GetDBParameters.FetchModelObjects")
}
return parameters, nil
}
func (self *SDBInstance) GetServiceIps() ([]SServiceIp, error) {
serviceips := []SServiceIp{}
q := ServiceIpManager.Query().Equals("service_id", self.Id)
err := db.FetchModelObjects(ServiceIpManager, q, &serviceips)
if err != nil {
return nil, errors.Wrap(err, "GetServiceIps.FetchModelObjects")
}
return serviceips, nil
}
func (self *SDBInstance) GetDBNetwork() (*SDBInstanceNetwork, error) {
q := DBInstanceNetworkManager.Query().Equals("dbinstance_id", self.Id)
count, err := q.CountWithError()
if err != nil {
return nil, err
}
if count == 1 {
network := &SDBInstanceNetwork{}
network.SetModelManager(DBInstanceNetworkManager, network)
err = q.First(network)
if err != nil {
return nil, err
}
return network, nil
}
if count > 1 {
return nil, sqlchemy.ErrDuplicateEntry
}
return nil, sql.ErrNoRows
}
func (manager *SDBInstanceManager) SyncDBInstances(ctx context.Context, userCred mcclient.TokenCredential, syncOwnerId mcclient.IIdentityProvider, provider *SCloudprovider, region *SCloudregion, cloudDBInstances []cloudprovider.ICloudDBInstance) ([]SDBInstance, []cloudprovider.ICloudDBInstance, compare.SyncResult) {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, provider.GetOwnerId()))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, provider.GetOwnerId()))
localDBInstances := []SDBInstance{}
remoteDBInstances := []cloudprovider.ICloudDBInstance{}
syncResult := compare.SyncResult{}
dbInstances, err := manager.getDBInstancesByRegion(region, provider)
if err != nil {
syncResult.Error(err)
return nil, nil, syncResult
}
removed := make([]SDBInstance, 0)
commondb := make([]SDBInstance, 0)
commonext := make([]cloudprovider.ICloudDBInstance, 0)
added := make([]cloudprovider.ICloudDBInstance, 0)
if err := compare.CompareSets(dbInstances, cloudDBInstances, &removed, &commondb, &commonext, &added); err != nil {
syncResult.Error(err)
return nil, nil, syncResult
}
for i := 0; i < len(removed); i++ {
err := removed[i].syncRemoveCloudDBInstance(ctx, userCred)
if err != nil {
syncResult.DeleteError(err)
} else {
syncResult.Delete()
}
}
for i := 0; i < len(commondb); i++ {
err := commondb[i].SyncWithCloudDBInstance(ctx, userCred, provider, commonext[i])
if err != nil {
syncResult.UpdateError(err)
continue
}
syncMetadata(ctx, userCred, &commondb[i], commonext[i])
localDBInstances = append(localDBInstances, commondb[i])
remoteDBInstances = append(remoteDBInstances, commonext[i])
syncResult.Update()
}
for i := 0; i < len(added); i++ {
instance, err := manager.newFromCloudDBInstance(ctx, userCred, syncOwnerId, provider, region, added[i])
if err != nil {
syncResult.AddError(err)
continue
}
syncMetadata(ctx, userCred, instance, added[i])
localDBInstances = append(localDBInstances, *instance)
remoteDBInstances = append(remoteDBInstances, added[i])
syncResult.Add()
}
return localDBInstances, remoteDBInstances, syncResult
}
func (self *SDBInstance) syncRemoveCloudDBInstance(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, self)
defer lockman.ReleaseObject(ctx, self)
err := self.ValidateDeleteCondition(ctx)
if err != nil { // cannot delete
return self.SetStatus(userCred, api.VPC_STATUS_UNKNOWN, "sync to delete")
}
return self.Delete(ctx, userCred)
}
func (self *SDBInstance) SyncWithCloudDBInstance(ctx context.Context, userCred mcclient.TokenCredential, provider *SCloudprovider, extInstance cloudprovider.ICloudDBInstance) error {
diff, err := db.UpdateWithLock(ctx, self, func() error {
self.Engine = extInstance.GetEngine()
self.EngineVersion = extInstance.GetEngineVersion()
self.InstanceType = extInstance.GetInstanceType()
self.VcpuCount = extInstance.GetVcpuCount()
self.VmemSizeMb = extInstance.GetVmemSizeMB()
self.DiskSizeGB = extInstance.GetDiskSizeGB()
self.Status = extInstance.GetStatus()
self.MaintainTime = extInstance.GetMaintainTime()
if zoneId := extInstance.GetIZoneId(); len(zoneId) > 0 {
zone, err := db.FetchByExternalId(ZoneManager, zoneId)
if err != nil {
return errors.Wrapf(err, "SyncWithCloudDBInstance.FetchZoneId")
}
self.ZoneId = zone.GetId()
}
if createdAt := extInstance.GetCreatedAt(); !createdAt.IsZero() {
self.CreatedAt = createdAt
}
factory, err := provider.GetProviderFactory()
if err != nil {
return errors.Wrap(err, "SyncWithCloudDBInstance.GetProviderFactory")
}
if factory.IsSupportPrepaidResources() {
self.BillingType = extInstance.GetBillingType()
self.ExpiredAt = extInstance.GetExpiredAt()
}
return nil
})
if err != nil {
return err
}
db.OpsLog.LogSyncUpdate(self, diff, userCred)
return nil
}
func (manager *SDBInstanceManager) newFromCloudDBInstance(ctx context.Context, userCred mcclient.TokenCredential, ownerId mcclient.IIdentityProvider, provider *SCloudprovider, region *SCloudregion, extInstance cloudprovider.ICloudDBInstance) (*SDBInstance, error) {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
instance := SDBInstance{}
instance.SetModelManager(manager, &instance)
newName, err := db.GenerateName(manager, ownerId, extInstance.GetName())
if err != nil {
return nil, err
}
instance.Name = newName
instance.ExternalId = extInstance.GetGlobalId()
instance.CloudregionId = region.Id
instance.ManagerId = provider.Id
instance.IsEmulated = extInstance.IsEmulated()
instance.Status = extInstance.GetStatus()
instance.Port = extInstance.GetPort()
instance.Engine = extInstance.GetEngine()
instance.EngineVersion = extInstance.GetEngineVersion()
instance.InstanceType = extInstance.GetInstanceType()
instance.VcpuCount = extInstance.GetVcpuCount()
instance.VmemSizeMb = extInstance.GetVmemSizeMB()
instance.DiskSizeGB = extInstance.GetDiskSizeGB()
instance.MaintainTime = extInstance.GetMaintainTime()
if zoneId := extInstance.GetIZoneId(); len(zoneId) > 0 {
zone, err := db.FetchByExternalId(ZoneManager, zoneId)
if err != nil {
return nil, errors.Wrapf(err, "newFromCloudDBInstance.FetchZoneId")
}
instance.ZoneId = zone.GetId()
}
if vpcId := extInstance.GetIVpcId(); len(vpcId) > 0 {
vpc, err := db.FetchByExternalId(VpcManager, vpcId)
if err != nil {
return nil, errors.Wrapf(err, "newFromCloudDBInstance.FetchVpcId")
}
instance.VpcId = vpc.GetId()
}
if createdAt := extInstance.GetCreatedAt(); !createdAt.IsZero() {
instance.CreatedAt = createdAt
}
factory, err := provider.GetProviderFactory()
if err != nil {
return nil, errors.Wrap(err, "newFromCloudDBInstance.GetProviderFactory")
}
if factory.IsSupportPrepaidResources() {
instance.BillingType = extInstance.GetBillingType()
instance.ExpiredAt = extInstance.GetExpiredAt()
}
err = manager.TableSpec().Insert(&instance)
if err != nil {
return nil, errors.Wrapf(err, "newFromCloudDBInstance.Insert")
}
SyncCloudProject(userCred, &instance, ownerId, extInstance, instance.ManagerId)
db.OpsLog.LogEvent(&instance, db.ACT_CREATE, instance.GetShortDesc(ctx), userCred)
return &instance, nil
}
+205 -1
View File
@@ -1040,6 +1040,58 @@ func (manager *SNetworkInterfaceManager) purgeAll(ctx context.Context, userCred
return nil
}
func (account *SDBInstanceAccount) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, account)
defer lockman.ReleaseObject(ctx, account)
err := account.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return account.Delete(ctx, userCred)
}
func (instance *SDBInstance) purgeAccounts(ctx context.Context, userCred mcclient.TokenCredential) error {
accounts, err := instance.GetDBAccounts()
if err != nil {
return err
}
for i := range accounts {
err = accounts[i].purge(ctx, userCred)
if err != nil {
return err
}
}
return nil
}
func (backup *SDBInstanceBackup) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, backup)
defer lockman.ReleaseObject(ctx, backup)
err := backup.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return backup.Delete(ctx, userCred)
}
func (instance *SDBInstance) purgeBackups(ctx context.Context, userCred mcclient.TokenCredential) error {
backups, err := instance.GetDBBackups()
if err != nil {
return err
}
for i := range backups {
err = backups[i].purge(ctx, userCred)
if err != nil {
return err
}
}
return nil
}
func (bucket *SBucket) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, bucket)
defer lockman.ReleaseObject(ctx, bucket)
@@ -1048,8 +1100,146 @@ func (bucket *SBucket) purge(ctx context.Context, userCred mcclient.TokenCredent
if err != nil {
return err
}
return bucket.Delete(ctx, userCred)
}
return bucket.RealDelete(ctx, userCred)
func (database *SDBInstanceDatabase) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, database)
defer lockman.ReleaseObject(ctx, database)
err := database.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return database.Delete(ctx, userCred)
}
func (instance *SDBInstance) purgeDatabases(ctx context.Context, userCred mcclient.TokenCredential) error {
databases, err := instance.GetDBDatabases()
if err != nil {
return err
}
for i := range databases {
err = databases[i].purge(ctx, userCred)
if err != nil {
return err
}
}
return nil
}
func (parameter *SDBInstanceParameter) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, parameter)
defer lockman.ReleaseObject(ctx, parameter)
err := parameter.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return parameter.Delete(ctx, userCred)
}
func (instance *SDBInstance) purgeParameters(ctx context.Context, userCred mcclient.TokenCredential) error {
parameters, err := instance.GetDBParameters()
if err != nil {
return err
}
for i := range parameters {
err = parameters[i].purge(ctx, userCred)
if err != nil {
return err
}
}
return nil
}
func (serviceip *SServiceIp) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, serviceip)
defer lockman.ReleaseObject(ctx, serviceip)
err := serviceip.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return serviceip.Delete(ctx, userCred)
}
func (instance *SDBInstance) purgeServiceips(ctx context.Context, userCred mcclient.TokenCredential) error {
serviceips, err := instance.GetServiceIps()
if err != nil {
return err
}
for i := range serviceips {
err = serviceips[i].purge(ctx, userCred)
if err != nil {
return err
}
}
return nil
}
func (network *SDBInstanceNetwork) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, network)
defer lockman.ReleaseObject(ctx, network)
err := network.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return network.Delete(ctx, userCred)
}
func (instance *SDBInstance) purgeNetwork(ctx context.Context, userCred mcclient.TokenCredential) error {
network, _ := instance.GetDBNetwork()
if network != nil {
return network.purge(ctx, userCred)
}
return nil
}
func (instance *SDBInstance) purge(ctx context.Context, userCred mcclient.TokenCredential) error {
lockman.LockObject(ctx, instance)
defer lockman.ReleaseObject(ctx, instance)
err := instance.purgeAccounts(ctx, userCred)
if err != nil {
return err
}
err = instance.purgeBackups(ctx, userCred)
if err != nil {
return err
}
err = instance.purgeDatabases(ctx, userCred)
if err != nil {
return err
}
err = instance.purgeParameters(ctx, userCred)
if err != nil {
return err
}
err = instance.purgeServiceips(ctx, userCred)
if err != nil {
return err
}
err = instance.purgeNetwork(ctx, userCred)
if err != nil {
return err
}
err = instance.ValidateDeleteCondition(ctx)
if err != nil {
return err
}
return instance.Delete(ctx, userCred)
}
func (bucketManager *SBucketManager) purgeAll(ctx context.Context, userCred mcclient.TokenCredential, providerId string) error {
@@ -1066,3 +1256,17 @@ func (bucketManager *SBucketManager) purgeAll(ctx context.Context, userCred mccl
}
return nil
}
func (manager *SDBInstanceManager) purgeAll(ctx context.Context, userCred mcclient.TokenCredential, providerId string) error {
instances, err := manager.getDBInstancesByProviderId(providerId)
if err != nil {
return err
}
for i := range instances {
err = instances[i].purge(ctx, userCred)
if err != nil {
return err
}
}
return nil
}
+140
View File
@@ -0,0 +1,140 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 models
import (
"context"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/util/compare"
"yunion.io/x/jsonutils"
"yunion.io/x/onecloud/pkg/cloudcommon/db"
"yunion.io/x/onecloud/pkg/cloudcommon/db/lockman"
"yunion.io/x/onecloud/pkg/mcclient"
"yunion.io/x/sqlchemy"
)
type SServiceIpManager struct {
db.SResourceBaseManager
}
var ServiceIpManager *SServiceIpManager
func init() {
ServiceIpManager = &SServiceIpManager{
SResourceBaseManager: db.NewResourceBaseManager(
SServiceIp{},
"serviceips_tbl",
"serviceip",
"serviceips",
),
}
}
func (model *SServiceIp) BeforeInsert() {
if len(model.Id) == 0 {
model.Id = db.DefaultUUIDGenerator()
}
}
type SServiceIp struct {
db.SResourceBase
Id string `width:"128" charset:"ascii" primary:"true" list:"user" get:"user"`
ServiceId string `width:"36" charset:"ascii" nullable:"false" list:"user" `
IpAddr string `width:"16" charset:"ascii" nullable:"false" list:"user"`
URL string `width:"256" charset:"ascii" nullable:"true" list:"user"`
ServiceType string `width:"16" charset:"ascii" nullable:"false" list:"user"`
}
func (manager *SServiceIpManager) AllowListItems(ctx context.Context, userCred mcclient.TokenCredential, query jsonutils.JSONObject) bool {
return true
}
func (manager *SServiceIpManager) ListItemFilter(ctx context.Context, q *sqlchemy.SQuery, userCred mcclient.TokenCredential, query jsonutils.JSONObject) (*sqlchemy.SQuery, error) {
return manager.SResourceBaseManager.ListItemFilter(ctx, q, userCred, query)
}
func (manager *SServiceIpManager) GetServiceIps(resource db.IModel) ([]SServiceIp, error) {
q := manager.Query().Equals("service_id", resource.GetId()).Equals("service_type", resource.Keyword())
ips := []SServiceIp{}
err := db.FetchModelObjects(manager, q, &ips)
if err != nil {
return nil, errors.Wrapf(err, "GetServiceIps.FetchModelObjects")
}
return ips, nil
}
func (manager *SServiceIpManager) SyncExtraIps(ctx context.Context, userCred mcclient.TokenCredential, resource db.IModel, ips []cloudprovider.SExtraIp) compare.SyncResult {
result := compare.SyncResult{}
dbServiceIps, err := manager.GetServiceIps(resource)
if err != nil {
result.Error(err)
return result
}
localIps := map[string]*SServiceIp{}
for i := 0; i < len(dbServiceIps); i++ {
localIps[dbServiceIps[i].IpAddr] = &dbServiceIps[i]
}
remoteIps := map[string]cloudprovider.SExtraIp{}
for i := 0; i < len(ips); i++ {
remoteIps[ips[i].IP] = ips[i]
}
for _, ip := range ips {
if _, exist := localIps[ip.IP]; !exist {
err = manager.newServiceIp(ctx, userCred, resource, ip)
if err != nil {
result.AddError(err)
} else {
result.Add()
}
}
}
for ip, serviceIp := range localIps {
if _, exist := remoteIps[ip]; !exist {
err := serviceIp.Delete(ctx, userCred)
if err != nil {
result.DeleteError(err)
} else {
result.Delete()
}
}
}
return result
}
func (manager *SServiceIpManager) newServiceIp(ctx context.Context, userCred mcclient.TokenCredential, resource db.IModel, ip cloudprovider.SExtraIp) error {
lockman.LockClass(ctx, manager, db.GetLockClassKey(manager, userCred))
defer lockman.ReleaseClass(ctx, manager, db.GetLockClassKey(manager, userCred))
serviceIp := SServiceIp{}
serviceIp.SetModelManager(manager, &serviceIp)
serviceIp.ServiceId = resource.GetId()
serviceIp.ServiceType = resource.Keyword()
serviceIp.IpAddr = ip.IP
serviceIp.URL = ip.URL
err := manager.TableSpec().Insert(&serviceIp)
if err != nil {
return errors.Wrapf(err, "newServiceIp.Insert")
}
return nil
}
+7
View File
@@ -113,6 +113,12 @@ func InitHandlers(app *appsrv.Application) {
models.ExternalProjectManager,
models.NetworkInterfaceManager,
models.NetworkinterfacenetworkManager,
models.DBInstanceManager,
models.DBInstanceBackupManager,
models.DBInstanceParameterManager,
models.DBInstanceDatabaseManager,
models.DBInstanceAccountManager,
models.ServiceIpManager,
} {
db.RegisterModelManager(manager)
handler := db.NewModelHandler(manager)
@@ -134,6 +140,7 @@ func InitHandlers(app *appsrv.Application) {
models.GroupguestManager,
models.StoragecachedimageManager,
models.CloudproviderRegionManager,
models.DBInstanceNetworkManager,
} {
db.RegisterModelManager(manager)
handler := db.NewJointModelHandler(manager)
@@ -0,0 +1,27 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
DBInstanceAccounts ResourceManager
)
func init() {
DBInstanceAccounts = NewComputeManager("dbinstanceaccount", "dbinstanceaccounts",
[]string{"ID", "Name", "DBInstance_id"},
[]string{})
registerCompute(&DBInstanceAccounts)
}
@@ -0,0 +1,27 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
DBInstanceBackups ResourceManager
)
func init() {
DBInstanceBackups = NewComputeManager("dbinstancebackup", "dbinstancebackups",
[]string{"ID", "Name", "Start_Time", "End_Time", "Backup_Type", "Intranet_Download_URL", "Download_URL", "DBNames", "Backup_Size_Mb", "DBInstance_id"},
[]string{})
registerCompute(&DBInstanceBackups)
}
@@ -0,0 +1,27 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
DBInstanceDatabases ResourceManager
)
func init() {
DBInstanceDatabases = NewComputeManager("dbinstancedatabase", "dbinstancedatabases",
[]string{"ID", "Name", "Character_Set", "DBInstance_id"},
[]string{})
registerCompute(&DBInstanceDatabases)
}
@@ -0,0 +1,32 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
DBInstanceNetworks JointResourceManager
)
func init() {
DBInstanceNetworks = NewJointComputeManager(
"dbinstancenetwork",
"dbinstancenetworks",
[]string{"Instance_Id", "Network_Id", "IP_Addr"},
[]string{},
&DBInstance,
&Networks,
)
registerCompute(&DBInstanceNetworks)
}
@@ -0,0 +1,27 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
DBInstanceParameters ResourceManager
)
func init() {
DBInstanceParameters = NewComputeManager("dbinstanceparameter", "dbinstanceparameters",
[]string{"ID", "Name", "Key", "Value", "Description"},
[]string{})
registerCompute(&DBInstanceParameters)
}
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
DBInstance ResourceManager
)
func init() {
DBInstance = NewComputeManager("dbinstance", "dbinstances",
[]string{"ID", "Name", "Billing_type", "Cloudregion_Id", "Status", "Vcpu_Count", "Vmem_Size"},
[]string{})
registerCompute(&DBInstance)
}
+27
View File
@@ -0,0 +1,27 @@
// Copyright 2019 Yunion
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT 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 modules
var (
ServiceIp ResourceManager
)
func init() {
ServiceIp = NewComputeManager("serviceip", "serviceips",
[]string{"ID", "Ip_Addr", "URL", "Service_Id", "Service_Type"},
[]string{})
registerCompute(&ServiceIp)
}
+35
View File
@@ -0,0 +1,35 @@
package multicloud
import (
"fmt"
"yunion.io/x/onecloud/pkg/cloudprovider"
)
type SDBInstanceBase struct {
SVirtualResourceBase
}
func (instance *SDBInstanceBase) GetDBNetwork() (*cloudprovider.SDBInstanceNetwork, error) {
return nil, fmt.Errorf("Not Implemented GetDBNetwork")
}
func (instance *SDBInstanceBase) GetExtraIps() ([]cloudprovider.SExtraIp, error) {
return nil, fmt.Errorf("Not Implemented GetExtraIps")
}
func (instance *SDBInstanceBase) GetIDBInstanceParameters() ([]cloudprovider.ICloudDBInstanceParameter, error) {
return nil, fmt.Errorf("Not Implemented GetIDBInstanceParameters")
}
func (instance *SDBInstanceBase) GetIDBInstanceBackups() ([]cloudprovider.ICloudDBInstanceBackup, error) {
return nil, fmt.Errorf("Not Implemented GetIDBInstanceBackups")
}
func (instance *SDBInstanceBase) GetIDBInstanceDatabases() ([]cloudprovider.ICloudDBInstanceDatabase, error) {
return nil, fmt.Errorf("Not Implemented GetIDBInstanceDatabases")
}
func (instance *SDBInstanceBase) GetIDBInstanceAccounts() ([]cloudprovider.ICloudDBInstanceAccount, error) {
return nil, fmt.Errorf("Not Implemented GetIDBInstanceAccounts")
}
+5
View File
@@ -0,0 +1,5 @@
package multicloud
type SDBInstanceAccountBase struct {
SResourceBase
}
+5
View File
@@ -0,0 +1,5 @@
package multicloud
type SDBInstanceBackupBase struct {
SResourceBase
}
@@ -0,0 +1,5 @@
package multicloud
type SDBInstanceDatabaseBase struct {
SResourceBase
}
+22
View File
@@ -21,6 +21,8 @@ import (
"path"
"time"
"yunion.io/x/jsonutils"
"github.com/minio/minio-go"
"yunion.io/x/pkg/errors"
@@ -38,10 +40,30 @@ type SBucket struct {
Acl string
}
func (bucket *SBucket) GetId() string {
return ""
}
func (bucket *SBucket) GetStatus() string {
return ""
}
func (bucket *SBucket) GetMetadata() *jsonutils.JSONDict {
return nil
}
func (bucket *SBucket) GetProjectId() string {
return ""
}
func (bucket *SBucket) IsEmulated() bool {
return false
}
func (bucket *SBucket) Refresh() error {
return nil
}
func (bucket *SBucket) GetGlobalId() string {
return bucket.Name
}
+4
View File
@@ -61,3 +61,7 @@ func (self *SRegion) GetISkuById(skuId string) (cloudprovider.ICloudSku, error)
func (self *SRegion) GetINetworkInterfaces() ([]cloudprovider.ICloudNetworkInterface, error) {
return nil, fmt.Errorf("Not Implement GetINetworkInterfaces")
}
func (self *SRegion) GetIDBInstances() ([]cloudprovider.ICloudDBInstance, error) {
return nil, fmt.Errorf("GetIDBInstances not implement")
}
+9
View File
@@ -0,0 +1,9 @@
package multicloud
type SVirtualResourceBase struct {
SResourceBase
}
func (self *SVirtualResourceBase) GetProjectId() string {
return ""
}
+1
View File
@@ -43,6 +43,7 @@ const (
ALIYUN_BSS_API_VERSION = "2017-12-14"
ALIYUN_RAM_API_VERSION = "2015-05-01"
ALIYUN_API_VERION_RDS = "2014-08-15"
)
type SAliyunClient struct {
+3
View File
@@ -20,6 +20,8 @@ import (
"io"
"time"
"yunion.io/x/onecloud/pkg/multicloud/objectstore"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"yunion.io/x/pkg/errors"
@@ -28,6 +30,7 @@ import (
)
type SBucket struct {
objectstore.SBucket
region *SRegion
Name string
+1 -1
View File
@@ -24,7 +24,7 @@ func convertChargeType(ct TChargeType) string {
switch ct {
case PrePaidInstanceChargeType:
return api.BILLING_TYPE_PREPAID
case PostPaidInstanceChargeType:
case PostPaidInstanceChargeType, PostPaidDBInstanceChargeType:
return api.BILLING_TYPE_POSTPAID
default:
return api.BILLING_TYPE_PREPAID
+443
View File
@@ -0,0 +1,443 @@
package aliyun
import (
"fmt"
"time"
"yunion.io/x/jsonutils"
"yunion.io/x/log"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud"
"yunion.io/x/pkg/errors"
)
type SReadOnlyDBInstanceIds struct {
ReadOnlyDBInstanceId []string
}
type SDBInstanceId struct {
DBInstanceId []string
}
type SDBInstanceExtra struct {
DBInstanceId SDBInstanceId
}
type SDBInstance struct {
multicloud.SDBInstanceBase
region *SRegion
AccountMaxQuantity int
AccountType string
CanTempUpgrade bool
Category string
AvailabilityValue string
DBInstanceDescription string
DBInstanceId string
ConnectionMode string
ConnectionString string
CurrentKernelVersion string
DBInstanceCPU int
CreateTime time.Time
DBInstanceClass string
DBInstanceClassType string
DBInstanceNetType string
DBInstanceStatus string
DBInstanceType string
DBInstanceDiskUsed int64
DBInstanceStorage int
DBInstanceStorageType string
DBInstanceMemory int
DBMaxQuantity int
IPType string
LatestKernelVersion string
DispenseMode string
Engine string
EngineVersion string
ExpireTime time.Time
InstanceNetworkType string
LockMode string
LockReason string
MutriORsignle bool
MaintainTime string
MaxConnections int
MaxIOPS int
Port int
PayType TChargeType
ReadOnlyDBInstanceIds SReadOnlyDBInstanceIds
RegionId string
ResourceGroupId string
VSwitchId string
VpcCloudInstanceId string
VpcId string
ZoneId string
Extra SDBInstanceExtra
SecurityIPList string
SecurityIPMode string
SupportCreateSuperAccount string
SupportUpgradeAccountType string
TempUpgradeTimeEnd time.Time
TempUpgradeTimeStart time.Time
}
func (rds *SDBInstance) GetName() string {
if len(rds.DBInstanceDescription) > 0 {
return rds.DBInstanceDescription
}
return rds.DBInstanceId
}
func (rds *SDBInstance) GetId() string {
return rds.DBInstanceId
}
func (rds *SDBInstance) GetGlobalId() string {
return rds.GetId()
}
// Creating 创建中
// Running 使用中
// Deleting 删除中
// Rebooting 重启中
// DBInstanceClassChanging 升降级中
// TRANSING 迁移中
// EngineVersionUpgrading 迁移版本中
// TransingToOthers 迁移数据到其他RDS中
// GuardDBInstanceCreating 生产灾备实例中
// Restoring 备份恢复中
// Importing 数据导入中
// ImportingFromOthers 从其他RDS实例导入数据中
// DBInstanceNetTypeChanging 内外网切换中
// GuardSwitching 容灾切换中
// INS_CLONING 实例克隆中
func (rds *SDBInstance) GetStatus() string {
switch rds.DBInstanceStatus {
case "Creating", "DBInstanceClassChanging", "GuardDBInstanceCreating", "DBInstanceNetTypeChanging", "GuardSwitching":
return api.DBINSTANCE_DEPLOYING
case "Running":
return api.DBINSTANCE_RUNNING
case "Deleting":
return api.DBINSTANCE_DELETING
case "Rebooting":
return api.DBINSTANCE_REBOOTING
case "TRANSING", "EngineVersionUpgrading", "TransingToOthers":
return api.DBINSTANCE_MIGRATING
case "Restoring":
return api.DBINSTANCE_RESTORING
case "Importing", "ImportingFromOthers":
return api.DBINSTANCE_IMPORTING
case "INS_CLONING":
return api.DBINSTANCE_CLONING
default:
return api.DBINSTANCE_UNKNOWN
}
}
func (rds *SDBInstance) GetBillingType() string {
return convertChargeType(rds.PayType)
}
func (rds *SDBInstance) GetExpiredAt() time.Time {
return rds.ExpireTime
}
func (rds *SDBInstance) GetCreatedAt() time.Time {
return rds.CreateTime
}
func (rds *SDBInstance) GetEngine() string {
return rds.Engine
}
func (rds *SDBInstance) GetEngineVersion() string {
return rds.EngineVersion
}
func (rds *SDBInstance) GetInstanceType() string {
return rds.DBInstanceClass
}
func (rds *SDBInstance) GetVcpuCount() int {
if rds.DBInstanceCPU == 0 {
rds.Refresh()
}
return rds.DBInstanceCPU
}
func (rds *SDBInstance) GetVmemSizeMB() int {
if rds.DBInstanceMemory == 0 {
rds.Refresh()
}
return rds.DBInstanceMemory
}
func (rds *SDBInstance) GetDiskSizeGB() int {
if rds.DBInstanceStorage == 0 {
rds.Refresh()
}
return rds.DBInstanceStorage
}
func (rds *SDBInstance) GetPort() int {
if rds.Port == 0 {
rds.Refresh()
}
return rds.Port
}
func (rds *SDBInstance) GetMaintainTime() string {
return rds.MaintainTime
}
func (rds *SDBInstance) GetIVpcId() string {
return rds.VpcId
}
func (rds *SDBInstance) Refresh() error {
instance, err := rds.region.GetDBInstanceDetail(rds.DBInstanceId)
if err != nil {
return err
}
return jsonutils.Update(rds, instance)
}
func (rds *SDBInstance) GetIZoneId() string {
if len(rds.ZoneId) > 0 {
zone, err := rds.region.getZoneById(rds.ZoneId)
if err != nil {
log.Errorf("SDBInstances.getZoneById %s error: %v", rds.ZoneId, err)
return ""
}
return zone.GetGlobalId()
}
return ""
}
func (rds *SDBInstance) GetDBNetwork() (*cloudprovider.SDBInstanceNetwork, error) {
netInfo, err := rds.region.GetDBInstanceNetInfo(rds.DBInstanceId)
if err != nil {
return nil, err
}
network := &cloudprovider.SDBInstanceNetwork{}
for _, net := range netInfo {
if net.IPType == "Private" {
network.IP = net.IPAddress
network.NetworkId = net.VSwitchId
return network, nil
}
}
return nil, fmt.Errorf("failed to found network for aliyun rds %s", rds.DBInstanceId)
}
func (rds *SDBInstance) GetExtraIps() ([]cloudprovider.SExtraIp, error) {
netInfo, err := rds.region.GetDBInstanceNetInfo(rds.DBInstanceId)
if err != nil {
return nil, err
}
ips := []cloudprovider.SExtraIp{}
for _, net := range netInfo {
if net.IPType == "Public" || net.IPType == "Inner" {
ips = append(ips, cloudprovider.SExtraIp{
IP: net.IPAddress,
URL: net.ConnectionString,
})
}
}
return ips, nil
}
func (region *SRegion) GetDBInstances(ids []string, offset int, limit int) ([]SDBInstance, int, error) {
if limit > 50 || limit <= 0 {
limit = 50
}
params := make(map[string]string)
params["RegionId"] = region.RegionId
params["PageSize"] = fmt.Sprintf("%d", limit)
params["PageNumber"] = fmt.Sprintf("%d", (offset/limit)+1)
body, err := region.rdsRequest("DescribeDBInstances", params)
if err != nil {
return nil, 0, errors.Wrapf(err, "GetDBInstances")
}
instances := []SDBInstance{}
err = body.Unmarshal(&instances, "Items", "DBInstance")
if err != nil {
return nil, 0, errors.Wrapf(err, "GetDBInstances.Unmarshal")
}
total, _ := body.Int("TotalRecordCount")
return instances, int(total), nil
}
func (region *SRegion) GetIDBInstances() ([]cloudprovider.ICloudDBInstance, error) {
instances := []SDBInstance{}
for {
part, total, err := region.GetDBInstances([]string{}, len(instances), 50)
if err != nil {
return nil, err
}
instances = append(instances, part...)
if len(instances) >= total {
break
}
}
idbinstances := []cloudprovider.ICloudDBInstance{}
for i := 0; i < len(instances); i++ {
instances[i].region = region
idbinstances = append(idbinstances, &instances[i])
}
return idbinstances, nil
}
func (region *SRegion) GetDBInstanceDetail(instanceId string) (*SDBInstance, error) {
params := map[string]string{}
params["RegionId"] = region.RegionId
params["DBInstanceId"] = instanceId
body, err := region.rdsRequest("DescribeDBInstanceAttribute", params)
if err != nil {
return nil, errors.Wrapf(err, "GetDBInstanceDetail")
}
instances := []SDBInstance{}
err = body.Unmarshal(&instances, "Items", "DBInstanceAttribute")
if err != nil {
return nil, errors.Wrapf(err, "GetDBInstanceDetail.Unmarshal")
}
if len(instances) == 1 {
instances[0].region = region
return &instances[0], nil
}
if len(instances) == 0 {
return nil, cloudprovider.ErrNotFound
}
return nil, cloudprovider.ErrDuplicateId
}
type SDBInstanceWeight struct {
}
type SDBInstanceWeights struct {
DBInstanceWeight []SDBInstanceWeight
}
type SsecurityIPGroup struct {
}
type SSecurityIPGroups struct {
securityIPGroup []SsecurityIPGroup
}
type SDBInstanceNetwork struct {
ConnectionString string
ConnectionStringType string
DBInstanceWeights SDBInstanceWeights
IPAddress string
IPType string
Port int
SecurityIPGroups SSecurityIPGroups
Upgradeable string
VPCId string
VSwitchId string
}
func (network *SDBInstanceNetwork) GetGlobalId() string {
return network.IPAddress
}
func (network *SDBInstanceNetwork) GetINetworkId() string {
return network.VSwitchId
}
func (network *SDBInstanceNetwork) GetIP() string {
return network.IPAddress
}
func (region *SRegion) GetDBInstanceNetInfo(instanceId string) ([]SDBInstanceNetwork, error) {
params := map[string]string{}
params["RegionId"] = region.RegionId
params["DBInstanceId"] = instanceId
body, err := region.rdsRequest("DescribeDBInstanceNetInfo", params)
if err != nil {
return nil, errors.Wrapf(err, "GetDBInstanceNetwork")
}
networks := []SDBInstanceNetwork{}
err = body.Unmarshal(&networks, "DBInstanceNetInfos", "DBInstanceNetInfo")
if err != nil {
return nil, err
}
return networks, nil
}
func (rds *SDBInstance) GetIDBInstanceParameters() ([]cloudprovider.ICloudDBInstanceParameter, error) {
parameters, err := rds.region.GetDBInstanceParameters(rds.DBInstanceId)
if err != nil {
return nil, err
}
iparameters := []cloudprovider.ICloudDBInstanceParameter{}
for i := 0; i < len(parameters); i++ {
iparameters = append(iparameters, &parameters[i])
}
return iparameters, nil
}
func (rds *SDBInstance) GetIDBInstanceBackups() ([]cloudprovider.ICloudDBInstanceBackup, error) {
backups := []SDBInstanceBackup{}
for {
parts, total, err := rds.region.GetDBInstanceBackups(rds.DBInstanceId, "", len(backups), 50)
if err != nil {
return nil, err
}
backups = append(backups, parts...)
if len(backups) >= total {
break
}
}
ibackups := []cloudprovider.ICloudDBInstanceBackup{}
for i := 0; i < len(backups); i++ {
ibackups = append(ibackups, &backups[i])
}
return ibackups, nil
}
func (rds *SDBInstance) GetIDBInstanceDatabases() ([]cloudprovider.ICloudDBInstanceDatabase, error) {
databases := []SDBInstanceDatabase{}
for {
parts, total, err := rds.region.GetDBInstanceDatabases(rds.DBInstanceId, "", len(databases), 500)
if err != nil {
return nil, err
}
databases = append(databases, parts...)
if len(databases) >= total {
break
}
}
idatabase := []cloudprovider.ICloudDBInstanceDatabase{}
for i := 0; i < len(databases); i++ {
idatabase = append(idatabase, &databases[i])
}
return idatabase, nil
}
func (rds *SDBInstance) GetIDBInstanceAccounts() ([]cloudprovider.ICloudDBInstanceAccount, error) {
accounts := []SDBInstanceAccount{}
for {
parts, total, err := rds.region.GetDBInstanceAccounts(rds.DBInstanceId, len(accounts), 50)
if err != nil {
return nil, err
}
accounts = append(accounts, parts...)
if len(accounts) >= total {
break
}
}
iaccounts := []cloudprovider.ICloudDBInstanceAccount{}
for i := 0; i < len(accounts); i++ {
iaccounts = append(iaccounts, &accounts[i])
}
return iaccounts, nil
}
+77
View File
@@ -0,0 +1,77 @@
package aliyun
import (
"fmt"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/multicloud"
"yunion.io/x/pkg/errors"
)
type SDatabasePrivilege struct {
AccountPrivilege string
AccountPrivilegeDetail string
DBName string
}
type SDatabasePrivileges struct {
DatabasePrivilege []SDatabasePrivilege
}
type SDBInstanceAccount struct {
multicloud.SDBInstanceAccountBase
AccountDescription string
AccountName string
AccountStatus string
AccountType string
DBInstanceId string
DatabasePrivileges SDatabasePrivileges
PrivExceeded string
}
func (account *SDBInstanceAccount) GetId() string {
return account.AccountName
}
func (account *SDBInstanceAccount) GetGlobalId() string {
return account.AccountName
}
func (account *SDBInstanceAccount) GetName() string {
return account.AccountName
}
func (account *SDBInstanceAccount) GetStatus() string {
switch account.AccountStatus {
case "Available":
return api.DBINSTANCE_USER_AVAILABLE
case "Unavailable":
return api.DBINSTANCE_USER_UNAVAILABLE
}
return account.AccountStatus
}
func (region *SRegion) GetDBInstanceAccounts(instanceId string, offset int, limit int) ([]SDBInstanceAccount, int, error) {
if limit > 50 || limit <= 0 {
limit = 50
}
params := map[string]string{
"RegionId": region.RegionId,
"PageSize": fmt.Sprintf("%d", limit),
"PageNumber": fmt.Sprintf("%d", (offset/limit)+1),
"DBInstanceId": instanceId,
}
body, err := region.rdsRequest("DescribeAccounts", params)
if err != nil {
return nil, 0, errors.Wrap(err, "DescribeAccounts")
}
accounts := []SDBInstanceAccount{}
err = body.Unmarshal(&accounts, "Accounts", "DBInstanceAccount")
if err != nil {
return nil, 0, errors.Wrap(err, "Unmarshal")
}
total, _ := body.Int("TotalRecordCount")
return accounts, int(total), nil
}
+119
View File
@@ -0,0 +1,119 @@
package aliyun
import (
"fmt"
"time"
"yunion.io/x/log"
"yunion.io/x/pkg/errors"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/multicloud"
)
type SDBInstanceBackup struct {
multicloud.SDBInstanceBackupBase
BackupDBNames string
BackupIntranetDownloadURL string
BackupDownloadURL string
BackupEndTime time.Time
BackupId string
BackupLocation string
BackupMethod string
BackupMode string
BackupScale string
BackupSize int
BackupStartTime time.Time
BackupStatus string
BackupType string
DBInstanceId string
HostInstanceID int
MetaStatus string
StoreStatus string
}
func (backup *SDBInstanceBackup) GetId() string {
return backup.BackupId
}
func (backup *SDBInstanceBackup) GetGlobalId() string {
return backup.BackupId
}
func (backup *SDBInstanceBackup) GetName() string {
return backup.BackupId
}
func (backup *SDBInstanceBackup) GetStartTime() time.Time {
return backup.BackupStartTime
}
func (backup *SDBInstanceBackup) GetEndTime() time.Time {
return backup.BackupEndTime
}
func (backup *SDBInstanceBackup) GetBackupType() string {
switch backup.BackupType {
case "FullBackup":
return api.BACKUP_TYPE_FULL_BACKUP
case "IncrementalBackup":
return api.BACKUP_TYPE_INCREMENTALBACKUP
default:
log.Errorf("Unknown backup type %s", backup.BackupType)
return api.BACKUP_TYPE_UNKNOWN
}
}
func (backup *SDBInstanceBackup) GetStatus() string {
switch backup.BackupStatus {
case "Success":
return api.DBINSTANCE_BACKUP_READY
case "Failed":
return api.DBINSTANCE_BACKUP_FAILED
default:
return api.DBINSTANCE_BACKUP_UNKNOWN
}
}
func (backup *SDBInstanceBackup) GetBackupSizeMb() int {
return backup.BackupSize / 1024 / 1024
}
func (backup *SDBInstanceBackup) GetDBNames() string {
return backup.BackupDBNames
}
func (backup *SDBInstanceBackup) GetDownloadURL() string {
return backup.BackupDownloadURL
}
func (backup *SDBInstanceBackup) GetIntranetDownloadURL() string {
return backup.BackupIntranetDownloadURL
}
func (region *SRegion) GetDBInstanceBackups(instanceId, backupId string, offset int, limit int) ([]SDBInstanceBackup, int, error) {
if limit > 50 || limit <= 0 {
limit = 50
}
params := map[string]string{
"RegionId": region.RegionId,
"PageSize": fmt.Sprintf("%d", limit),
"PageNumber": fmt.Sprintf("%d", (offset/limit)+1),
"DBInstanceId": instanceId,
}
if len(backupId) > 0 {
params["BackupId"] = backupId
}
body, err := region.rdsRequest("DescribeBackups", params)
if err != nil {
return nil, 0, errors.Wrap(err, "DescribeBackups")
}
backups := []SDBInstanceBackup{}
err = body.Unmarshal(&backups, "Items", "Backup")
if err != nil {
return nil, 0, errors.Wrap(err, "Unmarshal")
}
total, _ := body.Int("TotalRecordCount")
return backups, int(total), nil
}
+75
View File
@@ -0,0 +1,75 @@
package aliyun
import (
"fmt"
"yunion.io/x/pkg/errors"
api "yunion.io/x/onecloud/pkg/apis/compute"
"yunion.io/x/onecloud/pkg/multicloud"
)
type SDBInstanceDatabase struct {
multicloud.SDBInstanceDatabaseBase
CharacterSetName string
DBDescription string
DBInstanceId string
DBName string
DBStatus string
Engine string
}
func (database *SDBInstanceDatabase) GetId() string {
return database.DBName
}
func (database *SDBInstanceDatabase) GetGlobalId() string {
return database.DBName
}
func (database *SDBInstanceDatabase) GetName() string {
return database.DBName
}
func (database *SDBInstanceDatabase) GetStatus() string {
switch database.DBStatus {
case "Creating":
return api.DBINSTANCE_DATABASE_CREATING
case "Running":
return api.DBINSTANCE_DATABASE_RUNNING
case "Deleting":
return api.DBINSTANCE_DATABASE_DELETING
}
return database.DBStatus
}
func (database *SDBInstanceDatabase) GetCharacterSet() string {
return database.CharacterSetName
}
func (region *SRegion) GetDBInstanceDatabases(instanceId, dbName string, offset int, limit int) ([]SDBInstanceDatabase, int, error) {
if limit > 500 || limit <= 0 {
limit = 500
}
params := map[string]string{
"RegionId": region.RegionId,
"PageSize": fmt.Sprintf("%d", limit),
"PageNumber": fmt.Sprintf("%d", (offset/limit)+1),
"DBInstanceId": instanceId,
}
if len(dbName) > 0 {
params["DBName"] = dbName
}
body, err := region.rdsRequest("DescribeDatabases", params)
if err != nil {
return nil, 0, errors.Wrap(err, "DescribeDatabases")
}
databases := []SDBInstanceDatabase{}
err = body.Unmarshal(&databases, "Databases", "Database")
if err != nil {
return nil, 0, errors.Wrap(err, "Unmarshal")
}
total, _ := body.Int("TotalRecordCount")
return databases, int(total), nil
}
+52
View File
@@ -0,0 +1,52 @@
package aliyun
import (
"yunion.io/x/pkg/errors"
"yunion.io/x/pkg/utils"
)
type SDBInstanceParameter struct {
ParameterDescription string
ParameterValue string
ParameterName string
}
func (param *SDBInstanceParameter) GetGlobalId() string {
return param.ParameterName
}
func (param *SDBInstanceParameter) GetKey() string {
return param.ParameterName
}
func (param *SDBInstanceParameter) GetValue() string {
return param.ParameterValue
}
func (param *SDBInstanceParameter) GetDescription() string {
return param.ParameterDescription
}
func (region *SRegion) GetDBInstanceParameters(instanceId string) ([]SDBInstanceParameter, error) {
params := map[string]string{
"RegionId": region.RegionId,
"DBInstanceId": instanceId,
"ClientToken": utils.GenRequestId(20),
}
body, err := region.rdsRequest("DescribeParameters", params)
if err != nil {
return nil, errors.Wrapf(err, "DescribeParameters")
}
parameters1 := []SDBInstanceParameter{}
err = body.Unmarshal(&parameters1, "ConfigParameters", "DBInstanceParameter")
if err != nil {
return nil, errors.Wrap(err, "Unmarshal.ConfigParameters")
}
parameters2 := []SDBInstanceParameter{}
err = body.Unmarshal(&parameters1, "RunningParameters", "DBInstanceParameter")
if err != nil {
return nil, errors.Wrap(err, "Unmarshal.RunningParameters")
}
return append(parameters1, parameters2...), nil
}
+8
View File
@@ -111,6 +111,14 @@ func (self *SRegion) ecsRequest(apiName string, params map[string]string) (jsonu
return jsonRequest(client, "ecs.aliyuncs.com", ALIYUN_API_VERSION, apiName, params, self.client.Debug)
}
func (self *SRegion) rdsRequest(apiName string, params map[string]string) (jsonutils.JSONObject, error) {
client, err := self.getSdkClient()
if err != nil {
return nil, err
}
return jsonRequest(client, "rds.aliyuncs.com", ALIYUN_API_VERION_RDS, apiName, params, self.client.Debug)
}
func (self *SRegion) vpcRequest(action string, params map[string]string) (jsonutils.JSONObject, error) {
client, err := self.getSdkClient()
if err != nil {
+77
View File
@@ -0,0 +1,77 @@
package shell
import (
"yunion.io/x/onecloud/pkg/util/aliyun"
"yunion.io/x/onecloud/pkg/util/shellutils"
)
func init() {
type DBInstanceListOptions struct {
Id []string `help:"IDs of instances to show"`
Limit int `help:"page size"`
Offset int `help:"page offset"`
}
shellutils.R(&DBInstanceListOptions{}, "dbinstance-list", "List dbintances", func(cli *aliyun.SRegion, args *DBInstanceListOptions) error {
instances, total, e := cli.GetDBInstances(args.Id, args.Offset, args.Limit)
if e != nil {
return e
}
printList(instances, total, args.Offset, args.Limit, []string{})
return nil
})
type DBInstanceIdOptions struct {
ID string `help:"ID of instances to show"`
}
shellutils.R(&DBInstanceIdOptions{}, "dbinstance-show", "Show dbintance", func(cli *aliyun.SRegion, args *DBInstanceIdOptions) error {
instance, err := cli.GetDBInstanceDetail(args.ID)
if err != nil {
return err
}
printObject(instance)
return nil
})
shellutils.R(&DBInstanceIdOptions{}, "dbinstance-network-list", "Show dbintance network info", func(cli *aliyun.SRegion, args *DBInstanceIdOptions) error {
networks, err := cli.GetDBInstanceNetInfo(args.ID)
if err != nil {
return err
}
printList(networks, 0, 0, 0, []string{})
return nil
})
type DBInstanceIdExtraOptions struct {
ID string `help:"ID of instances to show"`
Limit int `help:"page size"`
Offset int `help:"page offset"`
}
shellutils.R(&DBInstanceIdExtraOptions{}, "dbinstance-backup-list", "List dbintance backups", func(cli *aliyun.SRegion, args *DBInstanceIdExtraOptions) error {
backups, _, err := cli.GetDBInstanceBackups(args.ID, "", args.Offset, args.Limit)
if err != nil {
return err
}
printList(backups, 0, 0, 0, []string{})
return nil
})
shellutils.R(&DBInstanceIdExtraOptions{}, "dbinstance-database-list", "List dbintance databases", func(cli *aliyun.SRegion, args *DBInstanceIdExtraOptions) error {
databases, _, err := cli.GetDBInstanceDatabases(args.ID, "", args.Offset, args.Limit)
if err != nil {
return err
}
printList(databases, 0, 0, 0, []string{})
return nil
})
shellutils.R(&DBInstanceIdExtraOptions{}, "dbinstance-account-list", "List dbintance account", func(cli *aliyun.SRegion, args *DBInstanceIdExtraOptions) error {
accounts, _, err := cli.GetDBInstanceAccounts(args.ID, args.Offset, args.Limit)
if err != nil {
return err
}
printList(accounts, 0, 0, 0, []string{})
return nil
})
}
+4 -3
View File
@@ -28,9 +28,10 @@ import (
type TChargeType string
const (
PrePaidInstanceChargeType TChargeType = "PrePaid"
PostPaidInstanceChargeType TChargeType = "PostPaid"
DefaultInstanceChargeType = PostPaidInstanceChargeType
PrePaidInstanceChargeType TChargeType = "PrePaid"
PostPaidInstanceChargeType TChargeType = "PostPaid"
PostPaidDBInstanceChargeType TChargeType = "Postpaid"
DefaultInstanceChargeType = PostPaidInstanceChargeType
)
type SpotStrategyType string
+2
View File
@@ -29,9 +29,11 @@ import (
"yunion.io/x/pkg/errors"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/multicloud/objectstore"
)
type SBucket struct {
objectstore.SBucket
region *SRegion
Name string
+16
View File
@@ -23,6 +23,7 @@ import (
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/ec2"
"github.com/aws/aws-sdk-go/service/iam"
"github.com/aws/aws-sdk-go/service/rds"
"github.com/aws/aws-sdk-go/service/s3"
"yunion.io/x/jsonutils"
@@ -63,6 +64,7 @@ type SRegion struct {
ec2Client *ec2.EC2
iamClient *iam.IAM
s3Client *s3.S3
rdsClient *rds.RDS
izones []cloudprovider.ICloudZone
ivpcs []cloudprovider.ICloudVpc
@@ -116,6 +118,20 @@ func (self *SRegion) getIamClient() (*iam.IAM, error) {
return self.iamClient, nil
}
func (self *SRegion) getRdsClient() (*rds.RDS, error) {
if self.rdsClient == nil {
s, err := self.getAwsSession()
if err != nil {
return nil, err
}
self.rdsClient = rds.New(s)
}
return self.rdsClient, nil
}
func (self *SRegion) GetS3Client() (*s3.S3, error) {
if self.s3Client == nil {
s, err := self.getAwsSession()
+3
View File
@@ -23,6 +23,8 @@ import (
"strings"
"time"
"yunion.io/x/onecloud/pkg/multicloud/objectstore"
"github.com/Azure/azure-sdk-for-go/storage"
"github.com/Microsoft/azure-vhd-utils/vhdcore/common"
"github.com/Microsoft/azure-vhd-utils/vhdcore/diskstream"
@@ -77,6 +79,7 @@ type AccountProperties struct {
}
type SStorageAccount struct {
objectstore.SBucket
region *SRegion
accountKey string
+4
View File
@@ -18,15 +18,19 @@ import (
"fmt"
"time"
"yunion.io/x/onecloud/pkg/multicloud/objectstore"
"yunion.io/x/pkg/errors"
"context"
"io"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/util/huawei/obs"
)
type SBucket struct {
objectstore.SBucket
region *SRegion
Name string
+3
View File
@@ -20,6 +20,8 @@ import (
"io"
"time"
"yunion.io/x/onecloud/pkg/multicloud/objectstore"
"github.com/tencentyun/cos-go-sdk-v5"
"yunion.io/x/pkg/errors"
@@ -29,6 +31,7 @@ import (
)
type SBucket struct {
objectstore.SBucket
region *SRegion
Name string
+4
View File
@@ -25,14 +25,18 @@ import (
"strconv"
"time"
"yunion.io/x/onecloud/pkg/multicloud/objectstore"
"yunion.io/x/log"
"context"
"yunion.io/x/onecloud/pkg/cloudprovider"
"yunion.io/x/onecloud/pkg/util/httputils"
)
type SBucket struct {
objectstore.SBucket
region *SRegion
projectId string
File diff suppressed because it is too large Load Diff
+125
View File
@@ -0,0 +1,125 @@
package rds
import (
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awsutil"
"github.com/aws/aws-sdk-go/aws/endpoints"
"github.com/aws/aws-sdk-go/aws/request"
)
func init() {
ops := []string{
opCopyDBSnapshot,
opCreateDBInstanceReadReplica,
opCopyDBClusterSnapshot,
opCreateDBCluster,
}
initRequest = func(r *request.Request) {
for _, operation := range ops {
if r.Operation.Name == operation {
r.Handlers.Build.PushFront(fillPresignedURL)
}
}
}
}
func fillPresignedURL(r *request.Request) {
fns := map[string]func(r *request.Request){
opCopyDBSnapshot: copyDBSnapshotPresign,
opCreateDBInstanceReadReplica: createDBInstanceReadReplicaPresign,
opCopyDBClusterSnapshot: copyDBClusterSnapshotPresign,
opCreateDBCluster: createDBClusterPresign,
}
if !r.ParamsFilled() {
return
}
if f, ok := fns[r.Operation.Name]; ok {
f(r)
}
}
func copyDBSnapshotPresign(r *request.Request) {
originParams := r.Params.(*CopyDBSnapshotInput)
if originParams.SourceRegion == nil || originParams.PreSignedUrl != nil || originParams.DestinationRegion != nil {
return
}
originParams.DestinationRegion = r.Config.Region
newParams := awsutil.CopyOf(r.Params).(*CopyDBSnapshotInput)
originParams.PreSignedUrl = presignURL(r, originParams.SourceRegion, newParams)
}
func createDBInstanceReadReplicaPresign(r *request.Request) {
originParams := r.Params.(*CreateDBInstanceReadReplicaInput)
if originParams.SourceRegion == nil || originParams.PreSignedUrl != nil || originParams.DestinationRegion != nil {
return
}
originParams.DestinationRegion = r.Config.Region
newParams := awsutil.CopyOf(r.Params).(*CreateDBInstanceReadReplicaInput)
originParams.PreSignedUrl = presignURL(r, originParams.SourceRegion, newParams)
}
func copyDBClusterSnapshotPresign(r *request.Request) {
originParams := r.Params.(*CopyDBClusterSnapshotInput)
if originParams.SourceRegion == nil || originParams.PreSignedUrl != nil || originParams.DestinationRegion != nil {
return
}
originParams.DestinationRegion = r.Config.Region
newParams := awsutil.CopyOf(r.Params).(*CopyDBClusterSnapshotInput)
originParams.PreSignedUrl = presignURL(r, originParams.SourceRegion, newParams)
}
func createDBClusterPresign(r *request.Request) {
originParams := r.Params.(*CreateDBClusterInput)
if originParams.SourceRegion == nil || originParams.PreSignedUrl != nil || originParams.DestinationRegion != nil {
return
}
originParams.DestinationRegion = r.Config.Region
newParams := awsutil.CopyOf(r.Params).(*CreateDBClusterInput)
originParams.PreSignedUrl = presignURL(r, originParams.SourceRegion, newParams)
}
// presignURL will presign the request by using SoureRegion to sign with. SourceRegion is not
// sent to the service, and is only used to not have the SDKs parsing ARNs.
func presignURL(r *request.Request, sourceRegion *string, newParams interface{}) *string {
cfg := r.Config.Copy(aws.NewConfig().
WithEndpoint("").
WithRegion(aws.StringValue(sourceRegion)))
clientInfo := r.ClientInfo
resolved, err := r.Config.EndpointResolver.EndpointFor(
clientInfo.ServiceName, aws.StringValue(cfg.Region),
func(opt *endpoints.Options) {
opt.DisableSSL = aws.BoolValue(cfg.DisableSSL)
opt.UseDualStack = aws.BoolValue(cfg.UseDualStack)
},
)
if err != nil {
r.Error = err
return nil
}
clientInfo.Endpoint = resolved.URL
clientInfo.SigningRegion = resolved.SigningRegion
// Presign a request with modified params
req := request.New(*cfg, clientInfo, r.Handlers, r.Retryer, r.Operation, newParams, r.Data)
req.Operation.HTTPMethod = "GET"
uri, err := req.Presign(5 * time.Minute) // 5 minutes should be enough.
if err != nil { // bubble error back up to original request
r.Error = err
return nil
}
// We have our URL, set it on params
return &uri
}
+69
View File
@@ -0,0 +1,69 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
// Package rds provides the client and types for making API
// requests to Amazon Relational Database Service.
//
// Amazon Relational Database Service (Amazon RDS) is a web service that makes
// it easier to set up, operate, and scale a relational database in the cloud.
// It provides cost-efficient, resizable capacity for an industry-standard relational
// database and manages common database administration tasks, freeing up developers
// to focus on what makes their applications and businesses unique.
//
// Amazon RDS gives you access to the capabilities of a MySQL, MariaDB, PostgreSQL,
// Microsoft SQL Server, Oracle, or Amazon Aurora database server. These capabilities
// mean that the code, applications, and tools you already use today with your
// existing databases work with Amazon RDS without modification. Amazon RDS
// automatically backs up your database and maintains the database software
// that powers your DB instance. Amazon RDS is flexible: you can scale your
// DB instance's compute resources and storage capacity to meet your application's
// demand. As with all Amazon Web Services, there are no up-front investments,
// and you pay only for the resources you use.
//
// This interface reference for Amazon RDS contains documentation for a programming
// or command line interface you can use to manage Amazon RDS. Note that Amazon
// RDS is asynchronous, which means that some interfaces might require techniques
// such as polling or callback functions to determine when a command has been
// applied. In this reference, the parameter descriptions indicate whether a
// command is applied immediately, on the next instance reboot, or during the
// maintenance window. The reference structure is as follows, and we list following
// some related topics from the user guide.
//
// Amazon RDS API Reference
//
// * For the alphabetical list of API actions, see API Actions (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Operations.html).
//
// * For the alphabetical list of data types, see Data Types (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/API_Types.html).
//
// * For a list of common query parameters, see Common Parameters (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonParameters.html).
//
// * For descriptions of the error codes, see Common Errors (http://docs.aws.amazon.com/AmazonRDS/latest/APIReference/CommonErrors.html).
//
// Amazon RDS User Guide
//
// * For a summary of the Amazon RDS interfaces, see Available RDS Interfaces
// (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Welcome.html#Welcome.Interfaces).
//
// * For more information about how to use the Query API, see Using the Query
// API (http://docs.aws.amazon.com/AmazonRDS/latest/UserGuide/Using_the_Query_API.html).
//
// See https://docs.aws.amazon.com/goto/WebAPI/rds-2014-10-31 for more information on this service.
//
// See rds package documentation for more information.
// https://docs.aws.amazon.com/sdk-for-go/api/service/rds/
//
// Using the Client
//
// To contact Amazon Relational Database Service with the SDK use the New function to create
// a new service client. With that client you can make API requests to the service.
// These clients are safe to use concurrently.
//
// See the SDK's documentation for more information on how to use the SDK.
// https://docs.aws.amazon.com/sdk-for-go/api/
//
// See aws.Config documentation for more information on configuring SDK clients.
// https://docs.aws.amazon.com/sdk-for-go/api/aws/#Config
//
// See the Amazon Relational Database Service client RDS for more
// information on creating client for this service.
// https://docs.aws.amazon.com/sdk-for-go/api/service/rds/#New
package rds
+25
View File
@@ -0,0 +1,25 @@
// IAM User or Role Database Authentication
//
// The rdsutil package's BuildAuthToken function provides a connection
// authentication token builder. Given an endpoint of the RDS database,
// AWS region, DB user, and AWS credentials the function will create an
// presigned URL to use as the authentication token for the database's
// connection.
//
// The following example shows how to use BuildAuthToken to create an authentication
// token for connecting to a MySQL database in RDS.
//
// authToken, err := rdsutils.BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds)
//
// // Create the MySQL DNS string for the DB connection
// // user:password@protocol(endpoint)/dbname?<params>
// dnsStr = fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true",
// dbUser, authToken, dbEndpoint, dbName,
// )
//
// // Use db to perform SQL operations on database
// db, err := sql.Open("mysql", dnsStr)
//
// See rdsutil package for more information.
// http://docs.aws.amazon.com/sdk-for-go/api/service/rds/rdsutils/
package rds
+510
View File
@@ -0,0 +1,510 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rds
const (
// ErrCodeAuthorizationAlreadyExistsFault for service response error code
// "AuthorizationAlreadyExists".
//
// The specified CIDRIP or Amazon EC2 security group is already authorized for
// the specified DB security group.
ErrCodeAuthorizationAlreadyExistsFault = "AuthorizationAlreadyExists"
// ErrCodeAuthorizationNotFoundFault for service response error code
// "AuthorizationNotFound".
//
// The specified CIDRIP or Amazon EC2 security group isn't authorized for the
// specified DB security group.
//
// RDS also may not be authorized by using IAM to perform necessary actions
// on your behalf.
ErrCodeAuthorizationNotFoundFault = "AuthorizationNotFound"
// ErrCodeAuthorizationQuotaExceededFault for service response error code
// "AuthorizationQuotaExceeded".
//
// The DB security group authorization quota has been reached.
ErrCodeAuthorizationQuotaExceededFault = "AuthorizationQuotaExceeded"
// ErrCodeBackupPolicyNotFoundFault for service response error code
// "BackupPolicyNotFoundFault".
ErrCodeBackupPolicyNotFoundFault = "BackupPolicyNotFoundFault"
// ErrCodeCertificateNotFoundFault for service response error code
// "CertificateNotFound".
//
// CertificateIdentifier doesn't refer to an existing certificate.
ErrCodeCertificateNotFoundFault = "CertificateNotFound"
// ErrCodeDBClusterAlreadyExistsFault for service response error code
// "DBClusterAlreadyExistsFault".
//
// The user already has a DB cluster with the given identifier.
ErrCodeDBClusterAlreadyExistsFault = "DBClusterAlreadyExistsFault"
// ErrCodeDBClusterBacktrackNotFoundFault for service response error code
// "DBClusterBacktrackNotFoundFault".
//
// BacktrackIdentifier doesn't refer to an existing backtrack.
ErrCodeDBClusterBacktrackNotFoundFault = "DBClusterBacktrackNotFoundFault"
// ErrCodeDBClusterNotFoundFault for service response error code
// "DBClusterNotFoundFault".
//
// DBClusterIdentifier doesn't refer to an existing DB cluster.
ErrCodeDBClusterNotFoundFault = "DBClusterNotFoundFault"
// ErrCodeDBClusterParameterGroupNotFoundFault for service response error code
// "DBClusterParameterGroupNotFound".
//
// DBClusterParameterGroupName doesn't refer to an existing DB cluster parameter
// group.
ErrCodeDBClusterParameterGroupNotFoundFault = "DBClusterParameterGroupNotFound"
// ErrCodeDBClusterQuotaExceededFault for service response error code
// "DBClusterQuotaExceededFault".
//
// The user attempted to create a new DB cluster and the user has already reached
// the maximum allowed DB cluster quota.
ErrCodeDBClusterQuotaExceededFault = "DBClusterQuotaExceededFault"
// ErrCodeDBClusterRoleAlreadyExistsFault for service response error code
// "DBClusterRoleAlreadyExists".
//
// The specified IAM role Amazon Resource Name (ARN) is already associated with
// the specified DB cluster.
ErrCodeDBClusterRoleAlreadyExistsFault = "DBClusterRoleAlreadyExists"
// ErrCodeDBClusterRoleNotFoundFault for service response error code
// "DBClusterRoleNotFound".
//
// The specified IAM role Amazon Resource Name (ARN) isn't associated with the
// specified DB cluster.
ErrCodeDBClusterRoleNotFoundFault = "DBClusterRoleNotFound"
// ErrCodeDBClusterRoleQuotaExceededFault for service response error code
// "DBClusterRoleQuotaExceeded".
//
// You have exceeded the maximum number of IAM roles that can be associated
// with the specified DB cluster.
ErrCodeDBClusterRoleQuotaExceededFault = "DBClusterRoleQuotaExceeded"
// ErrCodeDBClusterSnapshotAlreadyExistsFault for service response error code
// "DBClusterSnapshotAlreadyExistsFault".
//
// The user already has a DB cluster snapshot with the given identifier.
ErrCodeDBClusterSnapshotAlreadyExistsFault = "DBClusterSnapshotAlreadyExistsFault"
// ErrCodeDBClusterSnapshotNotFoundFault for service response error code
// "DBClusterSnapshotNotFoundFault".
//
// DBClusterSnapshotIdentifier doesn't refer to an existing DB cluster snapshot.
ErrCodeDBClusterSnapshotNotFoundFault = "DBClusterSnapshotNotFoundFault"
// ErrCodeDBInstanceAlreadyExistsFault for service response error code
// "DBInstanceAlreadyExists".
//
// The user already has a DB instance with the given identifier.
ErrCodeDBInstanceAlreadyExistsFault = "DBInstanceAlreadyExists"
// ErrCodeDBInstanceNotFoundFault for service response error code
// "DBInstanceNotFound".
//
// DBInstanceIdentifier doesn't refer to an existing DB instance.
ErrCodeDBInstanceNotFoundFault = "DBInstanceNotFound"
// ErrCodeDBLogFileNotFoundFault for service response error code
// "DBLogFileNotFoundFault".
//
// LogFileName doesn't refer to an existing DB log file.
ErrCodeDBLogFileNotFoundFault = "DBLogFileNotFoundFault"
// ErrCodeDBParameterGroupAlreadyExistsFault for service response error code
// "DBParameterGroupAlreadyExists".
//
// A DB parameter group with the same name exists.
ErrCodeDBParameterGroupAlreadyExistsFault = "DBParameterGroupAlreadyExists"
// ErrCodeDBParameterGroupNotFoundFault for service response error code
// "DBParameterGroupNotFound".
//
// DBParameterGroupName doesn't refer to an existing DB parameter group.
ErrCodeDBParameterGroupNotFoundFault = "DBParameterGroupNotFound"
// ErrCodeDBParameterGroupQuotaExceededFault for service response error code
// "DBParameterGroupQuotaExceeded".
//
// The request would result in the user exceeding the allowed number of DB parameter
// groups.
ErrCodeDBParameterGroupQuotaExceededFault = "DBParameterGroupQuotaExceeded"
// ErrCodeDBSecurityGroupAlreadyExistsFault for service response error code
// "DBSecurityGroupAlreadyExists".
//
// A DB security group with the name specified in DBSecurityGroupName already
// exists.
ErrCodeDBSecurityGroupAlreadyExistsFault = "DBSecurityGroupAlreadyExists"
// ErrCodeDBSecurityGroupNotFoundFault for service response error code
// "DBSecurityGroupNotFound".
//
// DBSecurityGroupName doesn't refer to an existing DB security group.
ErrCodeDBSecurityGroupNotFoundFault = "DBSecurityGroupNotFound"
// ErrCodeDBSecurityGroupNotSupportedFault for service response error code
// "DBSecurityGroupNotSupported".
//
// A DB security group isn't allowed for this action.
ErrCodeDBSecurityGroupNotSupportedFault = "DBSecurityGroupNotSupported"
// ErrCodeDBSecurityGroupQuotaExceededFault for service response error code
// "QuotaExceeded.DBSecurityGroup".
//
// The request would result in the user exceeding the allowed number of DB security
// groups.
ErrCodeDBSecurityGroupQuotaExceededFault = "QuotaExceeded.DBSecurityGroup"
// ErrCodeDBSnapshotAlreadyExistsFault for service response error code
// "DBSnapshotAlreadyExists".
//
// DBSnapshotIdentifier is already used by an existing snapshot.
ErrCodeDBSnapshotAlreadyExistsFault = "DBSnapshotAlreadyExists"
// ErrCodeDBSnapshotNotFoundFault for service response error code
// "DBSnapshotNotFound".
//
// DBSnapshotIdentifier doesn't refer to an existing DB snapshot.
ErrCodeDBSnapshotNotFoundFault = "DBSnapshotNotFound"
// ErrCodeDBSubnetGroupAlreadyExistsFault for service response error code
// "DBSubnetGroupAlreadyExists".
//
// DBSubnetGroupName is already used by an existing DB subnet group.
ErrCodeDBSubnetGroupAlreadyExistsFault = "DBSubnetGroupAlreadyExists"
// ErrCodeDBSubnetGroupDoesNotCoverEnoughAZs for service response error code
// "DBSubnetGroupDoesNotCoverEnoughAZs".
//
// Subnets in the DB subnet group should cover at least two Availability Zones
// unless there is only one Availability Zone.
ErrCodeDBSubnetGroupDoesNotCoverEnoughAZs = "DBSubnetGroupDoesNotCoverEnoughAZs"
// ErrCodeDBSubnetGroupNotAllowedFault for service response error code
// "DBSubnetGroupNotAllowedFault".
//
// The DBSubnetGroup shouldn't be specified while creating read replicas that
// lie in the same region as the source instance.
ErrCodeDBSubnetGroupNotAllowedFault = "DBSubnetGroupNotAllowedFault"
// ErrCodeDBSubnetGroupNotFoundFault for service response error code
// "DBSubnetGroupNotFoundFault".
//
// DBSubnetGroupName doesn't refer to an existing DB subnet group.
ErrCodeDBSubnetGroupNotFoundFault = "DBSubnetGroupNotFoundFault"
// ErrCodeDBSubnetGroupQuotaExceededFault for service response error code
// "DBSubnetGroupQuotaExceeded".
//
// The request would result in the user exceeding the allowed number of DB subnet
// groups.
ErrCodeDBSubnetGroupQuotaExceededFault = "DBSubnetGroupQuotaExceeded"
// ErrCodeDBSubnetQuotaExceededFault for service response error code
// "DBSubnetQuotaExceededFault".
//
// The request would result in the user exceeding the allowed number of subnets
// in a DB subnet groups.
ErrCodeDBSubnetQuotaExceededFault = "DBSubnetQuotaExceededFault"
// ErrCodeDBUpgradeDependencyFailureFault for service response error code
// "DBUpgradeDependencyFailure".
//
// The DB upgrade failed because a resource the DB depends on can't be modified.
ErrCodeDBUpgradeDependencyFailureFault = "DBUpgradeDependencyFailure"
// ErrCodeDomainNotFoundFault for service response error code
// "DomainNotFoundFault".
//
// Domain doesn't refer to an existing Active Directory domain.
ErrCodeDomainNotFoundFault = "DomainNotFoundFault"
// ErrCodeEventSubscriptionQuotaExceededFault for service response error code
// "EventSubscriptionQuotaExceeded".
//
// You have reached the maximum number of event subscriptions.
ErrCodeEventSubscriptionQuotaExceededFault = "EventSubscriptionQuotaExceeded"
// ErrCodeInstanceQuotaExceededFault for service response error code
// "InstanceQuotaExceeded".
//
// The request would result in the user exceeding the allowed number of DB instances.
ErrCodeInstanceQuotaExceededFault = "InstanceQuotaExceeded"
// ErrCodeInsufficientDBClusterCapacityFault for service response error code
// "InsufficientDBClusterCapacityFault".
//
// The DB cluster doesn't have enough capacity for the current operation.
ErrCodeInsufficientDBClusterCapacityFault = "InsufficientDBClusterCapacityFault"
// ErrCodeInsufficientDBInstanceCapacityFault for service response error code
// "InsufficientDBInstanceCapacity".
//
// The specified DB instance class isn't available in the specified Availability
// Zone.
ErrCodeInsufficientDBInstanceCapacityFault = "InsufficientDBInstanceCapacity"
// ErrCodeInsufficientStorageClusterCapacityFault for service response error code
// "InsufficientStorageClusterCapacity".
//
// There is insufficient storage available for the current action. You might
// be able to resolve this error by updating your subnet group to use different
// Availability Zones that have more storage available.
ErrCodeInsufficientStorageClusterCapacityFault = "InsufficientStorageClusterCapacity"
// ErrCodeInvalidDBClusterCapacityFault for service response error code
// "InvalidDBClusterCapacityFault".
//
// Capacity isn't a valid Aurora Serverless DB cluster capacity. Valid capacity
// values are 2, 4, 8, 16, 32, 64, 128, and 256.
ErrCodeInvalidDBClusterCapacityFault = "InvalidDBClusterCapacityFault"
// ErrCodeInvalidDBClusterSnapshotStateFault for service response error code
// "InvalidDBClusterSnapshotStateFault".
//
// The supplied value isn't a valid DB cluster snapshot state.
ErrCodeInvalidDBClusterSnapshotStateFault = "InvalidDBClusterSnapshotStateFault"
// ErrCodeInvalidDBClusterStateFault for service response error code
// "InvalidDBClusterStateFault".
//
// The DB cluster isn't in a valid state.
ErrCodeInvalidDBClusterStateFault = "InvalidDBClusterStateFault"
// ErrCodeInvalidDBInstanceStateFault for service response error code
// "InvalidDBInstanceState".
//
// The DB instance isn't in a valid state.
ErrCodeInvalidDBInstanceStateFault = "InvalidDBInstanceState"
// ErrCodeInvalidDBParameterGroupStateFault for service response error code
// "InvalidDBParameterGroupState".
//
// The DB parameter group is in use or is in an invalid state. If you are attempting
// to delete the parameter group, you can't delete it when the parameter group
// is in this state.
ErrCodeInvalidDBParameterGroupStateFault = "InvalidDBParameterGroupState"
// ErrCodeInvalidDBSecurityGroupStateFault for service response error code
// "InvalidDBSecurityGroupState".
//
// The state of the DB security group doesn't allow deletion.
ErrCodeInvalidDBSecurityGroupStateFault = "InvalidDBSecurityGroupState"
// ErrCodeInvalidDBSnapshotStateFault for service response error code
// "InvalidDBSnapshotState".
//
// The state of the DB snapshot doesn't allow deletion.
ErrCodeInvalidDBSnapshotStateFault = "InvalidDBSnapshotState"
// ErrCodeInvalidDBSubnetGroupFault for service response error code
// "InvalidDBSubnetGroupFault".
//
// The DBSubnetGroup doesn't belong to the same VPC as that of an existing cross-region
// read replica of the same source instance.
ErrCodeInvalidDBSubnetGroupFault = "InvalidDBSubnetGroupFault"
// ErrCodeInvalidDBSubnetGroupStateFault for service response error code
// "InvalidDBSubnetGroupStateFault".
//
// The DB subnet group cannot be deleted because it's in use.
ErrCodeInvalidDBSubnetGroupStateFault = "InvalidDBSubnetGroupStateFault"
// ErrCodeInvalidDBSubnetStateFault for service response error code
// "InvalidDBSubnetStateFault".
//
// The DB subnet isn't in the available state.
ErrCodeInvalidDBSubnetStateFault = "InvalidDBSubnetStateFault"
// ErrCodeInvalidEventSubscriptionStateFault for service response error code
// "InvalidEventSubscriptionState".
//
// This error can occur if someone else is modifying a subscription. You should
// retry the action.
ErrCodeInvalidEventSubscriptionStateFault = "InvalidEventSubscriptionState"
// ErrCodeInvalidOptionGroupStateFault for service response error code
// "InvalidOptionGroupStateFault".
//
// The option group isn't in the available state.
ErrCodeInvalidOptionGroupStateFault = "InvalidOptionGroupStateFault"
// ErrCodeInvalidRestoreFault for service response error code
// "InvalidRestoreFault".
//
// Cannot restore from VPC backup to non-VPC DB instance.
ErrCodeInvalidRestoreFault = "InvalidRestoreFault"
// ErrCodeInvalidS3BucketFault for service response error code
// "InvalidS3BucketFault".
//
// The specified Amazon S3 bucket name can't be found or Amazon RDS isn't authorized
// to access the specified Amazon S3 bucket. Verify the SourceS3BucketName and
// S3IngestionRoleArn values and try again.
ErrCodeInvalidS3BucketFault = "InvalidS3BucketFault"
// ErrCodeInvalidSubnet for service response error code
// "InvalidSubnet".
//
// The requested subnet is invalid, or multiple subnets were requested that
// are not all in a common VPC.
ErrCodeInvalidSubnet = "InvalidSubnet"
// ErrCodeInvalidVPCNetworkStateFault for service response error code
// "InvalidVPCNetworkStateFault".
//
// The DB subnet group doesn't cover all Availability Zones after it's created
// because of users' change.
ErrCodeInvalidVPCNetworkStateFault = "InvalidVPCNetworkStateFault"
// ErrCodeKMSKeyNotAccessibleFault for service response error code
// "KMSKeyNotAccessibleFault".
//
// An error occurred accessing an AWS KMS key.
ErrCodeKMSKeyNotAccessibleFault = "KMSKeyNotAccessibleFault"
// ErrCodeOptionGroupAlreadyExistsFault for service response error code
// "OptionGroupAlreadyExistsFault".
//
// The option group you are trying to create already exists.
ErrCodeOptionGroupAlreadyExistsFault = "OptionGroupAlreadyExistsFault"
// ErrCodeOptionGroupNotFoundFault for service response error code
// "OptionGroupNotFoundFault".
//
// The specified option group could not be found.
ErrCodeOptionGroupNotFoundFault = "OptionGroupNotFoundFault"
// ErrCodeOptionGroupQuotaExceededFault for service response error code
// "OptionGroupQuotaExceededFault".
//
// The quota of 20 option groups was exceeded for this AWS account.
ErrCodeOptionGroupQuotaExceededFault = "OptionGroupQuotaExceededFault"
// ErrCodePointInTimeRestoreNotEnabledFault for service response error code
// "PointInTimeRestoreNotEnabled".
//
// SourceDBInstanceIdentifier refers to a DB instance with BackupRetentionPeriod
// equal to 0.
ErrCodePointInTimeRestoreNotEnabledFault = "PointInTimeRestoreNotEnabled"
// ErrCodeProvisionedIopsNotAvailableInAZFault for service response error code
// "ProvisionedIopsNotAvailableInAZFault".
//
// Provisioned IOPS not available in the specified Availability Zone.
ErrCodeProvisionedIopsNotAvailableInAZFault = "ProvisionedIopsNotAvailableInAZFault"
// ErrCodeReservedDBInstanceAlreadyExistsFault for service response error code
// "ReservedDBInstanceAlreadyExists".
//
// User already has a reservation with the given identifier.
ErrCodeReservedDBInstanceAlreadyExistsFault = "ReservedDBInstanceAlreadyExists"
// ErrCodeReservedDBInstanceNotFoundFault for service response error code
// "ReservedDBInstanceNotFound".
//
// The specified reserved DB Instance not found.
ErrCodeReservedDBInstanceNotFoundFault = "ReservedDBInstanceNotFound"
// ErrCodeReservedDBInstanceQuotaExceededFault for service response error code
// "ReservedDBInstanceQuotaExceeded".
//
// Request would exceed the user's DB Instance quota.
ErrCodeReservedDBInstanceQuotaExceededFault = "ReservedDBInstanceQuotaExceeded"
// ErrCodeReservedDBInstancesOfferingNotFoundFault for service response error code
// "ReservedDBInstancesOfferingNotFound".
//
// Specified offering does not exist.
ErrCodeReservedDBInstancesOfferingNotFoundFault = "ReservedDBInstancesOfferingNotFound"
// ErrCodeResourceNotFoundFault for service response error code
// "ResourceNotFoundFault".
//
// The specified resource ID was not found.
ErrCodeResourceNotFoundFault = "ResourceNotFoundFault"
// ErrCodeSNSInvalidTopicFault for service response error code
// "SNSInvalidTopic".
//
// SNS has responded that there is a problem with the SND topic specified.
ErrCodeSNSInvalidTopicFault = "SNSInvalidTopic"
// ErrCodeSNSNoAuthorizationFault for service response error code
// "SNSNoAuthorization".
//
// You do not have permission to publish to the SNS topic ARN.
ErrCodeSNSNoAuthorizationFault = "SNSNoAuthorization"
// ErrCodeSNSTopicArnNotFoundFault for service response error code
// "SNSTopicArnNotFound".
//
// The SNS topic ARN does not exist.
ErrCodeSNSTopicArnNotFoundFault = "SNSTopicArnNotFound"
// ErrCodeSharedSnapshotQuotaExceededFault for service response error code
// "SharedSnapshotQuotaExceeded".
//
// You have exceeded the maximum number of accounts that you can share a manual
// DB snapshot with.
ErrCodeSharedSnapshotQuotaExceededFault = "SharedSnapshotQuotaExceeded"
// ErrCodeSnapshotQuotaExceededFault for service response error code
// "SnapshotQuotaExceeded".
//
// The request would result in the user exceeding the allowed number of DB snapshots.
ErrCodeSnapshotQuotaExceededFault = "SnapshotQuotaExceeded"
// ErrCodeSourceNotFoundFault for service response error code
// "SourceNotFound".
//
// The requested source could not be found.
ErrCodeSourceNotFoundFault = "SourceNotFound"
// ErrCodeStorageQuotaExceededFault for service response error code
// "StorageQuotaExceeded".
//
// The request would result in the user exceeding the allowed amount of storage
// available across all DB instances.
ErrCodeStorageQuotaExceededFault = "StorageQuotaExceeded"
// ErrCodeStorageTypeNotSupportedFault for service response error code
// "StorageTypeNotSupported".
//
// Storage of the StorageType specified can't be associated with the DB instance.
ErrCodeStorageTypeNotSupportedFault = "StorageTypeNotSupported"
// ErrCodeSubnetAlreadyInUse for service response error code
// "SubnetAlreadyInUse".
//
// The DB subnet is already in use in the Availability Zone.
ErrCodeSubnetAlreadyInUse = "SubnetAlreadyInUse"
// ErrCodeSubscriptionAlreadyExistFault for service response error code
// "SubscriptionAlreadyExist".
//
// The supplied subscription name already exists.
ErrCodeSubscriptionAlreadyExistFault = "SubscriptionAlreadyExist"
// ErrCodeSubscriptionCategoryNotFoundFault for service response error code
// "SubscriptionCategoryNotFound".
//
// The supplied category does not exist.
ErrCodeSubscriptionCategoryNotFoundFault = "SubscriptionCategoryNotFound"
// ErrCodeSubscriptionNotFoundFault for service response error code
// "SubscriptionNotFound".
//
// The subscription name does not exist.
ErrCodeSubscriptionNotFoundFault = "SubscriptionNotFound"
)
+95
View File
@@ -0,0 +1,95 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rds
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/client"
"github.com/aws/aws-sdk-go/aws/client/metadata"
"github.com/aws/aws-sdk-go/aws/request"
"github.com/aws/aws-sdk-go/aws/signer/v4"
"github.com/aws/aws-sdk-go/private/protocol/query"
)
// RDS provides the API operation methods for making requests to
// Amazon Relational Database Service. See this package's package overview docs
// for details on the service.
//
// RDS methods are safe to use concurrently. It is not safe to
// modify mutate any of the struct's properties though.
type RDS struct {
*client.Client
}
// Used for custom client initialization logic
var initClient func(*client.Client)
// Used for custom request initialization logic
var initRequest func(*request.Request)
// Service information constants
const (
ServiceName = "rds" // Name of service.
EndpointsID = ServiceName // ID to lookup a service endpoint with.
ServiceID = "RDS" // ServiceID is a unique identifer of a specific service.
)
// New creates a new instance of the RDS client with a session.
// If additional configuration is needed for the client instance use the optional
// aws.Config parameter to add your extra config.
//
// Example:
// // Create a RDS client from just a session.
// svc := rds.New(mySession)
//
// // Create a RDS client with additional configuration
// svc := rds.New(mySession, aws.NewConfig().WithRegion("us-west-2"))
func New(p client.ConfigProvider, cfgs ...*aws.Config) *RDS {
c := p.ClientConfig(EndpointsID, cfgs...)
return newClient(*c.Config, c.Handlers, c.Endpoint, c.SigningRegion, c.SigningName)
}
// newClient creates, initializes and returns a new service client instance.
func newClient(cfg aws.Config, handlers request.Handlers, endpoint, signingRegion, signingName string) *RDS {
svc := &RDS{
Client: client.New(
cfg,
metadata.ClientInfo{
ServiceName: ServiceName,
ServiceID: ServiceID,
SigningName: signingName,
SigningRegion: signingRegion,
Endpoint: endpoint,
APIVersion: "2014-10-31",
},
handlers,
),
}
// Handlers
svc.Handlers.Sign.PushBackNamed(v4.SignRequestHandler)
svc.Handlers.Build.PushBackNamed(query.BuildHandler)
svc.Handlers.Unmarshal.PushBackNamed(query.UnmarshalHandler)
svc.Handlers.UnmarshalMeta.PushBackNamed(query.UnmarshalMetaHandler)
svc.Handlers.UnmarshalError.PushBackNamed(query.UnmarshalErrorHandler)
// Run custom client initialization if present
if initClient != nil {
initClient(svc.Client)
}
return svc
}
// newRequest creates a new request for a RDS operation and runs any
// custom request initialization.
func (c *RDS) newRequest(op *request.Operation, params, data interface{}) *request.Request {
req := c.NewRequest(op, params, data)
// Run custom request initialization if present
if initRequest != nil {
initRequest(req)
}
return req
}
+294
View File
@@ -0,0 +1,294 @@
// Code generated by private/model/cli/gen-api/main.go. DO NOT EDIT.
package rds
import (
"time"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/request"
)
// WaitUntilDBInstanceAvailable uses the Amazon RDS API operation
// DescribeDBInstances to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *RDS) WaitUntilDBInstanceAvailable(input *DescribeDBInstancesInput) error {
return c.WaitUntilDBInstanceAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilDBInstanceAvailableWithContext is an extended version of WaitUntilDBInstanceAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RDS) WaitUntilDBInstanceAvailableWithContext(ctx aws.Context, input *DescribeDBInstancesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilDBInstanceAvailable",
MaxAttempts: 60,
Delay: request.ConstantWaiterDelay(30 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "deleted",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "deleting",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "failed",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "incompatible-restore",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "incompatible-parameters",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeDBInstancesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeDBInstancesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilDBInstanceDeleted uses the Amazon RDS API operation
// DescribeDBInstances to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *RDS) WaitUntilDBInstanceDeleted(input *DescribeDBInstancesInput) error {
return c.WaitUntilDBInstanceDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilDBInstanceDeletedWithContext is an extended version of WaitUntilDBInstanceDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RDS) WaitUntilDBInstanceDeletedWithContext(ctx aws.Context, input *DescribeDBInstancesInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilDBInstanceDeleted",
MaxAttempts: 60,
Delay: request.ConstantWaiterDelay(30 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "deleted",
},
{
State: request.SuccessWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "DBInstanceNotFound",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "creating",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "modifying",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "rebooting",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBInstances[].DBInstanceStatus",
Expected: "resetting-master-credentials",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeDBInstancesInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeDBInstancesRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilDBSnapshotAvailable uses the Amazon RDS API operation
// DescribeDBSnapshots to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *RDS) WaitUntilDBSnapshotAvailable(input *DescribeDBSnapshotsInput) error {
return c.WaitUntilDBSnapshotAvailableWithContext(aws.BackgroundContext(), input)
}
// WaitUntilDBSnapshotAvailableWithContext is an extended version of WaitUntilDBSnapshotAvailable.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RDS) WaitUntilDBSnapshotAvailableWithContext(ctx aws.Context, input *DescribeDBSnapshotsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilDBSnapshotAvailable",
MaxAttempts: 60,
Delay: request.ConstantWaiterDelay(30 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "available",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "deleted",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "deleting",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "failed",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "incompatible-restore",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "incompatible-parameters",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeDBSnapshotsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeDBSnapshotsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
// WaitUntilDBSnapshotDeleted uses the Amazon RDS API operation
// DescribeDBSnapshots to wait for a condition to be met before returning.
// If the condition is not met within the max attempt window, an error will
// be returned.
func (c *RDS) WaitUntilDBSnapshotDeleted(input *DescribeDBSnapshotsInput) error {
return c.WaitUntilDBSnapshotDeletedWithContext(aws.BackgroundContext(), input)
}
// WaitUntilDBSnapshotDeletedWithContext is an extended version of WaitUntilDBSnapshotDeleted.
// With the support for passing in a context and options to configure the
// Waiter and the underlying request options.
//
// The context must be non-nil and will be used for request cancellation. If
// the context is nil a panic will occur. In the future the SDK may create
// sub-contexts for http.Requests. See https://golang.org/pkg/context/
// for more information on using Contexts.
func (c *RDS) WaitUntilDBSnapshotDeletedWithContext(ctx aws.Context, input *DescribeDBSnapshotsInput, opts ...request.WaiterOption) error {
w := request.Waiter{
Name: "WaitUntilDBSnapshotDeleted",
MaxAttempts: 60,
Delay: request.ConstantWaiterDelay(30 * time.Second),
Acceptors: []request.WaiterAcceptor{
{
State: request.SuccessWaiterState,
Matcher: request.PathAllWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "deleted",
},
{
State: request.SuccessWaiterState,
Matcher: request.ErrorWaiterMatch,
Expected: "DBSnapshotNotFound",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "creating",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "modifying",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "rebooting",
},
{
State: request.FailureWaiterState,
Matcher: request.PathAnyWaiterMatch, Argument: "DBSnapshots[].Status",
Expected: "resetting-master-credentials",
},
},
Logger: c.Config.Logger,
NewRequest: func(opts []request.Option) (*request.Request, error) {
var inCpy *DescribeDBSnapshotsInput
if input != nil {
tmp := *input
inCpy = &tmp
}
req, _ := c.DescribeDBSnapshotsRequest(inCpy)
req.SetContext(ctx)
req.ApplyOptions(opts...)
return req, nil
},
}
w.ApplyOptions(opts...)
return w.WaitWithContext(ctx)
}
+1
View File
@@ -102,6 +102,7 @@ github.com/aws/aws-sdk-go/aws/request
github.com/aws/aws-sdk-go/aws/session
github.com/aws/aws-sdk-go/service/ec2
github.com/aws/aws-sdk-go/service/iam
github.com/aws/aws-sdk-go/service/rds
github.com/aws/aws-sdk-go/service/s3
github.com/aws/aws-sdk-go/service/s3/s3manager
github.com/aws/aws-sdk-go/aws/awserr