-
Notifications
You must be signed in to change notification settings - Fork 38
/
types.go
258 lines (224 loc) · 7.38 KB
/
types.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
// Copyright The Karpor 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 storage
import (
"bytes"
"context"
"fmt"
"strings"
"time"
"github.com/KusionStack/karpor/pkg/core/entity"
"gopkg.in/yaml.v2"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
yamlutil "k8s.io/apimachinery/pkg/util/yaml"
)
const (
Equals = "="
DSLPatternType = "dsl"
SQLPatternType = "sql"
)
// Storage interface defines the basic operations for storage.
type Storage interface {
ResourceStorage
ResourceGroupRuleStorage
SearchStorage
}
// ResourceStorage interface defines the basic operations for resource storage.
type ResourceStorage interface {
GetResource(ctx context.Context, cluster string, obj runtime.Object) error
SaveResource(ctx context.Context, cluster string, obj runtime.Object) error
DeleteResource(ctx context.Context, cluster string, obj runtime.Object) error
DeleteAllResources(ctx context.Context, cluster string) error
CountResources(ctx context.Context) (int, error)
}
// ResourceGroupRuleStorage interface defines the basic operations for resource
// group rule storage.
type ResourceGroupRuleStorage interface {
GetResourceGroupRule(ctx context.Context, name string) (*entity.ResourceGroupRule, error)
SaveResourceGroupRule(ctx context.Context, data *entity.ResourceGroupRule) error
DeleteResourceGroupRule(ctx context.Context, name string) error
ListResourceGroupRules(ctx context.Context) ([]*entity.ResourceGroupRule, error)
CountResourceGroupRules(ctx context.Context) (int, error)
ListResourceGroupsBy(ctx context.Context, ruleName string) (*ResourceGroupResult, error)
}
// SearchStorage interface defines the basic operations for search storage.
type SearchStorage interface {
Search(ctx context.Context, queryString, patternType string, pagination *Pagination) (*SearchResult, error)
SearchByTerms(ctx context.Context, keysAndValues map[string]any, pagination *Pagination) (*SearchResult, error)
AggregateByTerms(ctx context.Context, keys []string) (*AggregateResults, error)
}
type SearchStorageGetter interface {
GetSearchStorage() (SearchStorage, error)
}
type ResourceStorageGetter interface {
GetResourceStorage() (ResourceStorage, error)
}
type ResourceGroupRuleStorageGetter interface {
GetResourceGroupRuleStorage() (ResourceGroupRuleStorage, error)
}
// Query represents the query parameters for searching resources.
type Query struct {
Key string
Values []string
Operator string
}
// Pagination defines the parameters for pagination in search results.
type Pagination struct {
Page int
PageSize int
}
// SearchResult contains the search results and total count.
type SearchResult struct {
Total int
Resources []*Resource
}
// AggregateResults is assumed to be a struct that holds aggregation results.
type AggregateResults struct {
Buckets []Bucket
Total int
}
// Bucket is assumed to be a struct that holds individual bucket data.
type Bucket struct {
Keys []string
Count int
}
type ResourceGroupResult struct {
Groups []*entity.ResourceGroup `json:"groups" yaml:"groups"`
Fields []string `json:"fields" yaml:"fields"`
}
// Overview returns a brief summary of the search result.
func (r *SearchResult) Overview() string {
var sb strings.Builder
sb.WriteString(fmt.Sprintf("Total: %d\n", r.Total))
sb.WriteString("Resources:\n")
for _, res := range r.Resources {
sb.WriteString(fmt.Sprintf("- Cluster: %s, Namespace: %s, Kind: %s, Name: %s\n",
res.Cluster, res.Namespace, res.Kind, res.Name))
}
return sb.String()
}
// ToYAML returns the search result in YAML format.
func (r *SearchResult) ToYAML() (string, error) {
if len(r.Resources) == 0 {
return "", nil
}
var yamlString string
for _, res := range r.Resources {
resYAML, err := yaml.Marshal(res.Object)
if err != nil {
return "", err
}
yamlString += string(resYAML) + "\n---\n"
}
return yamlString, nil
}
// Resource represents a Kubernetes resource with additional metadata.
type Resource struct {
entity.ResourceGroup `json:",inline" yaml:",inline"`
Object map[string]interface{} `json:"object"`
}
// NewResource creates a new Resource instance based on the provided bytes
// and cluster. It decodes the YAML bytes into an unstructured object and
// constructs a Resource with the relevant fields.
func NewResource(cluster string, b []byte) (*Resource, error) {
// Ensure the cluster name is not empty.
if len(cluster) == 0 {
return nil, fmt.Errorf("cluster cannot be empty")
}
// Initialize an unstructured object for decoding data.
obj := &unstructured.Unstructured{}
// Create a YAML or JSON decoder with the provided bytes.
decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewReader(b), len(b))
if err := decoder.Decode(obj); err != nil {
return nil, err
}
// Build and return the Resource object with decoded data and cluster info.
return &Resource{
ResourceGroup: entity.ResourceGroup{
Cluster: cluster,
Namespace: obj.GetNamespace(),
APIVersion: obj.GetAPIVersion(),
Kind: obj.GetKind(),
Name: obj.GetName(),
},
Object: obj.Object,
}, nil
}
// Map2Resource converts a map to a Resource object.
func Map2Resource(in map[string]interface{}) (*Resource, error) {
out := &Resource{}
out.Cluster = in["cluster"].(string)
out.APIVersion = in["apiVersion"].(string)
out.Kind = in["kind"].(string)
out.Namespace = in["namespace"].(string)
out.Name = in["name"].(string)
content := in["content"].(string)
obj := &unstructured.Unstructured{}
decoder := yamlutil.NewYAMLOrJSONDecoder(bytes.NewBufferString(content), len(content))
if err := decoder.Decode(obj); err != nil {
return nil, err
}
out.Object = obj.Object
return out, nil
}
// Map2ResourceGroupRule converts a map to a ResourceGroupRule object.
func Map2ResourceGroupRule(in map[string]interface{}) (*entity.ResourceGroupRule, error) {
out := &entity.ResourceGroupRule{}
out.ID = toString(in["id"])
out.Name = toString(in["name"])
out.Description = toString(in["description"])
fields := in["fields"].([]interface{})
out.Fields = make([]string, len(fields))
for i, field := range fields {
out.Fields[i] = toString(field)
}
var err error
if out.CreatedAt, err = toTime(in["createdAt"]); err != nil {
return nil, err
}
if out.UpdatedAt, err = toTime(in["updatedAt"]); err != nil {
return nil, err
}
if out.DeletedAt, err = toTime(in["deletedAt"]); err != nil {
return nil, err
}
return out, nil
}
//nolint:nilnil
func toTime(in interface{}) (*metav1.Time, error) {
if in == nil {
return nil, nil
}
s, ok := in.(string)
if !ok {
return nil, fmt.Errorf("expected input to be a string, got %T", in)
}
t, err := time.ParseInLocation(time.RFC3339, s, time.UTC)
if err != nil {
return nil, err
}
return &metav1.Time{Time: t}, nil
}
func toString(in interface{}) string {
if in == nil {
return ""
}
rt, ok := in.(string)
if !ok {
return ""
}
return rt
}