-
Notifications
You must be signed in to change notification settings - Fork 818
/
product.go
382 lines (316 loc) · 9.26 KB
/
product.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
/*
Copyright 2021 The KodeRover Authors.
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 mongodb
import (
"context"
"errors"
"fmt"
"time"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"github.com/koderover/zadig/pkg/microservice/aslan/config"
"github.com/koderover/zadig/pkg/microservice/aslan/core/common/repository/models"
"github.com/koderover/zadig/pkg/setting"
mongotool "github.com/koderover/zadig/pkg/tool/mongo"
)
type ProductFindOptions struct {
Name string
EnvName string
Namespace string
}
// ClusterId is a primitive.ObjectID{}.Hex()
type ProductListOptions struct {
EnvName string
Name string
IsPublic bool
ClusterID string
IsSortByUpdateTime bool
IsSortByProductName bool
ExcludeStatus string
ExcludeSource string
Source string
InProjects []string
InEnvs []string
}
type projectEnvs struct {
ID projectID `bson:"_id"`
ProjectName string `bson:"project_name"`
Envs []string `bson:"envs"`
}
type projectID struct {
ProductName string `bson:"product_name"`
}
type ProductColl struct {
*mongo.Collection
coll string
}
func NewProductColl() *ProductColl {
name := models.Product{}.TableName()
return &ProductColl{Collection: mongotool.Database(config.MongoDatabase()).Collection(name), coll: name}
}
func (c *ProductColl) GetCollectionName() string {
return c.coll
}
func (c *ProductColl) EnsureIndex(ctx context.Context) error {
mod := []mongo.IndexModel{
{
Keys: bson.D{
bson.E{Key: "env_name", Value: 1},
bson.E{Key: "product_name", Value: 1},
},
Options: options.Index().SetUnique(true),
},
{
Keys: bson.D{
bson.E{Key: "env_name", Value: 1},
bson.E{Key: "product_name", Value: 1},
bson.E{Key: "update_time", Value: 1},
},
Options: options.Index().SetUnique(false),
},
}
_, err := c.Indexes().CreateMany(ctx, mod)
return err
}
type ProductEnvFindOptions struct {
Name string
Namespace string
}
func (c *ProductColl) FindEnv(opt *ProductEnvFindOptions) (*models.Product, error) {
query := bson.M{}
if opt.Name != "" {
query["product_name"] = opt.Name
}
if opt.Namespace != "" {
query["namespace"] = opt.Namespace
}
ret := new(models.Product)
err := c.FindOne(context.TODO(), query).Decode(ret)
return ret, err
}
func (c *ProductColl) Find(opt *ProductFindOptions) (*models.Product, error) {
res := &models.Product{}
query := bson.M{}
if opt.Name != "" {
query["product_name"] = opt.Name
}
if opt.EnvName != "" {
query["env_name"] = opt.EnvName
}
if opt.Namespace != "" {
query["namespace"] = opt.Namespace
}
err := c.FindOne(context.TODO(), query).Decode(res)
return res, err
}
func (c *ProductColl) EnvCount() (int64, error) {
query := bson.M{"status": bson.M{"$ne": setting.ProductStatusDeleting}}
ctx := context.Background()
count, err := c.Collection.CountDocuments(ctx, query)
if err != nil {
return 0, err
}
return count, nil
}
func (c *ProductColl) List(opt *ProductListOptions) ([]*models.Product, error) {
var ret []*models.Product
query := bson.M{}
if opt == nil {
opt = &ProductListOptions{}
}
if opt.EnvName != "" {
query["env_name"] = opt.EnvName
} else if len(opt.InEnvs) > 0 {
query["env_name"] = bson.M{"$in": opt.InEnvs}
}
if opt.Name != "" {
query["product_name"] = opt.Name
}
if opt.IsPublic {
query["is_public"] = opt.IsPublic
}
if opt.ClusterID != "" {
query["cluster_id"] = opt.ClusterID
}
if opt.Source != "" {
query["source"] = opt.Source
}
if opt.ExcludeSource != "" {
query["source"] = bson.M{"$ne": opt.ExcludeSource}
}
if opt.ExcludeStatus != "" {
query["status"] = bson.M{"$ne": opt.ExcludeStatus}
}
if len(opt.InProjects) > 0 {
query["product_name"] = bson.M{"$in": opt.InProjects}
}
ctx := context.Background()
opts := options.Find()
if opt.IsSortByUpdateTime {
opts.SetSort(bson.D{{"update_time", -1}})
}
if opt.IsSortByProductName {
opts.SetSort(bson.D{{"product_name", 1}})
}
cursor, err := c.Collection.Find(ctx, query, opts)
if err != nil {
return nil, err
}
err = cursor.All(ctx, &ret)
if err != nil {
return nil, err
}
return ret, nil
}
func (c *ProductColl) ListProjectsInNames(names []string) ([]*projectEnvs, error) {
var res []*projectEnvs
var pipeline []bson.M
if len(names) > 0 {
pipeline = append(pipeline, bson.M{"$match": bson.M{"product_name": bson.M{"$in": names}}})
}
pipeline = append(pipeline,
bson.M{
"$group": bson.M{
"_id": bson.M{
"product_name": "$product_name",
},
"project_name": bson.M{"$last": "$product_name"},
"envs": bson.M{"$push": "$env_name"},
},
},
)
cursor, err := c.Aggregate(context.TODO(), pipeline)
if err != nil {
return nil, err
}
if err = cursor.All(context.TODO(), &res); err != nil {
return nil, err
}
return res, nil
}
func (c *ProductColl) UpdateStatus(owner, productName, status string) error {
query := bson.M{"env_name": owner, "product_name": productName}
change := bson.M{"$set": bson.M{
"status": status,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) UpdateErrors(owner, productName, errorMsg string) error {
query := bson.M{"env_name": owner, "product_name": productName}
change := bson.M{"$set": bson.M{
"error": errorMsg,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) UpdateRegistry(envName, productName, registryId string) error {
query := bson.M{"env_name": envName, "product_name": productName}
change := bson.M{"$set": bson.M{
"registry_id": registryId,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) UpdateRender(envName, productName string, render *models.RenderInfo) error {
query := bson.M{"env_name": envName, "product_name": productName}
change := bson.M{"$set": bson.M{
"render": render,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) Delete(owner, productName string) error {
query := bson.M{"env_name": owner, "product_name": productName}
_, err := c.DeleteOne(context.TODO(), query)
return err
}
// Update Cannot update owner & product name
func (c *ProductColl) Update(args *models.Product) error {
query := bson.M{"env_name": args.EnvName, "product_name": args.ProductName}
change := bson.M{"$set": bson.M{
"update_time": time.Now().Unix(),
"services": args.Services,
"status": args.Status,
"revision": args.Revision,
"render": args.Render,
"error": args.Error,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) Create(args *models.Product) error {
// avoid panic issue
if args == nil {
return errors.New("nil Product")
}
now := time.Now().Unix()
args.CreateTime = now
args.UpdateTime = now
_, err := c.InsertOne(context.TODO(), args)
return err
}
func (c *ProductColl) UpdateGroup(envName, productName string, groupIndex int, group []*models.ProductService) error {
serviceGroup := fmt.Sprintf("services.%d", groupIndex)
query := bson.M{
"env_name": envName,
"product_name": productName,
}
change := bson.M{
"update_time": time.Now().Unix(),
serviceGroup: group,
}
_, err := c.UpdateOne(context.TODO(), query, bson.M{"$set": change})
return err
}
func (c *ProductColl) UpdateProductRecycleDay(envName, productName string, recycleDay int) error {
query := bson.M{"env_name": envName, "product_name": productName}
change := bson.M{"$set": bson.M{
"recycle_day": recycleDay,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) UpdateIsPublic(envName, productName string, isPublic bool) error {
query := bson.M{"env_name": envName, "product_name": productName}
change := bson.M{"$set": bson.M{
"update_time": time.Now().Unix(),
"is_public": isPublic,
}}
_, err := c.UpdateOne(context.TODO(), query, change)
return err
}
func (c *ProductColl) Count(productName string) (int, error) {
num, err := c.CountDocuments(context.TODO(), bson.M{"product_name": productName, "status": bson.M{"$ne": setting.ProductStatusDeleting}})
return int(num), err
}
// UpdateAll updates all envs in a bulk write.
// Currently only field `services` is supported.
// Note: A bulk operation can have at most 1000 operations, but the client will do it for us.
// see https://stackoverflow.com/questions/24237887/what-is-mongodb-batch-operation-max-size
func (c *ProductColl) UpdateAll(envs []*models.Product) error {
if len(envs) == 0 {
return nil
}
var ms []mongo.WriteModel
for _, env := range envs {
ms = append(ms,
mongo.NewUpdateOneModel().
SetFilter(bson.D{{"_id", env.ID}}).
SetUpdate(bson.D{{"$set", bson.D{{"services", env.Services}}}}),
)
}
_, err := c.BulkWrite(context.TODO(), ms)
return err
}