/
addon_tenant.go
176 lines (159 loc) · 5.5 KB
/
addon_tenant.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
// Copyright (c) 2021 Terminus, Inc.
//
// This program is free software: you can use, redistribute, and/or modify
// it under the terms of the GNU Affero General Public License, version 3
// or later ("AGPL"), as published by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but WITHOUT
// ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
// FITNESS FOR A PARTICULAR PURPOSE.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package addon
import (
"encoding/base64"
"encoding/json"
"fmt"
"strconv"
"time"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/modules/orchestrator/dbclient"
"github.com/erda-project/erda/pkg/crypto/uuid"
"github.com/erda-project/erda/pkg/kms/kmstypes"
"github.com/erda-project/erda/pkg/strutil"
)
const (
CREATE_DB = "CREATE DATABASE IF NOT EXISTS `%s`;"
CREATE_USER = "CREATE USER '%s'@'%%' IDENTIFIED by '%s';"
GRANT_USER_TO_DB = "GRANT ALL ON %s.* TO '%s'@'%%';"
FLUSH = "flush privileges;"
)
// CreateAddonTenant
func (a *Addon) CreateAddonTenant(name string, addonInstanceRoutingID string, config map[string]string) (string, error) {
addoninsRouting, err := a.db.GetInstanceRouting(addonInstanceRoutingID)
if err != nil {
return "", err
}
if addoninsRouting == nil {
return "", fmt.Errorf("未找到 addon(%s)", addonInstanceRoutingID)
}
if addoninsRouting.Status != string(apistructs.AddonAttached) {
return "", fmt.Errorf("addon(%s) not ready, cannot create tenant", addoninsRouting.ID)
}
addonins, err := a.db.GetAddonInstance(addoninsRouting.RealInstance)
if err != nil {
return "", err
}
projectid, err := strconv.ParseUint(addoninsRouting.ProjectID, 10, 64)
if err != nil {
return "", fmt.Errorf("failed to parse project id(%s), %v", addoninsRouting.ProjectID, err)
}
existTenants, err := a.db.ListAddonInstanceTenantByProjectIDs([]uint64{projectid})
if err != nil {
return "", err
}
for _, e := range existTenants {
if e.Name == name {
return "", fmt.Errorf("已存在同名addon租户")
}
}
switch addoninsRouting.AddonName {
case "mysql":
return a.CreateMysqlTenant(name, addoninsRouting, addonins, config)
default:
return "", fmt.Errorf("addon(%s) not support creating tenant yet", addoninsRouting.AddonName)
}
}
func (a *Addon) CreateMysqlTenant(name string, addoninsRouting *dbclient.AddonInstanceRouting, addonins *dbclient.AddonInstance, config map[string]string) (string, error) {
username := name + "-" + uuid.UUID()[:12]
dbs_s := config["database"]
dbs := strutil.Split(dbs_s, ",", true)
if len(dbs) == 0 {
dbs = []string{username}
}
clusterinfo, err := a.bdl.QueryClusterInfo(addonins.Cluster)
if err != nil {
return "", err
}
kmskey, err := a.bdl.KMSCreateKey(apistructs.KMSCreateKeyRequest{
CreateKeyRequest: kmstypes.CreateKeyRequest{
PluginKind: kmstypes.PluginKind_DICE_KMS,
},
})
if err != nil {
return "", err
}
passwd := uuid.UUID()
r, err := a.bdl.KMSEncrypt(apistructs.KMSEncryptRequest{
EncryptRequest: kmstypes.EncryptRequest{
KeyID: kmskey.KeyMetadata.KeyID,
PlaintextBase64: base64.StdEncoding.EncodeToString([]byte(passwd)),
},
})
if err != nil {
return "", err
}
passwd_encrypted := r.CiphertextBase64
// 创建 user 及 db
sqls := []string{}
for _, db := range dbs {
sqls = append(sqls, fmt.Sprintf(CREATE_DB, db))
}
sqls = append(sqls, fmt.Sprintf(CREATE_USER, username, passwd))
for _, db := range dbs {
sqls = append(sqls, fmt.Sprintf(GRANT_USER_TO_DB, db, username))
}
sqls = append(sqls, FLUSH)
addonconfig, err := a.getAddonConfig(addonins.ID)
if err != nil {
return "", err
}
host, ok1 := addonconfig.Config["MYSQL_HOST"]
rootpasswd, ok2 := addonconfig.Config["MYSQL_PASSWORD"]
port, ok3 := addonconfig.Config["MYSQL_PORT"]
rootname, ok4 := addonconfig.Config["MYSQL_USERNAME"]
if !ok1 || !ok2 || !ok3 || !ok4 {
return "", fmt.Errorf("addon 配置中 MYSQL_HOST | MYSQL_PASSWORD | MYSQL_PORT | MYSQL_USERNAME 不存在: %+v", addonconfig.Config)
}
var execSqlDto apistructs.MysqlExec
execSqlDto.URL = strutil.Join([]string{apistructs.AddonMysqlJdbcPrefix, host.(string), ":", port.(string)}, "")
execSqlDto.User = rootname.(string)
execSqlDto.Password = rootpasswd.(string)
execSqlDto.Sqls = sqls
if err := a.bdl.MySQLExec(&execSqlDto, formatSoldierUrl(&clusterinfo)); err != nil {
return "", err
}
// 创建 tenant 记录
tenantConfig := map[string]string{
"MYSQL_HOST": host.(string),
"MYSQL_PASSSWORD": passwd_encrypted,
"MYSQL_PORT": port.(string),
"MYSQL_USERNAME": username,
"MYSQL_DATABASE": strutil.Join(dbs, ",", true),
"ADDON_HAS_ENCRIPY": "YES",
}
tenantConfig_s, err := json.Marshal(tenantConfig)
if err != nil {
return "", err
}
id := a.getRandomId()
if err := a.db.CreateAddonInstanceTenant(&dbclient.AddonInstanceTenant{
ID: id,
Name: name,
AddonInstanceID: addonins.ID,
AddonInstanceRoutingID: addoninsRouting.ID,
Config: string(tenantConfig_s),
OrgID: addonins.OrgID,
ProjectID: addonins.ProjectID,
AppID: addonins.ApplicationID,
Workspace: addonins.Workspace,
Deleted: "N",
KmsKey: kmskey.KeyMetadata.KeyID,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}); err != nil {
return "", err
}
return id, nil
}