resource.go 1.8 KB
Newer Older
Z
zryfish 已提交
1 2 3 4 5 6 7
package resource

import (
	"errors"
	"k8s.io/apimachinery/pkg/runtime/schema"
	"kubesphere.io/kubesphere/pkg/api"
	"kubesphere.io/kubesphere/pkg/apiserver/query"
Z
zryfish 已提交
8
	"kubesphere.io/kubesphere/pkg/informers"
Z
zryfish 已提交
9 10
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/deployment"
H
hongming 已提交
11
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/namespace"
Z
zryfish 已提交
12 13 14 15
)

var ErrResourceNotSupported = errors.New("resource is not supported")

H
hongming 已提交
16
type ResourceGetter struct {
Z
zryfish 已提交
17 18 19
	getters map[schema.GroupVersionResource]v1alpha3.Interface
}

H
hongming 已提交
20
func New(factory informers.InformerFactory) *ResourceGetter {
Z
zryfish 已提交
21 22
	getters := make(map[schema.GroupVersionResource]v1alpha3.Interface)

Z
zryfish 已提交
23
	getters[schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}] = deployment.New(factory.KubernetesSharedInformerFactory())
H
hongming 已提交
24
	getters[schema.GroupVersionResource{Group: "", Version: "v1", Resource: "namespaces"}] = namespace.New(factory.KubernetesSharedInformerFactory())
Z
zryfish 已提交
25

H
hongming 已提交
26
	return &ResourceGetter{
Z
zryfish 已提交
27 28 29 30 31 32
		getters: getters,
	}
}

// tryResource will retrieve a getter with resource name, it doesn't guarantee find resource with correct group version
// need to refactor this use schema.GroupVersionResource
H
hongming 已提交
33
func (r *ResourceGetter) tryResource(resource string) v1alpha3.Interface {
Z
zryfish 已提交
34 35 36 37 38 39 40 41 42
	for k, v := range r.getters {
		if k.Resource == resource {
			return v
		}
	}

	return nil
}

H
hongming 已提交
43
func (r *ResourceGetter) Get(resource, namespace, name string) (interface{}, error) {
Z
zryfish 已提交
44 45 46 47 48 49 50
	getter := r.tryResource(resource)
	if getter == nil {
		return nil, ErrResourceNotSupported
	}
	return getter.Get(namespace, name)
}

H
hongming 已提交
51
func (r *ResourceGetter) List(resource, namespace string, query *query.Query) (*api.ListResult, error) {
Z
zryfish 已提交
52 53 54 55
	getter := r.tryResource(resource)
	if getter == nil {
		return nil, ErrResourceNotSupported
	}
Z
zryfish 已提交
56
	return getter.List(namespace, query)
Z
zryfish 已提交
57
}