forked from aliyun/terraform-provider-alicloud
-
Notifications
You must be signed in to change notification settings - Fork 0
/
resource_alicloud_db_readwrite_splitting_connection.go
266 lines (228 loc) · 8.49 KB
/
resource_alicloud_db_readwrite_splitting_connection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package alicloud
import (
"encoding/json"
"fmt"
"regexp"
"strconv"
"time"
"github.com/aliyun/alibaba-cloud-sdk-go/services/rds"
"github.com/hashicorp/terraform/helper/resource"
"github.com/hashicorp/terraform/helper/schema"
"github.com/terraform-providers/terraform-provider-alicloud/alicloud/connectivity"
)
const dbConnectionPrefixWithSuffixRegex = "^([a-zA-Z0-9\\-_]+)" + dbConnectionSuffixRegex + "$"
var dbConnectionPrefixWithSuffixRegexp = regexp.MustCompile(dbConnectionPrefixWithSuffixRegex)
func resourceAlicloudDBReadWriteSplittingConnection() *schema.Resource {
return &schema.Resource{
Create: resourceAlicloudDBReadWriteSplittingConnectionCreate,
Read: resourceAlicloudDBReadWriteSplittingConnectionRead,
Update: resourceAlicloudDBReadWriteSplittingConnectionUpdate,
Delete: resourceAlicloudDBReadWriteSplittingConnectionDelete,
Importer: &schema.ResourceImporter{
State: schema.ImportStatePassthrough,
},
Schema: map[string]*schema.Schema{
"instance_id": &schema.Schema{
Type: schema.TypeString,
ForceNew: true,
Required: true,
},
"connection_prefix": &schema.Schema{
Type: schema.TypeString,
Optional: true,
ForceNew: true,
ValidateFunc: validateDBConnectionPrefix,
},
"distribution_type": &schema.Schema{
Type: schema.TypeString,
Required: true,
ValidateFunc: validateAllowedStringValue([]string{"Standard", "Custom"}),
},
"weight": &schema.Schema{
Type: schema.TypeMap,
Optional: true,
},
"max_delay_time": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
"connection_string": &schema.Schema{
Type: schema.TypeString,
Computed: true,
},
"port": &schema.Schema{
Type: schema.TypeInt,
Optional: true,
Computed: true,
},
},
}
}
func resourceAlicloudDBReadWriteSplittingConnectionCreate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
request := rds.CreateAllocateReadWriteSplittingConnectionRequest()
request.RegionId = string(client.Region)
request.DBInstanceId = Trim(d.Get("instance_id").(string))
request.MaxDelayTime = strconv.Itoa(d.Get("max_delay_time").(int))
prefix, ok := d.GetOk("connection_prefix")
if ok && prefix.(string) != "" {
request.ConnectionStringPrefix = prefix.(string)
}
port, ok := d.GetOk("port")
if ok {
request.Port = strconv.Itoa(port.(int))
}
request.DistributionType = d.Get("distribution_type").(string)
if weight, ok := d.GetOk("weight"); ok && weight != nil && len(weight.(map[string]interface{})) > 0 {
if serial, err := json.Marshal(weight); err != nil {
return err
} else {
request.Weight = string(serial)
}
}
if err := resource.Retry(60*time.Minute, func() *resource.RetryError {
_, err := client.WithRdsClient(func(rdsClient *rds.Client) (interface{}, error) {
return rdsClient.AllocateReadWriteSplittingConnection(request)
})
if err != nil {
if IsExceptedErrors(err, DBReadInstanceNotReadyStatus) {
return resource.RetryableError(fmt.Errorf("AllocateReadWriteSplittingConnection got an error: %#v", err))
}
return resource.NonRetryableError(fmt.Errorf("AllocateReadWriteSplittingConnection got an error: %#v", err))
}
return nil
}); err != nil {
return fmt.Errorf("AllocateReadWriteSplittingConnection got an error: %#v", err)
}
d.SetId(request.DBInstanceId)
// wait read write splitting connection ready after creation
// for it may take up to 10 hours to create a readonly instance
if err := rdsService.WaitForDBReadWriteSplitting(request.DBInstanceId, 60*60*10); err != nil {
return fmt.Errorf("WaitForDBReadWriteSplitting got error: %#v", err)
}
return resourceAlicloudDBReadWriteSplittingConnectionUpdate(d, meta)
}
func resourceAlicloudDBReadWriteSplittingConnectionRead(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
err := rdsService.WaitForDBReadWriteSplitting(d.Id(), 30*60)
if err != nil {
return fmt.Errorf("WaitForDBReadWriteSplitting got an error: %#v", err)
}
conn, err := rdsService.DescribeReadWriteSplittingConnection(d.Id())
if err != nil {
return fmt.Errorf("DescribeReadWriteSplittingConnection got an error: %#v", err)
}
d.Set("instance_id", d.Id())
d.Set("connection_string", conn.ConnectionString)
d.Set("distribution_type", conn.DistributionType)
if port, err := strconv.Atoi(conn.Port); err == nil {
d.Set("port", port)
}
if mdt, err := strconv.Atoi(conn.MaxDelayTime); err == nil {
d.Set("max_delay_time", mdt)
}
if w, ok := d.GetOk("weight"); ok {
documented := w.(map[string]interface{})
for _, config := range conn.DBInstanceWeights.DBInstanceWeight {
if config.Availability != "Available" {
delete(documented, config.DBInstanceId)
continue
}
if config.Weight != "0" {
if _, ok := documented[config.DBInstanceId]; ok {
documented[config.DBInstanceId] = config.Weight
}
}
}
d.Set("weight", documented)
}
submatch := dbConnectionPrefixWithSuffixRegexp.FindStringSubmatch(conn.ConnectionString)
if len(submatch) > 1 {
d.Set("connection_prefix", submatch[1])
}
return nil
}
func resourceAlicloudDBReadWriteSplittingConnectionUpdate(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
request := rds.CreateModifyReadWriteSplittingConnectionRequest()
request.DBInstanceId = d.Id()
update := false
if d.HasChange("max_delay_time") {
request.MaxDelayTime = strconv.Itoa(d.Get("max_delay_time").(int))
update = true
}
if !update && d.IsNewResource() {
return resourceAlicloudDBReadWriteSplittingConnectionRead(d, meta)
}
if d.HasChange("weight") {
if weight, ok := d.GetOk("weight"); ok && weight != nil && len(weight.(map[string]interface{})) > 0 {
if serial, err := json.Marshal(weight); err != nil {
return err
} else {
request.Weight = string(serial)
}
}
update = true
}
if d.HasChange("distribution_type") {
request.DistributionType = d.Get("distribution_type").(string)
update = true
}
if update {
// wait instance running before modifying
if err := rdsService.WaitForDBInstance(request.DBInstanceId, Running, 60*60); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
if err := resource.Retry(30*time.Minute, func() *resource.RetryError {
_, err := client.WithRdsClient(func(rdsClient *rds.Client) (interface{}, error) {
return rdsClient.ModifyReadWriteSplittingConnection(request)
})
if err != nil {
if IsExceptedErrors(err, OperationDeniedDBStatus) || IsExceptedErrors(err, DBReadInstanceNotReadyStatus) {
return resource.RetryableError(fmt.Errorf("Modify DBInstance Connection got an error: %#v", err))
}
return resource.NonRetryableError(fmt.Errorf("Modify DBInstance Connection got an error: %#v", err))
}
return nil
}); err != nil {
return err
}
// wait instance running after modifying
if err := rdsService.WaitForDBInstance(request.DBInstanceId, Running, 500); err != nil {
return fmt.Errorf("WaitForInstance %s got error: %#v", Running, err)
}
}
return resourceAlicloudDBReadWriteSplittingConnectionRead(d, meta)
}
func resourceAlicloudDBReadWriteSplittingConnectionDelete(d *schema.ResourceData, meta interface{}) error {
client := meta.(*connectivity.AliyunClient)
rdsService := RdsService{client}
return resource.Retry(30*time.Minute, func() *resource.RetryError {
request := rds.CreateReleaseReadWriteSplittingConnectionRequest()
request.DBInstanceId = d.Id()
_, err := client.WithRdsClient(func(rdsClient *rds.Client) (interface{}, error) {
return rdsClient.ReleaseReadWriteSplittingConnection(request)
})
if err != nil {
if IsExceptedErrors(err, OperationDeniedDBStatus) {
return resource.RetryableError(fmt.Errorf("Release DB connection got an error: %#v.", err))
}
if rdsService.NotFoundDBInstance(err) || IsExceptedError(err, InvalidRwSplitNetTypeNotFound) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Release DB connection got an error: %#v.", err))
}
_, err = rdsService.DescribeReadWriteSplittingConnection(d.Id())
if err != nil {
if rdsService.NotFoundDBInstance(err) || IsExceptedError(err, InvalidCurrentConnectionStringNotFound) {
return nil
}
return resource.NonRetryableError(fmt.Errorf("Release DB connection got an error: %#v.", err))
}
return resource.RetryableError(fmt.Errorf("Release DB connection timeout."))
})
}