-
Notifications
You must be signed in to change notification settings - Fork 18
/
readwriteimpl.go
463 lines (383 loc) · 14.5 KB
/
readwriteimpl.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
/******************************************************************************
* Copyright (c) 2021 PingCAP, Inc. *
* Licensed under the Apache License, Version 2.0 (the "License"); *
* you may not use this file except in compliance with the License. *
* You may obtain a copy of the License at *
* *
* http://www.apache.org/licenses/LICENSE-2.0 *
* *
* Unless required by applicable law or agreed to in writing, software *
* distributed under the License is distributed on an "AS IS" BASIS, *
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
* See the License for the specific language governing permissions and *
* limitations under the License. *
******************************************************************************/
package management
import (
"context"
"fmt"
"github.com/pingcap-inc/tiem/common/constants"
"github.com/pingcap-inc/tiem/common/errors"
"github.com/pingcap-inc/tiem/common/structs"
"github.com/pingcap-inc/tiem/library/framework"
dbCommon "github.com/pingcap-inc/tiem/models/common"
"gorm.io/gorm"
)
type ClusterReadWrite struct {
dbCommon.GormDB
}
func (g *ClusterReadWrite) Create(ctx context.Context, cluster *Cluster) (*Cluster, error) {
err := g.DB(ctx).Create(cluster).Error
if err != nil {
// duplicated name
existOrError := g.DB(ctx).Model(&Cluster{}).Where("name = ?", cluster.Name).First(&Cluster{}).Error
if existOrError == nil {
err = errors.NewErrorf(errors.TIEM_DUPLICATED_NAME, "%s:%s", errors.TIEM_DUPLICATED_NAME.Explain(), cluster.Name)
} else {
err = dbCommon.WrapDBError(err)
}
}
return cluster, err
}
func (g *ClusterReadWrite) Delete(ctx context.Context, clusterID string) (err error) {
got, err := g.Get(ctx, clusterID)
if err != nil {
return
}
err = g.DB(ctx).Delete(got).Error
if err != nil {
return dbCommon.WrapDBError(err)
}
err = g.DB(ctx).Where("cluster_id = ?", clusterID).Delete(&ClusterInstance{}).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) DeleteInstance(ctx context.Context, ID string) error {
instance := &ClusterInstance{}
err := g.DB(ctx).First(instance, "id = ?", ID).Error
if err != nil {
return errors.WrapError(errors.TIEM_INSTANCE_NOT_FOUND, "", err)
}
err = g.DB(ctx).Delete(instance).Error
if err != nil {
return errors.WrapError(errors.TIEM_DELETE_INSTANCE_ERROR, "", err)
}
return nil
}
func (g *ClusterReadWrite) Get(ctx context.Context, clusterID string) (*Cluster, error) {
if "" == clusterID {
errInfo := "get cluster failed : empty clusterID"
framework.LogWithContext(ctx).Error(errInfo)
return nil, errors.NewError(errors.TIEM_PARAMETER_INVALID, errInfo)
}
cluster := &Cluster{}
err := g.DB(ctx).First(cluster, "id = ?", clusterID).Error
if err != nil {
errInfo := fmt.Sprintf("get cluster failed : clusterID = %s, err = %s", clusterID, err.Error())
framework.LogWithContext(ctx).Error(errInfo)
return nil, errors.WrapError(errors.TIEM_CLUSTER_NOT_FOUND, errInfo, err)
} else {
return cluster, nil
}
}
func (g *ClusterReadWrite) GetMeta(ctx context.Context, clusterID string) (cluster *Cluster, instances []*ClusterInstance, users []*DBUser, err error) {
cluster, err = g.Get(ctx, clusterID)
if err != nil {
err = dbCommon.WrapDBError(err)
return
}
instances = make([]*ClusterInstance, 0)
err = g.DB(ctx).Model(&ClusterInstance{}).Where("cluster_id = ?", clusterID).Find(&instances).Error
if err != nil {
err = dbCommon.WrapDBError(err)
return
}
users, err = g.GetDBUser(ctx, clusterID)
if err != nil {
err = dbCommon.WrapDBError(err)
return
}
return
}
func (g *ClusterReadWrite) GetRelations(ctx context.Context, clusterID string) ([]*ClusterRelation, error) {
relations := make([]*ClusterRelation, 0)
err := g.DB(ctx).Model(&ClusterRelation{}).Where("object_cluster_id = ? ", clusterID).Find(&relations).Error
if err != nil {
err = dbCommon.WrapDBError(err)
}
return relations, err
}
// todo
func (g *ClusterReadWrite) QueryMetas(ctx context.Context, filters Filters, pageReq structs.PageRequest) ([]*Result, structs.Page, error) {
page := structs.Page{
Page: pageReq.Page,
PageSize: pageReq.PageSize,
}
if len(filters.TenantId) == 0 {
err := errors.NewError(errors.TIEM_PARAMETER_INVALID, "tenant id required in QueryMetas")
return nil, page, err
}
clusters := make([]*Cluster, 0)
total := int64(0)
query := g.DB(ctx).Table("clusters").Where("tenant_id = ?", filters.TenantId).Where("deleted_at is null")
if len(filters.ClusterIDs) > 0 {
query = query.Where("id in ?", filters.ClusterIDs)
}
if filters.NameLike != "" {
query = query.Where("name like '%" + filters.NameLike + "%'")
}
if len(filters.Type) > 0 {
query = query.Where("type = ?", filters.Type)
}
if len(filters.StatusFilters) > 0 {
query = query.Where("status in ?", filters.StatusFilters)
}
if len(filters.Tag) > 0 {
query = query.Where("tag_info like '%\"" + filters.Tag + "\"%'")
}
err := query.Count(&total).Order("updated_at desc").Offset(pageReq.GetOffset()).Limit(pageReq.PageSize).Find(&clusters).Error
if err != nil {
err = errors.WrapError(errors.TIEM_CLUSTER_NOT_FOUND, "", err)
return nil, page, err
} else {
page.Total = int(total)
}
results := make([]*Result, 0)
for _, c := range clusters {
instances := make([]*ClusterInstance, 0)
err = g.DB(ctx).Model(&ClusterInstance{}).Where("cluster_id = ?", c.ID).Find(&instances).Error
if err != nil {
err = errors.WrapError(errors.TIEM_INSTANCE_NOT_FOUND, "", err)
return nil, page, err
}
users, err := g.GetDBUser(ctx, c.ID)
if err != nil {
err = dbCommon.WrapDBError(err)
return nil, page, err
}
results = append(results, &Result{
Cluster: c,
Instances: instances,
DBUsers: users,
})
}
return results, page, nil
}
func (g *ClusterReadWrite) UpdateMeta(ctx context.Context, cluster *Cluster, instances []*ClusterInstance) error {
return g.DB(ctx).Transaction(func(tx *gorm.DB) error {
err := g.UpdateClusterInfo(ctx, cluster)
if err == nil {
err = g.UpdateInstance(ctx, instances...)
}
if err != nil {
msg := fmt.Sprintf("cluster update meta failed, clusterId = %s", cluster.ID)
framework.LogWithContext(ctx).Error(msg)
tx.Rollback()
return dbCommon.WrapDBError(err)
}
return nil
})
}
func (g *ClusterReadWrite) QueryInstancesByHost(ctx context.Context, hostId string, typeFilter []string, statusFilter []string) ([]*ClusterInstance, error) {
if len(hostId) == 0 {
return nil, errors.NewError(errors.TIEM_PARAMETER_INVALID, "empty hostId")
}
query := g.DB(ctx).Table("cluster_instances").Where("host_id = ?", hostId)
if len(typeFilter) > 0 {
query = query.Where("type in ?", typeFilter)
}
if len(statusFilter) > 0 {
query = query.Where("status in ?", statusFilter)
}
instances := make([]*ClusterInstance, 0)
err := query.Find(&instances).Error
return instances, dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) UpdateInstance(ctx context.Context, instances ...*ClusterInstance) error {
return g.DB(ctx).Transaction(func(tx *gorm.DB) error {
toCreate := make([]*ClusterInstance, 0)
for _, instance := range instances {
if instance.ID == "" {
toCreate = append(toCreate, instance)
} else {
err := tx.Save(instance).Error
if err != nil {
err = dbCommon.WrapDBError(err)
return err
}
}
}
if len(toCreate) > 0 {
err := tx.CreateInBatches(toCreate, len(toCreate)).Error
if err != nil {
err = dbCommon.WrapDBError(err)
return err
}
}
return nil
})
}
func (g *ClusterReadWrite) UpdateClusterInfo(ctx context.Context, template *Cluster) error {
if template == nil {
errInfo := "update cluster base info failed : empty template"
framework.LogWithContext(ctx).Error(errInfo)
return errors.NewError(errors.TIEM_PARAMETER_INVALID, errInfo)
}
cluster, err := g.Get(ctx, template.ID)
if err != nil {
err = dbCommon.WrapDBError(err)
return err
}
err = g.DB(ctx).Model(cluster).Omit("status", "maintenance_status").Updates(template).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) UpdateStatus(ctx context.Context, clusterID string, status constants.ClusterRunningStatus) error {
cluster, err := g.Get(ctx, clusterID)
if err != nil {
return err
}
cluster.Status = string(status)
err = g.DB(ctx).Save(cluster).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) SetMaintenanceStatus(ctx context.Context, clusterID string, targetStatus constants.ClusterMaintenanceStatus) error {
cluster, err := g.Get(ctx, clusterID)
if err != nil {
return err
}
if cluster.MaintenanceStatus != constants.ClusterMaintenanceNone &&
targetStatus != constants.ClusterMaintenanceDeleting ||
cluster.MaintenanceStatus == constants.ClusterMaintenanceDeleting {
errInfo := fmt.Sprintf("set cluster maintenance status conflicted : current maintenance = %s, target maintenance = %s, clusterID = %s", cluster.MaintenanceStatus, targetStatus, clusterID)
framework.LogWithContext(ctx).Error(errInfo)
return errors.NewError(errors.TIEM_CLUSTER_MAINTENANCE_CONFLICT, errInfo)
}
cluster.MaintenanceStatus = targetStatus
err = g.DB(ctx).Save(cluster).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) ClearMaintenanceStatus(ctx context.Context, clusterID string, originalStatus constants.ClusterMaintenanceStatus) error {
cluster, err := g.Get(ctx, clusterID)
if err != nil {
return err
}
if cluster.MaintenanceStatus != originalStatus {
errInfo := fmt.Sprintf("clear cluster maintenance status failed : unmatched original status, want %s, current %s", originalStatus, cluster.MaintenanceStatus)
framework.LogWithContext(ctx).Error(errInfo)
return errors.NewError(errors.TIEM_CLUSTER_MAINTENANCE_CONFLICT, errInfo)
}
cluster.MaintenanceStatus = constants.ClusterMaintenanceNone
err = g.DB(ctx).Save(cluster).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) CreateRelation(ctx context.Context, relation *ClusterRelation) error {
err := g.DB(ctx).Create(relation).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) DeleteRelation(ctx context.Context, relationID uint) error {
relation := &ClusterRelation{}
err := g.DB(ctx).First(relation, "id = ?", relationID).Delete(relation).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) SwapMasterSlaveRelation(ctx context.Context, oldMasterClusterId, oldSlaveClusterId, newSyncChangeFeedTaskId string) error {
tx := g.DB(ctx).Begin()
if err := tx.Error; err != nil {
return err
}
err := tx.Delete(&ClusterRelation{
RelationType: constants.ClusterRelationStandBy,
ObjectClusterID: oldSlaveClusterId,
SubjectClusterID: oldMasterClusterId,
}).Error
if err != nil {
tx.Rollback()
return err
}
err = tx.Create(&ClusterRelation{
RelationType: constants.ClusterRelationStandBy,
ObjectClusterID: oldMasterClusterId,
SubjectClusterID: oldSlaveClusterId,
SyncChangeFeedTaskID: newSyncChangeFeedTaskId,
}).Error
if err != nil {
tx.Rollback()
return err
}
return dbCommon.WrapDBError(tx.Commit().Error)
}
func (g *ClusterReadWrite) CreateClusterTopologySnapshot(ctx context.Context, snapshot ClusterTopologySnapshot) error {
if len(snapshot.ClusterID) == 0 || len(snapshot.TenantID) == 0 {
errInfo := fmt.Sprintf("CreateClusterTopologySnapshot failed : parameter invalid, ClusterID = %s, TenantID = %s", snapshot.ClusterID, snapshot.TenantID)
framework.LogWithContext(ctx).Error(errInfo)
return errors.NewError(errors.TIEM_PARAMETER_INVALID, errInfo)
}
if len(snapshot.PrivateKey) == 0 || len(snapshot.PublicKey) == 0 {
errInfo := "CreateClusterTopologySnapshot failed : connection key required"
framework.LogWithContext(ctx).Error(errInfo)
return errors.NewError(errors.TIEM_PARAMETER_INVALID, errInfo)
}
err := g.DB(ctx).Create(&snapshot).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) GetCurrentClusterTopologySnapshot(ctx context.Context, clusterID string) (snapshot ClusterTopologySnapshot, err error) {
if len(clusterID) == 0 {
errInfo := "get cluster topology snapshot failed : cluster id required"
framework.LogWithContext(ctx).Error(errInfo)
err = errors.NewError(errors.TIEM_PARAMETER_INVALID, errInfo)
return
}
err = g.DB(ctx).Model(snapshot).Where("cluster_id = ?", clusterID).First(&snapshot).Error
err = dbCommon.WrapDBError(err)
return
}
func (g *ClusterReadWrite) UpdateTopologySnapshotConfig(ctx context.Context, clusterID string, config string) error {
snapshot := &ClusterTopologySnapshot{}
err := g.DB(ctx).Model(&ClusterTopologySnapshot{}).Where("cluster_id = ?", clusterID).First(snapshot).Error
if err != nil {
errInfo := "update cluster topology snapshot failed : record not found"
framework.LogWithContext(ctx).Error(errInfo)
err = errors.NewError(errors.TIEM_CLUSTER_NOT_FOUND, errInfo)
return err
}
snapshot.Config = config
return dbCommon.WrapDBError(g.DB(ctx).Save(snapshot).Error)
}
func (g *ClusterReadWrite) ClearClusterPhysically(ctx context.Context, clusterID string) error {
got, err := g.Get(ctx, clusterID)
if err != nil {
return err
}
err = g.DB(ctx).Unscoped().Delete(got).Error
if err != nil {
return dbCommon.WrapDBError(err)
}
err = g.DB(ctx).Where("cluster_id = ?", clusterID).Unscoped().Delete(&ClusterInstance{}).Error
err = g.DB(ctx).Where("cluster_id = ?", clusterID).Unscoped().Delete(&ClusterTopologySnapshot{}).Error
err = g.DB(ctx).Where("cluster_id = ?", clusterID).Unscoped().Delete(&DBUser{}).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) CreateDBUser(ctx context.Context, user *DBUser) error {
err := g.DB(ctx).Create(user).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) GetDBUser(ctx context.Context, clusterID string) ([]*DBUser, error) {
users := make([]*DBUser, 0)
err := g.DB(ctx).Model(&DBUser{}).Where("cluster_id = ? ", clusterID).Find(&users).Error
if err != nil {
err = dbCommon.WrapDBError(err)
}
return users, err
}
func (g *ClusterReadWrite) DeleteDBUser(ctx context.Context, ID uint) error {
user := &DBUser{}
err := g.DB(ctx).First(user, "id = ?", ID).Delete(user).Error
return dbCommon.WrapDBError(err)
}
func (g *ClusterReadWrite) UpdateDBUser(ctx context.Context, user *DBUser) error {
g.DB(ctx).Save(user)
return nil
}
func NewClusterReadWrite(db *gorm.DB) *ClusterReadWrite {
return &ClusterReadWrite{
dbCommon.WrapDB(db),
}
}