-
Notifications
You must be signed in to change notification settings - Fork 259
Expand file tree
/
Copy pathoperationlog.go
More file actions
315 lines (272 loc) · 8.56 KB
/
operationlog.go
File metadata and controls
315 lines (272 loc) · 8.56 KB
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
/*
* Tencent is pleased to support the open source community by making Blueking Container Service available.
* Copyright (C) 2019 THL A29 Limited, a Tencent company. All rights reserved.
* Licensed under the MIT License (the "License"); you may not use this file except
* in compliance with the License. You may obtain a copy of the License at
* http://opensource.org/licenses/MIT
* 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 operationlog xxx
package operationlog
import (
"context"
"fmt"
"sync"
"github.com/Tencent/bk-bcs/bcs-common/common/blog"
"github.com/Tencent/bk-bcs/bcs-common/pkg/odm/drivers"
"github.com/Tencent/bk-bcs/bcs-common/pkg/odm/operator"
"go.mongodb.org/mongo-driver/bson"
types "github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/api/clustermanager"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/store/options"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/store/task"
"github.com/Tencent/bk-bcs/bcs-services/bcs-cluster-manager/internal/store/util"
)
const (
tableName = "operationlog"
defaultLogListLength = 3000
resourceType = "resourcetype"
resourceID = "resourceid"
taskID = "taskid"
createTime = "createtime"
clusterID = "clusterid"
// 索引名称常量
indexNameMainQuery = "idx_main_query"
indexNameClusterTime = "idx_cluster_time"
)
// ModelOperationLog database operation for operation_log
type ModelOperationLog struct {
tableName string
indexes []drivers.Index
db drivers.DB
isTableEnsured bool
isTableEnsuredMutex sync.RWMutex
}
var (
operationLogIndexes = []drivers.Index{
{
Name: indexNameMainQuery,
Key: bson.D{
bson.E{Key: clusterID, Value: 1},
bson.E{Key: resourceType, Value: 1},
bson.E{Key: resourceID, Value: 1},
bson.E{Key: createTime, Value: -1},
},
Unique: false,
},
{
Name: indexNameClusterTime,
Key: bson.D{
bson.E{Key: clusterID, Value: 1},
bson.E{Key: createTime, Value: -1},
},
Unique: false,
},
}
)
// New create operationLog model
func New(db drivers.DB) *ModelOperationLog {
return &ModelOperationLog{
tableName: util.DataTableNamePrefix + tableName,
db: db,
indexes: operationLogIndexes,
}
}
// ensure table
func (m *ModelOperationLog) ensureTable(ctx context.Context) error {
m.isTableEnsuredMutex.RLock()
if m.isTableEnsured {
m.isTableEnsuredMutex.RUnlock()
return nil
}
if err := util.EnsureTable(ctx, m.db, m.tableName, m.indexes); err != nil {
m.isTableEnsuredMutex.RUnlock()
return err
}
m.isTableEnsuredMutex.RUnlock()
m.isTableEnsuredMutex.Lock()
m.isTableEnsured = true
m.isTableEnsuredMutex.Unlock()
return nil
}
// CreateOperationLog create operation log
func (m *ModelOperationLog) CreateOperationLog(ctx context.Context, log *types.OperationLog) error {
if log == nil {
return fmt.Errorf("log to be created cannot be empty")
}
if err := m.ensureTable(ctx); err != nil {
return err
}
if _, err := m.db.Table(m.tableName).Insert(ctx, []interface{}{log}); err != nil {
return err
}
return nil
}
// DeleteOperationLogByResourceID delete operationLog
func (m *ModelOperationLog) DeleteOperationLogByResourceID(ctx context.Context, resourceIndex string) error {
if err := m.ensureTable(ctx); err != nil {
return err
}
cond := operator.NewLeafCondition(operator.Eq, operator.M{
resourceID: resourceIndex,
})
deleteCounter, err := m.db.Table(m.tableName).Delete(ctx, cond)
if err != nil {
return err
}
if deleteCounter == 0 {
blog.Warnf("no operationLog delete with resourceID %s", resourceIndex)
}
return nil
}
// DeleteOperationLogByResourceType delete operationLog
func (m *ModelOperationLog) DeleteOperationLogByResourceType(ctx context.Context, resType string) error {
if err := m.ensureTable(ctx); err != nil {
return err
}
cond := operator.NewLeafCondition(operator.Eq, operator.M{
resourceType: resType,
})
deleteCounter, err := m.db.Table(m.tableName).Delete(ctx, cond)
if err != nil {
return err
}
if deleteCounter == 0 {
blog.Warnf("no operationLog delete with resourceType %s", resType)
}
return nil
}
// DeleteOperationLogByDate delete operationLog by date
func (m *ModelOperationLog) DeleteOperationLogByDate(ctx context.Context, startTime, endTime string) error {
if err := m.ensureTable(ctx); err != nil {
return err
}
startCond := operator.NewLeafCondition(operator.Gte, operator.M{createTime: startTime})
endCond := operator.NewLeafCondition(operator.Lte, operator.M{createTime: endTime})
cond := operator.NewBranchCondition(operator.And, startCond, endCond)
deleteCounter, err := m.db.Table(m.tableName).Delete(ctx, cond)
if err != nil {
return err
}
if deleteCounter == 0 {
blog.Warnf("no operationLog delete with startTime: %s - endTime: %s", startTime, endTime)
}
return nil
}
// ListOperationLog list logs
func (m *ModelOperationLog) ListOperationLog(ctx context.Context, cond *operator.Condition, opt *options.ListOption) (
[]*types.OperationLog, error) {
logList := make([]*types.OperationLog, 0)
finder := m.db.Table(m.tableName).Find(cond)
if len(opt.Sort) != 0 {
finder = finder.WithSort(util.MapInt2MapIf(opt.Sort))
}
if opt.Offset != 0 {
finder = finder.WithStart(opt.Offset)
}
if opt.Limit == 0 {
finder = finder.WithLimit(defaultLogListLength)
} else {
finder = finder.WithLimit(opt.Limit)
}
if opt.All {
finder = finder.WithLimit(0)
}
if err := finder.All(ctx, &logList); err != nil {
return nil, err
}
return logList, nil
}
// CountOperationLog count operationLog
func (m *ModelOperationLog) CountOperationLog(ctx context.Context, cond *operator.Condition) (
int64, error) {
return m.db.Table(m.tableName).Find(cond).Count(ctx)
}
// ListAggreOperationLog aggre logs
func (m *ModelOperationLog) ListAggreOperationLog(ctx context.Context, condSrc, condDst []bson.E,
opt *options.ListOption) (
[]*types.TaskOperationLog, error) {
retTaskOpLogs := make([]*types.TaskOperationLog, 0)
const (
asField = "task"
)
pipeline := make([]map[string]interface{}, 0)
aggreOptions := make(map[string]interface{})
// 根据查询条件自动选择合适的索引
indexHint := m.selectIndexHint(condSrc)
if indexHint != "" {
aggreOptions["hint"] = indexHint
}
// from src table filter
if len(condSrc) > 0 {
pipeline = append(pipeline, util.BuildMatchCond(util.TransBsonEToMap(condSrc)))
}
pipeline = append(pipeline, util.BuildLookUpCond(util.UnionTable{
DstTable: util.DataTableNamePrefix + task.TableName,
FromFields: taskID,
DstFields: taskID,
AsField: asField,
}))
pipeline = append(pipeline, util.BuildUnWindCond(asField))
pipeline = append(pipeline, util.BuildProjectOutput(util.BuildTaskOperationLogProject()))
// from dst table filter
if len(condDst) > 0 {
pipeline = append(pipeline, util.BuildMatchCond(util.TransBsonEToMap(condDst)))
}
if len(opt.Sort) != 0 {
pipeline = append(pipeline, map[string]interface{}{
"$sort": util.MapInt2MapIf(opt.Sort),
})
}
// count logs for conds
if opt.Count {
if err := m.db.Table(m.tableName).AggregationWithOptions(ctx, pipeline, aggreOptions, &retTaskOpLogs); err != nil {
return nil, err
}
return retTaskOpLogs, nil
}
if opt.Offset >= 0 {
pipeline = append(pipeline, map[string]interface{}{
"$skip": opt.Offset,
})
}
if opt.Limit == 0 {
pipeline = append(pipeline, map[string]interface{}{
"$limit": 50,
})
} else {
pipeline = append(pipeline, map[string]interface{}{
"$limit": opt.Limit,
})
}
if err := m.db.Table(m.tableName).AggregationWithOptions(ctx, pipeline, aggreOptions, &retTaskOpLogs); err != nil {
return nil, err
}
return retTaskOpLogs, nil
}
// selectIndexHint 根据查询条件选择合适的索引hint
func (m *ModelOperationLog) selectIndexHint(condSrc []bson.E) string {
// 分析查询条件,选择最优索引
hasResourceType := false
hasClusterID := false
for _, cond := range condSrc {
switch cond.Key {
case resourceType:
hasResourceType = true
case clusterID:
hasClusterID = true
}
}
// 索引选择策略:
// 1. 如果有clusterID + resourceType,使用主索引
// 2. 如果只有clusterID,使用clusterID索引
// 3. 其他情况使用默认索引(让MongoDB自动选择)
if hasClusterID && hasResourceType {
return indexNameMainQuery
} else if hasClusterID {
return indexNameClusterTime
}
return ""
}