nodes.go 8.1 KB
Newer Older
H
hongming 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
/*
Copyright 2019 The KubeSphere 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.
*/

Z
zryfish 已提交
17 18 19 20 21 22 23 24 25 26 27 28 29
package node

import (
	"fmt"
	v1 "k8s.io/api/core/v1"
	"k8s.io/apimachinery/pkg/api/resource"
	"k8s.io/apimachinery/pkg/labels"
	"k8s.io/apimachinery/pkg/runtime"
	"k8s.io/client-go/informers"
	resourceheper "k8s.io/kubectl/pkg/util/resource"
	"kubesphere.io/kubesphere/pkg/api"
	"kubesphere.io/kubesphere/pkg/apiserver/query"
	"kubesphere.io/kubesphere/pkg/models/resources/v1alpha3"
30
	"sort"
Z
zryfish 已提交
31 32 33 34
)

// Those annotations were added to node only for display purposes
const (
H
hongming 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47
	nodeCPURequests                                 = "node.kubesphere.io/cpu-requests"
	nodeMemoryRequests                              = "node.kubesphere.io/memory-requests"
	nodeCPULimits                                   = "node.kubesphere.io/cpu-limits"
	nodeMemoryLimits                                = "node.kubesphere.io/memory-limits"
	nodeCPURequestsFraction                         = "node.kubesphere.io/cpu-requests-fraction"
	nodeCPULimitsFraction                           = "node.kubesphere.io/cpu-limits-fraction"
	nodeMemoryRequestsFraction                      = "node.kubesphere.io/memory-requests-fraction"
	nodeMemoryLimitsFraction                        = "node.kubesphere.io/memory-limits-fraction"
	nodeConfigOK               v1.NodeConditionType = "ConfigOK"
	nodeKubeletReady           v1.NodeConditionType = "KubeletReady"
	statusRunning                                   = "running"
	statusWarning                                   = "warning"
	statusUnschedulable                             = "unschedulable"
Z
zryfish 已提交
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
)

type nodesGetter struct {
	informers informers.SharedInformerFactory
}

func New(informers informers.SharedInformerFactory) v1alpha3.Interface {
	return &nodesGetter{
		informers: informers,
	}
}

func (c nodesGetter) Get(_, name string) (runtime.Object, error) {
	node, err := c.informers.Core().V1().Nodes().Lister().Get(name)
	if err != nil {
		return nil, err
	}

	// ignore the error, skip annotating process if error happened
	pods, _ := c.informers.Core().V1().Pods().Lister().Pods("").List(labels.Everything())
	c.annotateNode(node, pods)

	return node, nil
}

73 74
func (c nodesGetter) List(_ string, q *query.Query) (*api.ListResult, error) {
	nodes, err := c.informers.Core().V1().Nodes().Lister().List(q.Selector())
Z
zryfish 已提交
75 76 77 78
	if err != nil {
		return nil, err
	}

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
	var filtered []*v1.Node
	for _, object := range nodes {
		selected := true
		for field, value := range q.Filters {
			if !c.filter(object, query.Filter{Field: field, Value: value}) {
				selected = false
				break
			}
		}

		if selected {
			filtered = append(filtered, object)
		}
	}

	// sort by sortBy field
	sort.Slice(filtered, func(i, j int) bool {
		if !q.Ascending {
			return c.compare(filtered[i], filtered[j], q.SortBy)
		}
		return !c.compare(filtered[i], filtered[j], q.SortBy)
	})

	total := len(filtered)
	if q.Pagination == nil {
		q.Pagination = query.NoPagination
	}
	start, end := q.Pagination.GetValidPagination(total)
	selectedNodes := filtered[start:end]

Z
zryfish 已提交
109
	// ignore the error, skip annotating process if error happened
110
	pods, _ := c.informers.Core().V1().Pods().Lister().Pods("").List(labels.Everything())
Z
zryfish 已提交
111 112 113 114 115 116 117
	var nonTerminatedPodsList []*v1.Pod
	for _, pod := range pods {
		if pod.Status.Phase != v1.PodSucceeded && pod.Status.Phase != v1.PodFailed {
			nonTerminatedPodsList = append(nonTerminatedPodsList, pod)
		}
	}

118 119
	var result []interface{}
	for _, node := range selectedNodes {
Z
zryfish 已提交
120 121 122 123
		c.annotateNode(node, nonTerminatedPodsList)
		result = append(result, node)
	}

124 125 126 127
	return &api.ListResult{
		TotalItems: total,
		Items:      result,
	}, nil
Z
zryfish 已提交
128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
}

func (c nodesGetter) compare(left runtime.Object, right runtime.Object, field query.Field) bool {
	leftNode, ok := left.(*v1.Node)
	if !ok {
		return false
	}

	rightNode, ok := right.(*v1.Node)
	if !ok {
		return false
	}

	return v1alpha3.DefaultObjectMetaCompare(leftNode.ObjectMeta, rightNode.ObjectMeta, field)
}

