/
collectionresource_storage.go
68 lines (53 loc) · 1.96 KB
/
collectionresource_storage.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
package internalstorage
import (
"context"
"gorm.io/gorm"
"k8s.io/apimachinery/pkg/apis/meta/v1/unstructured"
"k8s.io/apimachinery/pkg/runtime"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/runtime/serializer/json"
internal "github.com/clusterpedia-io/clusterpedia/pkg/apis/clusterpedia"
)
var caseSensitiveJSONIterator = json.CaseSensitiveJSONIterator()
type CollectionResourceStorage struct {
db *gorm.DB
collectionResource *internal.CollectionResource
}
func (s *CollectionResourceStorage) Get(ctx context.Context, opts *internal.ListOptions) (*internal.CollectionResource, error) {
cr := s.collectionResource.DeepCopy()
types := make(map[schema.GroupResource]*internal.CollectionResourceType, len(cr.ResourceTypes))
var typesQuery = s.db
for i, rt := range cr.ResourceTypes {
typesQuery = typesQuery.Or(map[string]interface{}{
"group": rt.Group,
"version": rt.Version,
"resource": rt.Resource,
})
types[rt.GroupResource()] = &cr.ResourceTypes[i]
}
query := s.db.WithContext(ctx).Model(&Resource{}).Where(typesQuery)
_, query, err := applyListOptionsToCollectionResourceQuery(query, opts)
if err != nil {
return nil, err
}
var resources []Resource
result := query.Find(&resources)
if result.Error != nil {
return nil, InterpreError(s.collectionResource.Name, result.Error)
}
objs := make([]runtime.Object, 0, len(resources))
for _, resource := range resources {
types[resource.GroupVersionResource().GroupResource()].Kind = resource.Kind
obj := &unstructured.Unstructured{}
if err := caseSensitiveJSONIterator.Unmarshal(resource.Object, obj); err != nil {
return nil, InterpreError(s.collectionResource.Name, err)
}
objs = append(objs, obj)
}
cr.Items = objs
return cr, nil
}
// TODO(iceber): support with remaining count and continue
func applyListOptionsToCollectionResourceQuery(query *gorm.DB, opts *internal.ListOptions) (int64, *gorm.DB, error) {
return applyListOptionsToQuery(query, opts, nil)
}