-
Notifications
You must be signed in to change notification settings - Fork 466
/
EnvironmentService.go
393 lines (362 loc) · 12.9 KB
/
EnvironmentService.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
/*
* Copyright (c) 2020 Devtron Labs
*
* 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 cluster
import (
"fmt"
"github.com/devtron-labs/devtron/client/grafana"
"github.com/devtron-labs/devtron/internal/sql/repository/cluster"
"github.com/devtron-labs/devtron/internal/util"
"github.com/devtron-labs/devtron/pkg/pipeline"
"github.com/go-pg/pg"
"github.com/pkg/errors"
"go.uber.org/zap"
"time"
)
type EnvironmentBean struct {
Id int `json:"id,omitempty" validate:"number"`
Environment string `json:"environment_name,omitempty" validate:"required,max=50"`
ClusterId int `json:"cluster_id,omitempty" validate:"number,required"`
ClusterName string `json:"cluster_name,omitempty"`
Active bool `json:"active"`
Default bool `json:"default"`
PrometheusEndpoint string `json:"prometheus_endpoint,omitempty"`
Namespace string `json:"namespace,omitempty" validate:"max=50"`
CdArgoSetup bool `json:"isClusterCdActive"`
}
type EnvironmentService interface {
FindOne(environment string) (*EnvironmentBean, error)
Create(mappings *EnvironmentBean, userId int32) (*EnvironmentBean, error)
GetAll() ([]EnvironmentBean, error)
GetAllActive() ([]EnvironmentBean, error)
FindById(id int) (*EnvironmentBean, error)
Update(mappings *EnvironmentBean, userId int32) (*EnvironmentBean, error)
FindClusterByEnvId(id int) (*ClusterBean, error)
GetEnvironmentListForAutocomplete() ([]EnvironmentBean, error)
FindByIds(ids []*int) ([]*EnvironmentBean, error)
FindByNamespaceAndClusterName(namespaces string, clusterName string) (*cluster.Environment, error)
GetByClusterId(id int) ([]*EnvironmentBean, error)
}
type EnvironmentServiceImpl struct {
environmentRepository cluster.EnvironmentRepository
logger *zap.SugaredLogger
clusterService ClusterService
K8sUtil *util.K8sUtil
propertiesConfigService pipeline.PropertiesConfigService
grafanaClient grafana.GrafanaClient
}
func NewEnvironmentServiceImpl(environmentRepository cluster.EnvironmentRepository,
clusterService ClusterService, logger *zap.SugaredLogger,
K8sUtil *util.K8sUtil,
propertiesConfigService pipeline.PropertiesConfigService,
grafanaClient grafana.GrafanaClient,
) *EnvironmentServiceImpl {
return &EnvironmentServiceImpl{
environmentRepository: environmentRepository,
logger: logger,
clusterService: clusterService,
K8sUtil: K8sUtil,
propertiesConfigService: propertiesConfigService,
grafanaClient: grafanaClient,
}
}
func (impl EnvironmentServiceImpl) Create(mappings *EnvironmentBean, userId int32) (*EnvironmentBean, error) {
existingEnvs, err := impl.environmentRepository.FindByClusterId(mappings.ClusterId)
if err != nil && !util.IsErrNoRows(err) {
impl.logger.Errorw("error while fetch", "err", err)
return nil, err
}
err = impl.validateNamespaces(mappings.Namespace, existingEnvs)
if err != nil {
return nil, err
}
clusterBean, err := impl.clusterService.FindById(mappings.ClusterId)
if err != nil {
return nil, err
}
model, err := impl.environmentRepository.FindByName(mappings.Environment)
if err != nil && err != pg.ErrNoRows {
impl.logger.Errorw("error in finding environment for update", "err", err)
return mappings, err
}
if model.Id > 0 {
impl.logger.Warnw("environment already exists", "model", model)
return mappings, fmt.Errorf("environment already exists")
}
model = &cluster.Environment{
Name: mappings.Environment,
ClusterId: mappings.ClusterId,
Active: mappings.Active,
Namespace: mappings.Namespace,
Default: mappings.Default,
}
model.CreatedBy = userId
model.UpdatedBy = userId
model.CreatedOn = time.Now()
model.UpdatedOn = time.Now()
err = impl.environmentRepository.Create(model)
if err != nil {
impl.logger.Errorw("error in saving environment", "err", err)
return mappings, err
}
if len(model.Namespace) > 0 {
cfg, err := impl.clusterService.GetClusterConfig(clusterBean)
if err != nil {
return nil, err
}
if err := impl.K8sUtil.CreateNsIfNotExists(model.Namespace, cfg); err != nil {
impl.logger.Errorw("error in creating ns", "ns", model.Namespace, "err", err)
}
}
//ignore grafana if no prometheus url found
if len(clusterBean.PrometheusUrl) > 0 {
_, err = impl.clusterService.CreateGrafanaDataSource(clusterBean, model)
if err != nil {
impl.logger.Errorw("unable to create grafana data source", "env", model)
}
}
mappings.Id = model.Id
return mappings, nil
}
func (impl EnvironmentServiceImpl) FindOne(environment string) (*EnvironmentBean, error) {
model, err := impl.environmentRepository.FindOne(environment)
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
return nil, err
}
bean := &EnvironmentBean{
Id: model.Id,
Environment: model.Name,
ClusterId: model.Cluster.Id,
Active: model.Active,
PrometheusEndpoint: model.Cluster.PrometheusEndpoint,
Namespace: model.Namespace,
Default: model.Default,
}
return bean, nil
}
func (impl EnvironmentServiceImpl) GetAll() ([]EnvironmentBean, error) {
models, err := impl.environmentRepository.FindAll()
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
}
var beans []EnvironmentBean
for _, model := range models {
beans = append(beans, EnvironmentBean{
Id: model.Id,
Environment: model.Name,
ClusterId: model.Cluster.Id,
ClusterName: model.Cluster.ClusterName,
Active: model.Active,
PrometheusEndpoint: model.Cluster.PrometheusEndpoint,
Namespace: model.Namespace,
Default: model.Default,
CdArgoSetup: model.Cluster.CdArgoSetup,
})
}
return beans, nil
}
func (impl EnvironmentServiceImpl) GetAllActive() ([]EnvironmentBean, error) {
models, err := impl.environmentRepository.FindAllActive()
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
}
var beans []EnvironmentBean
for _, model := range models {
beans = append(beans, EnvironmentBean{
Id: model.Id,
Environment: model.Name,
ClusterId: model.Cluster.Id,
Active: model.Active,
PrometheusEndpoint: model.Cluster.PrometheusEndpoint,
Namespace: model.Namespace,
Default: model.Default,
})
}
return beans, nil
}
func (impl EnvironmentServiceImpl) FindById(id int) (*EnvironmentBean, error) {
model, err := impl.environmentRepository.FindById(id)
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
return nil, err
}
bean := &EnvironmentBean{
Id: model.Id,
Environment: model.Name,
ClusterId: model.Cluster.Id,
Active: model.Active,
PrometheusEndpoint: model.Cluster.PrometheusEndpoint,
Namespace: model.Namespace,
Default: model.Default,
}
/*clusterBean := &ClusterBean{
id:model.Cluster.id,
ClusterName: model.Cluster.ClusterName,
Active:model.Cluster.Active,
}*/
return bean, nil
}
func (impl EnvironmentServiceImpl) Update(mappings *EnvironmentBean, userId int32) (*EnvironmentBean, error) {
model, err := impl.environmentRepository.FindById(mappings.Id)
if err != nil {
impl.logger.Errorw("error in finding environment for update", "err", err)
return mappings, err
}
isNamespaceChange := false
if model.Namespace != mappings.Namespace {
isNamespaceChange = true
}
clusterBean, err := impl.clusterService.FindById(mappings.ClusterId)
if err != nil {
return nil, err
}
model.Name = mappings.Environment
model.Active = mappings.Active
model.Namespace = mappings.Namespace
model.Default = mappings.Default
model.UpdatedBy = userId
model.UpdatedOn = time.Now()
//namespace create if not exist
if len(model.Namespace) > 0 {
cfg, err := impl.clusterService.GetClusterConfig(clusterBean)
if err != nil {
return nil, err
}
if err := impl.K8sUtil.CreateNsIfNotExists(model.Namespace, cfg); err != nil {
impl.logger.Errorw("error in creating ns", "ns", model.Namespace, "err", err)
}
}
//namespace changed, update it on chart env override config as well
if isNamespaceChange == true {
impl.logger.Debug("namespace has modified in request, it will update related config")
envPropertiesList, err := impl.propertiesConfigService.GetEnvironmentPropertiesById(mappings.Id)
if err != nil {
impl.logger.Error("failed to fetch chart environment override config", "err", err)
//TODO - atomic operation breaks, throw internal error codes
} else {
for _, envProperties := range envPropertiesList {
_, err := impl.propertiesConfigService.UpdateEnvironmentProperties(0, &pipeline.EnvironmentProperties{Id: envProperties.Id, Namespace: mappings.Namespace}, userId)
if err != nil {
impl.logger.Error("failed to update chart environment override config", "err", err)
//TODO - atomic operation breaks, throw internal error codes
}
}
}
}
grafanaDatasourceId := model.GrafanaDatasourceId
//grafana datasource create if not exist
if len(clusterBean.PrometheusUrl) > 0 && grafanaDatasourceId == 0 {
grafanaDatasourceId, err = impl.clusterService.CreateGrafanaDataSource(clusterBean, model)
if err != nil {
impl.logger.Errorw("unable to create grafana data source for missing env", "env", model)
}
}
model.GrafanaDatasourceId = grafanaDatasourceId
err = impl.environmentRepository.Update(model)
if err != nil {
impl.logger.Errorw("error in updating environment", "err", err)
return mappings, err
}
mappings.Id = model.Id
return mappings, nil
}
func (impl EnvironmentServiceImpl) FindClusterByEnvId(id int) (*ClusterBean, error) {
model, err := impl.environmentRepository.FindById(id)
if err != nil {
impl.logger.Errorw("fetch cluster by environment id", "err", err)
return nil, err
}
clusterBean := &ClusterBean{
Id: model.Cluster.Id,
ClusterName: model.Cluster.ClusterName,
Active: model.Cluster.Active,
ServerUrl: model.Cluster.ServerUrl,
Config: model.Cluster.Config,
}
return clusterBean, nil
}
func (impl EnvironmentServiceImpl) GetEnvironmentListForAutocomplete() ([]EnvironmentBean, error) {
models, err := impl.environmentRepository.FindAllActive()
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
}
var beans []EnvironmentBean
for _, model := range models {
beans = append(beans, EnvironmentBean{
Id: model.Id,
Environment: model.Name,
Namespace: model.Namespace,
CdArgoSetup: model.Cluster.CdArgoSetup,
})
}
return beans, nil
}
func (impl EnvironmentServiceImpl) validateNamespaces(namespace string, envs []*cluster.Environment) error {
if len(envs) >= 1 {
if namespace == "" {
impl.logger.Errorw("namespace cannot be empty")
return errors.New("namespace cannot be empty")
}
for _, n := range envs {
if n.Namespace == "" {
impl.logger.Errorw("cannot create env as existing old envs have no namespace")
return errors.New("cannot create env as existing old envs have no namespace")
}
}
}
return nil
}
func (impl EnvironmentServiceImpl) FindByIds(ids []*int) ([]*EnvironmentBean, error) {
models, err := impl.environmentRepository.FindByIds(ids)
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
}
var beans []*EnvironmentBean
for _, model := range models {
beans = append(beans, &EnvironmentBean{
Id: model.Id,
Environment: model.Name,
//ClusterId: model.Cluster.Id,
//ClusterName: model.Cluster.ClusterName,
Active: model.Active,
//PrometheusEndpoint: model.Cluster.PrometheusEndpoint,
Namespace: model.Namespace,
Default: model.Default,
//CdArgoSetup: model.Cluster.CdArgoSetup,
})
}
return beans, nil
}
func (impl EnvironmentServiceImpl) FindByNamespaceAndClusterName(namespaces string, clusterName string) (*cluster.Environment, error) {
env, err := impl.environmentRepository.FindByNamespaceAndClusterName(namespaces, clusterName)
return env, err
}
func (impl EnvironmentServiceImpl) GetByClusterId(id int) ([]*EnvironmentBean, error) {
models, err := impl.environmentRepository.FindByClusterId(id)
if err != nil {
impl.logger.Errorw("error in fetching environment", "err", err)
}
var beans []*EnvironmentBean
for _, model := range models {
beans = append(beans, &EnvironmentBean{
Id: model.Id,
Environment: model.Name,
Namespace: model.Namespace,
})
}
return beans, nil
}