-
Notifications
You must be signed in to change notification settings - Fork 373
/
general_ability.go
352 lines (295 loc) · 10.6 KB
/
general_ability.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
// 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 generalability
import (
"fmt"
"strconv"
"strings"
"time"
"github.com/ghodss/yaml"
"github.com/erda-project/erda/apistructs"
"github.com/erda-project/erda/bundle"
"github.com/erda-project/erda/modules/msp/instance/db"
"github.com/erda-project/erda/modules/msp/resource/deploy/handlers"
"github.com/erda-project/erda/modules/msp/resource/utils"
"github.com/erda-project/erda/pkg/parser/diceyml"
)
const (
ProjectDisplayName = "general_ability"
ProjectDescFormat = "%s集群能力项目"
ApplicationNameSuffix = "_ability"
AbilityPrefix = "ABILITY_"
AbilityHostSuffix = "_HOST"
AbilityPortSuffix = "_PORT"
AbilityRuntimeId = "abilityRuntimeId"
LifeHost = "lifeHost"
LifePort = "lifePort"
)
type GeneralAbilityDeployHandler struct {
*handlers.DefaultDeployHandler
}
func (p *provider) IsMatch(tmc *db.Tmc) bool {
return tmc.ServiceType == "GENERAL_ABILITY"
}
func (p *provider) BuildServiceGroupRequest(resourceInfo *handlers.ResourceInfo, tmcInstance *db.Instance, clusterConfig map[string]string) interface{} {
// general-ability addon will call orchestrator to do real deploy
return nil
}
func (p *provider) DoDeploy(serviceGroupDeployRequest interface{}, resourceInfo *handlers.ResourceInfo, tmcInstance *db.Instance, clusterConfig map[string]string) (
interface{}, error) {
runtimeId, err := p.doRuntimeCreateRequest(tmcInstance, resourceInfo)
if err != nil {
return nil, err
}
runtimeStatus, err := p.waitRuntimeReady(tmcInstance, runtimeId)
if err != nil {
return nil, err
}
return runtimeStatus, nil
}
func (p *provider) BuildTmcInstanceConfig(tmcInstance *db.Instance, serviceGroupDeployResult interface{}, clusterConfig map[string]string, additionalConfig map[string]string) map[string]string {
runtimeStatus := serviceGroupDeployResult.(*bundle.GetRuntimeServicesResponseData)
config := map[string]string{}
for name, service := range runtimeStatus.Services {
// todo lifeHost support
addrs := service.Addrs
if len(addrs) == 0 {
continue
}
addr := addrs[0]
idx := strings.LastIndex(addr, ":")
keyPrefix := AbilityPrefix + tmcInstance.Engine + "_" + name
hostKey := strings.ToUpper(strings.ReplaceAll(keyPrefix+AbilityHostSuffix, "-", "_"))
portKey := strings.ToUpper(strings.ReplaceAll(keyPrefix+AbilityPortSuffix, "-", "_"))
if idx == -1 {
config[hostKey] = addr
} else {
config[hostKey] = addr[0:idx]
config[portKey] = addr[idx+1:]
}
}
return config
}
func (p *provider) DoApplyTmcInstanceTenant(req *handlers.ResourceDeployRequest, resourceInfo *handlers.ResourceInfo,
tmcInstance *db.Instance, tenant *db.InstanceTenant, clusterConfig map[string]string) (map[string]string, error) {
// todo add lifeHost support
return map[string]string{}, nil
}
func (p *provider) doRuntimeCreateRequest(tmcInstance *db.Instance, resourceInfo *handlers.ResourceInfo) (uint64, error) {
instanceOptions := map[string]string{}
utils.JsonConvertObjToType(tmcInstance.Options, &instanceOptions)
orgIdValue := instanceOptions["orgId"]
if len(orgIdValue) == 0 {
return 0, fmt.Errorf("orgId is null")
}
orgId, err := strconv.ParseUint(orgIdValue, 10, 64)
if err != nil {
return 0, fmt.Errorf("orgId[%s] can not convert to number", orgIdValue)
}
az := tmcInstance.Az
userId := instanceOptions["User-ID"]
workspace := instanceOptions["workspace"]
var projectId uint64
if resourceInfo.Tmc.DeployMode == handlers.DeployModePAAS {
projectIdValue := instanceOptions["projectId"]
if len(projectIdValue) == 0 {
return 0, fmt.Errorf("projectId is null")
}
projectId, _ = strconv.ParseUint(projectIdValue, 10, 64)
} else {
projectId, err = p.getProjectId(orgId, az)
if err != nil {
return 0, err
}
}
applicationId, err := p.getApplicationId(orgId, projectId, tmcInstance.Engine, userId)
if err != nil {
return 0, err
}
releaseId := tmcInstance.ReleaseID
if len(releaseId) == 0 {
releaseId, err = p.createRelease(orgId, resourceInfo.Dice, tmcInstance.Engine, tmcInstance.Version)
if err != nil {
return 0, err
}
err = p.TmcVersionDb.UpdateReleaseId(tmcInstance.Engine, tmcInstance.Version, releaseId)
if err != nil {
return 0, err
}
}
runtimeId, err := p.getRuntimeId(resourceInfo.Tmc.DeployMode, orgId, projectId, applicationId, workspace, tmcInstance.Version, releaseId, az)
if err != nil {
return 0, err
}
instanceOptions[AbilityRuntimeId] = strconv.FormatUint(runtimeId, 10)
// todo support lifeHost config
optionsStr, _ := utils.JsonConvertObjToString(instanceOptions)
p.InstanceDb.Model(tmcInstance).Update("options", optionsStr)
return runtimeId, nil
}
func (p *provider) getProjectId(orgId uint64, az string) (uint64, error) {
userID := p.GetDiceOperatorId()
name := az + "_" + ProjectDisplayName
project, err := p.Bdl.GetProjectByOrgIdAndName(orgId, name, userID)
if err != nil {
return 0, err
}
if project != nil {
return project.ID, nil
}
desc := fmt.Sprintf(ProjectDescFormat, az)
projectId, err := p.createProject(orgId, name, az, ProjectDisplayName, desc)
if err != nil {
return 0, err
}
return projectId, nil
}
func (p *provider) createProject(orgId uint64, projectName, clusterName, displayName, desc string) (uint64, error) {
return p.Bdl.CreateProject(apistructs.ProjectCreateRequest{
ClusterConfig: map[string]string{
"DEV": clusterName,
"TEST": clusterName,
"STAGING": clusterName,
"PROD": clusterName,
},
OrgID: orgId,
Name: projectName,
DisplayName: displayName,
Desc: desc,
CpuQuota: 5.0,
MemQuota: 16.0,
}, p.GetDiceOperatorId())
}
func (p *provider) getApplicationId(orgId uint64, projectId uint64, engine string, userId string) (uint64, error) {
applicationName := engine + ApplicationNameSuffix
operatorId := p.GetDiceOperatorId()
applications, err := p.Bdl.GetAppsByProjectAndAppName(projectId, orgId, operatorId, applicationName)
if err != nil {
return 0, err
}
if applications.Total > 0 {
return applications.List[0].ID, nil
}
applicationId, err := p.createApplication(orgId, projectId, applicationName, engine, "ABILITY")
if err != nil {
return 0, err
}
if len(userId) == 0 {
return applicationId, nil
}
err = p.addApplicationManager(applicationId, userId)
if err != nil {
return 0, err
}
return applicationId, nil
}
func (p *provider) createApplication(orgId uint64, projectId uint64, applicationName string, desc string, mode string) (uint64, error) {
app, err := p.Bdl.CreateApp(apistructs.ApplicationCreateRequest{
ProjectID: projectId,
Name: applicationName,
Desc: desc,
Mode: apistructs.ApplicationMode(mode),
}, p.GetDiceOperatorId())
if err != nil {
return 0, err
}
return app.ID, nil
}
func (p *provider) addApplicationManager(applicationId uint64, managerUserId string) error {
return p.Bdl.AddMember(apistructs.MemberAddRequest{
Scope: apistructs.Scope{
Type: "app",
ID: strconv.FormatUint(applicationId, 10),
},
Roles: []string{"Manager"},
UserIDs: []string{managerUserId},
}, p.GetDiceOperatorId())
}
func (p *provider) createRelease(orgId uint64, dice *diceyml.Object, engine string, version string) (string, error) {
releaseName := engine + ":" + version
for _, service := range dice.Services {
if service.Deployments.Selectors == nil {
service.Deployments.Selectors = map[string]diceyml.Selector{}
}
service.Envs["ADDON_GROUP"] = "ability"
service.Envs["ADDON_TYPE"] = engine
service.Envs["ADDON_ID"] = engine
}
yml, err := yaml.Marshal(*dice)
if err != nil {
return "", fmt.Errorf("error marshal to yaml:%s", err.Error())
}
return p.Bdl.CreateRelease(apistructs.ReleaseCreateRequest{
ReleaseName: releaseName,
Dice: string(yml),
}, orgId, p.GetDiceOperatorId())
}
func (p *provider) getRuntimeId(deployMode string, orgId uint64, projectId uint64, applicationId uint64, workspace string, version string, releaseId string, clusterName string) (uint64, error) {
runtimeName := version
if deployMode == handlers.DeployModePAAS {
runtimeName += "-" + clusterName
}
runtimes, err := p.Bdl.GetRuntimes(runtimeName, strconv.FormatUint(applicationId, 10), workspace, strconv.FormatUint(orgId, 10), p.GetDiceOperatorId())
if err != nil {
return 0, err
}
if len(runtimes) > 0 {
runtime := runtimes[0]
if runtime.DeployStatus == apistructs.DeploymentStatusWaiting || runtime.DeployStatus == apistructs.DeploymentStatusDeploying {
return runtime.ID, nil
} else if runtime.DeployStatus == apistructs.DeploymentStatusCanceling {
return 0, fmt.Errorf("get runtime canceling, can not deploy")
}
}
runtimeId, err := p.createRuntime(orgId, projectId, applicationId, workspace, runtimeName, releaseId, clusterName)
if err != nil {
return 0, err
}
return runtimeId, nil
}
func (p *provider) createRuntime(orgId uint64, projectId uint64, applicationId uint64, workspace string, runtimeName string, releaseId string, clusterName string) (uint64, error) {
runtime, err := p.Bdl.CreateRuntime(apistructs.RuntimeCreateRequest{
Name: runtimeName,
ReleaseID: releaseId,
Operator: p.GetDiceOperatorId(),
ClusterName: clusterName,
Source: "PIPELINE",
Extra: apistructs.RuntimeCreateRequestExtra{
OrgID: orgId,
ProjectID: projectId,
ApplicationID: applicationId,
Workspace: workspace,
},
}, orgId, p.GetDiceOperatorId())
if err != nil {
return 0, err
}
return runtime.RuntimeID, nil
}
func (p *provider) waitRuntimeReady(instance *db.Instance, runtimeId uint64) (*bundle.GetRuntimeServicesResponseData, error) {
instanceOptions := map[string]string{}
utils.JsonConvertObjToType(instance.Options, &instanceOptions)
orgId, _ := strconv.ParseUint(instanceOptions["orgId"], 10, 64)
startTime := time.Now().Unix()
for time.Now().Unix()-startTime < handlers.RuntimeMaxUpTimeoutSeconds {
runtime, err := p.Bdl.GetRuntimeServices(runtimeId, orgId, p.GetDiceOperatorId())
if err != nil {
continue
}
if runtime.DeployStatus == string(apistructs.DeploymentStatusOK) {
return runtime, nil
}
time.Sleep(10 * time.Second)
}
return nil, fmt.Errorf("wait servicegroup up timeout")
}