resource.go 2.1 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
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
H
hongming 已提交
10
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/application"
Z
zryfish 已提交
11
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/deployment"
H
hongming 已提交
12
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3/namespace"
Z
zryfish 已提交
13 14 15 16
)

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

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

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

Z
zryfish 已提交
24
	getters[schema.GroupVersionResource{Group: "apps", Version: "v1", Resource: "deployments"}] = deployment.New(factory.KubernetesSharedInformerFactory())
H
hongming 已提交
25
	getters[schema.GroupVersionResource{Group: "", Version: "v1", Resource: "namespaces"}] = namespace.New(factory.KubernetesSharedInformerFactory())
H
hongming 已提交
26
	getters[schema.GroupVersionResource{Group: "app.k8s.io", Version: "v1beta1", Resource: "applications"}] = application.New(factory.ApplicationSharedInformerFactory())
Z
zryfish 已提交
27

H
hongming 已提交
28
	return &ResourceGetter{
Z
zryfish 已提交
29 30 31 32 33 34
		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 已提交
35
func (r *ResourceGetter) tryResource(resource string) v1alpha3.Interface {
Z
zryfish 已提交
36 37 38 39 40 41 42 43 44
	for k, v := range r.getters {
		if k.Resource == resource {
			return v
		}
	}

	return nil
}

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

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