func (c nodesGetter) filter(object runtime.Object, filter query.Filter) bool {
H
hongming 已提交
145
	node, ok := object.(*v1.Node)
Z
zryfish 已提交
146 147 148
	if !ok {
		return false
	}
H
hongming 已提交
149 150 151 152
	switch filter.Field {
	case query.FieldStatus:
		return getNodeStatus(node) == string(filter.Value)
	}
Z
zryfish 已提交
153

H
hongming 已提交
154
	return v1alpha3.DefaultObjectMetaFilter(node.ObjectMeta, filter)
Z
zryfish 已提交
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
}

// annotateNode adds cpu/memory requests usage data to node's annotations
func (c nodesGetter) annotateNode(node *v1.Node, pods []*v1.Pod) {
	if len(pods) == 0 {
		return
	}

	var nodePods []*v1.Pod
	for _, pod := range pods {
		if pod.Spec.NodeName == node.Name {
			nodePods = append(nodePods, pod)
		}
	}

	reqs, limits := c.getPodsTotalRequestAndLimits(nodePods)

	if node.Annotations == nil {
		node.Annotations = make(map[string]string)
	}

	cpuReqs, cpuLimits, memoryReqs, memoryLimits := reqs[v1.ResourceCPU], limits[v1.ResourceCPU], reqs[v1.ResourceMemory], limits[v1.ResourceMemory]
	node.Annotations[nodeCPURequests] = cpuReqs.String()
	node.Annotations[nodeCPULimits] = cpuLimits.String()
	node.Annotations[nodeMemoryRequests] = memoryReqs.String()
	node.Annotations[nodeMemoryLimits] = memoryLimits.String()

	fractionCpuReqs, fractionCpuLimits := float64(0), float64(0)
	allocatable := node.Status.Allocatable
	if allocatable.Cpu().MilliValue() != 0 {
		fractionCpuReqs = float64(cpuReqs.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100
		fractionCpuLimits = float64(cpuLimits.MilliValue()) / float64(allocatable.Cpu().MilliValue()) * 100
	}
	fractionMemoryReqs, fractionMemoryLimits := float64(0), float64(0)
	if allocatable.Memory().Value() != 0 {
		fractionMemoryReqs = float64(memoryReqs.Value()) / float64(allocatable.Memory().Value()) * 100
		fractionMemoryLimits = float64(memoryLimits.Value()) / float64(allocatable.Memory().Value()) * 100
	}

	node.Annotations[nodeCPURequestsFraction] = fmt.Sprintf("%d%%", int(fractionCpuReqs))
	node.Annotations[nodeCPULimitsFraction] = fmt.Sprintf("%d%%", int(fractionCpuLimits))
	node.Annotations[nodeMemoryRequestsFraction] = fmt.Sprintf("%d%%", int(fractionMemoryReqs))
	node.Annotations[nodeMemoryLimitsFraction] = fmt.Sprintf("%d%%", int(fractionMemoryLimits))
}

func (c nodesGetter) getPodsTotalRequestAndLimits(pods []*v1.Pod) (reqs map[v1.ResourceName]resource.Quantity, limits map[v1.ResourceName]resource.Quantity) {
	reqs, limits = map[v1.ResourceName]resource.Quantity{}, map[v1.ResourceName]resource.Quantity{}
	for _, pod := range pods {
		podReqs, podLimits := resourceheper.PodRequestsAndLimits(pod)
		for podReqName, podReqValue := range podReqs {
			if value, ok := reqs[podReqName]; !ok {
				reqs[podReqName] = podReqValue.DeepCopy()
			} else {
				value.Add(podReqValue)
				reqs[podReqName] = value
			}
		}
		for podLimitName, podLimitValue := range podLimits {
			if value, ok := limits[podLimitName]; !ok {
				limits[podLimitName] = podLimitValue.DeepCopy()
			} else {
				value.Add(podLimitValue)
				limits[podLimitName] = value
			}
		}
	}
	return
}
H
hongming 已提交
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

func getNodeStatus(node *v1.Node) string {
	if node.Spec.Unschedulable {
		return statusUnschedulable
	}
	for _, condition := range node.Status.Conditions {
		if isUnhealthyStatus(condition) {
			return statusWarning
		}
	}

	return statusRunning
}

var expectedConditions = map[v1.NodeConditionType]v1.ConditionStatus{
	v1.NodeMemoryPressure:     v1.ConditionFalse,
	v1.NodeDiskPressure:       v1.ConditionFalse,
	v1.NodePIDPressure:        v1.ConditionFalse,
	v1.NodeNetworkUnavailable: v1.ConditionFalse,
	nodeConfigOK:              v1.ConditionTrue,
	nodeKubeletReady:          v1.ConditionTrue,
	v1.NodeReady:              v1.ConditionTrue,
}

func isUnhealthyStatus(condition v1.NodeCondition) bool {
	expectedStatus := expectedConditions[condition.Type]
	if expectedStatus != "" && condition.Status != expectedStatus {
		return true
	}
	return false
}