namespaces.go 1.9 KB
Newer Older
Z
zryfish 已提交
1 2 3
package namespace

import (
R
runzexia 已提交
4 5 6 7 8 9 10 11
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/informers"
	"kubesphere.io/kubesphere/pkg/api"
	"kubesphere.io/kubesphere/pkg/apiserver/query"
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
	"strings"
Z
zryfish 已提交
12 13 14
)

type namespaceGetter struct {
R
runzexia 已提交
15
	informers informers.SharedInformerFactory
Z
zryfish 已提交
16 17 18
}

func NewNamespaceGetter(informers informers.SharedInformerFactory) v1alpha3.Interface {
R
runzexia 已提交
19
	return &namespaceGetter{informers: informers}
Z
zryfish 已提交
20 21 22
}

func (n namespaceGetter) Get(_, name string) (runtime.Object, error) {
R
runzexia 已提交
23
	return n.informers.Core().V1().Namespaces().Lister().Get(name)
Z
zryfish 已提交
24 25 26
}

func (n namespaceGetter) List(_ string, query *query.Query) (*api.ListResult, error) {
R
runzexia 已提交
27 28 29 30
	ns, err := n.informers.Core().V1().Namespaces().Lister().List(labels.Everything())
	if err != nil {
		return nil, err
	}
Z
zryfish 已提交
31

R
runzexia 已提交
32 33 34 35
	var result []runtime.Object
	for _, item := range ns {
		result = append(result, item)
	}
Z
zryfish 已提交
36

R
runzexia 已提交
37
	return v1alpha3.DefaultList(result, query, n.compare, n.filter), nil
Z
zryfish 已提交
38 39 40
}

func (n namespaceGetter) filter(item runtime.Object, filter query.Filter) bool {
R
runzexia 已提交
41 42 43 44
	namespace, ok := item.(*v1.Namespace)
	if !ok {
		return false
	}
Z
zryfish 已提交
45

R
runzexia 已提交
46 47 48 49 50 51 52 53
	switch filter.Field {
	case query.FieldName:
		return query.ComparableString(namespace.Name).Contains(filter.Value)
	case query.FieldStatus:
		return query.ComparableString(namespace.Status.Phase).Compare(filter.Value) == 0
	default:
		return false
	}
Z
zryfish 已提交
54 55 56
}

func (n namespaceGetter) compare(left runtime.Object, right runtime.Object, field query.Field) bool {
R
runzexia 已提交
57 58 59 60
	leftNs, ok := left.(*v1.Namespace)
	if !ok {
		return false
	}
Z
zryfish 已提交
61

R
runzexia 已提交
62 63 64 65
	rightNs, ok := right.(*v1.Namespace)
	if !ok {
		return true
	}
Z
zryfish 已提交
66

R
runzexia 已提交
67 68 69 70 71 72 73 74 75
	switch field {
	case query.FieldName:
		return strings.Compare(leftNs.Name, rightNs.Name) > 0
	case query.FieldCreationTimeStamp:
		return leftNs.CreationTimestamp.After(rightNs.CreationTimestamp.Time)
	default:
		return false
	}
}