detail.go 11.8 KB
Newer Older
1
// Copyright 2017 The Kubernetes Authors.
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
//
// 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.

package node

import (
	"log"

20
	"github.com/kubernetes/dashboard/src/app/backend/api"
21
	"github.com/kubernetes/dashboard/src/app/backend/errors"
22
	metricapi "github.com/kubernetes/dashboard/src/app/backend/integration/metric/api"
23
	"github.com/kubernetes/dashboard/src/app/backend/resource/common"
B
Batikan Urcan 已提交
24
	"github.com/kubernetes/dashboard/src/app/backend/resource/dataselect"
25 26
	"github.com/kubernetes/dashboard/src/app/backend/resource/event"
	"github.com/kubernetes/dashboard/src/app/backend/resource/pod"
27
	v1 "k8s.io/api/core/v1"
S
Sebastian Florek 已提交
28 29 30 31
	"k8s.io/apimachinery/pkg/api/resource"
	metaV1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/apimachinery/pkg/fields"
	k8sClient "k8s.io/client-go/kubernetes"
32 33
)

34 35 36 37 38 39 40 41 42 43 44 45
// NodeAllocatedResources describes node allocated resources.
type NodeAllocatedResources struct {
	// CPURequests is number of allocated milicores.
	CPURequests int64 `json:"cpuRequests"`

	// CPURequestsFraction is a fraction of CPU, that is allocated.
	CPURequestsFraction float64 `json:"cpuRequestsFraction"`

	// CPULimits is defined CPU limit.
	CPULimits int64 `json:"cpuLimits"`

	// CPULimitsFraction is a fraction of defined CPU limit, can be over 100%, i.e.
M
Marcin Maciaszczyk 已提交
46
	// overcommitted.
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
	CPULimitsFraction float64 `json:"cpuLimitsFraction"`

	// CPUCapacity is specified node CPU capacity in milicores.
	CPUCapacity int64 `json:"cpuCapacity"`

	// MemoryRequests is a fraction of memory, that is allocated.
	MemoryRequests int64 `json:"memoryRequests"`

	// MemoryRequestsFraction is a fraction of memory, that is allocated.
	MemoryRequestsFraction float64 `json:"memoryRequestsFraction"`

	// MemoryLimits is defined memory limit.
	MemoryLimits int64 `json:"memoryLimits"`

	// MemoryLimitsFraction is a fraction of defined memory limit, can be over 100%, i.e.
M
Marcin Maciaszczyk 已提交
62
	// overcommitted.
63 64 65 66 67 68 69 70 71 72
	MemoryLimitsFraction float64 `json:"memoryLimitsFraction"`

	// MemoryCapacity is specified node memory capacity in bytes.
	MemoryCapacity int64 `json:"memoryCapacity"`

	// AllocatedPods in number of currently allocated pods on the node.
	AllocatedPods int `json:"allocatedPods"`

	// PodCapacity is maximum number of pods, that can be allocated on the node.
	PodCapacity int64 `json:"podCapacity"`
73 74 75

	// PodFraction is a fraction of pods, that can be allocated on given node.
	PodFraction float64 `json:"podFraction"`
76 77
}

78 79 80
// NodeDetail is a presentation layer view of Kubernetes Node resource. This means it is Node plus
// additional augmented data we can get from other sources.
type NodeDetail struct {
81 82
	// Extends list item structure.
	Node `json:",inline"`
83

84
	// NodePhase is the current lifecycle phase of the node.
85
	Phase v1.NodePhase `json:"phase"`
86

87 88 89 90 91 92 93 94 95 96
	// PodCIDR represents the pod IP range assigned to the node.
	PodCIDR string `json:"podCIDR"`

	// ID of the node assigned by the cloud provider.
	ProviderID string `json:"providerID"`

	// Unschedulable controls node schedulability of new pods. By default node is schedulable.
	Unschedulable bool `json:"unschedulable"`

	// Set of ids/uuids to uniquely identify the node.
97
	NodeInfo v1.NodeSystemInfo `json:"nodeInfo"`
98

99
	// Conditions is an array of current node conditions.
100
	Conditions []common.Condition `json:"conditions"`
101 102 103 104 105 106 107 108 109

	// Container images of the node.
	ContainerImages []string `json:"containerImages"`

	// PodList contains information about pods belonging to this node.
	PodList pod.PodList `json:"podList"`

	// Events is list of events associated to the node.
	EventList common.EventList `json:"eventList"`
110 111

	// Metrics collected for this resource
112
	Metrics []metricapi.Metric `json:"metrics"`
113 114 115

	// Taints
	Taints []v1.Taint `json:"taints,omitempty"`
116

117 118 119
	// Addresses is a list of addresses reachable to the node. Queried from cloud provider, if available.
	Addresses []v1.NodeAddress `json:"addresses,omitempty"`

120 121
	// List of non-critical errors, that occurred during resource retrieval.
	Errors []error `json:"errors"`
122 123 124
}

// GetNodeDetail gets node details.
125 126
func GetNodeDetail(client k8sClient.Interface, metricClient metricapi.MetricClient, name string,
	dsQuery *dataselect.DataSelectQuery) (*NodeDetail, error) {
127 128
	log.Printf("Getting details of %s node", name)

129
	node, err := client.CoreV1().Nodes().Get(name, metaV1.GetOptions{})
130 131 132 133
	if err != nil {
		return nil, err
	}

134 135
	// Download standard metrics. Currently metrics are hard coded, but it is possible to replace
	// dataselect.StdMetricsDataSelect with data select provided in the request.
136
	_, metricPromises := dataselect.GenericDataSelectWithMetrics(toCells([]v1.Node{*node}),
137
		dsQuery,
138
		metricapi.NoResourceCache, metricClient)
139

140
	pods, err := getNodePods(client, *node)
141 142 143
	nonCriticalErrors, criticalError := errors.HandleError(err)
	if criticalError != nil {
		return nil, criticalError
144 145
	}

146
	podList, err := GetNodePods(client, metricClient, dsQuery, name)
147 148 149 150
	nonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)
	if criticalError != nil {
		return nil, criticalError
	}
151

152
	eventList, err := event.GetNodeEvents(client, dsQuery, node.Name)
153 154 155
	nonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)
	if criticalError != nil {
		return nil, criticalError
156 157
	}

158
	allocatedResources, err := getNodeAllocatedResources(*node, pods)
159 160 161
	nonCriticalErrors, criticalError = errors.AppendError(err, nonCriticalErrors)
	if criticalError != nil {
		return nil, criticalError
162 163
	}

164
	metrics, _ := metricPromises.GetMetrics()
165
	nodeDetails := toNodeDetail(*node, podList, eventList, allocatedResources, metrics, nonCriticalErrors)
166 167 168
	return &nodeDetails, nil
}

169 170
func getNodeAllocatedResources(node v1.Node, podList *v1.PodList) (NodeAllocatedResources, error) {
	reqs, limits := map[v1.ResourceName]resource.Quantity{}, map[v1.ResourceName]resource.Quantity{}
171 172

	for _, pod := range podList.Items {
173
		podReqs, podLimits, err := PodRequestsAndLimits(&pod)
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194
		if err != nil {
			return NodeAllocatedResources{}, err
		}
		for podReqName, podReqValue := range podReqs {
			if value, ok := reqs[podReqName]; !ok {
				reqs[podReqName] = *podReqValue.Copy()
			} else {
				value.Add(podReqValue)
				reqs[podReqName] = value
			}
		}
		for podLimitName, podLimitValue := range podLimits {
			if value, ok := limits[podLimitName]; !ok {
				limits[podLimitName] = *podLimitValue.Copy()
			} else {
				value.Add(podLimitValue)
				limits[podLimitName] = value
			}
		}
	}

195 196
	cpuRequests, cpuLimits, memoryRequests, memoryLimits := reqs[v1.ResourceCPU],
		limits[v1.ResourceCPU], reqs[v1.ResourceMemory], limits[v1.ResourceMemory]
197 198 199 200 201 202

	var cpuRequestsFraction, cpuLimitsFraction float64 = 0, 0
	if capacity := float64(node.Status.Capacity.Cpu().MilliValue()); capacity > 0 {
		cpuRequestsFraction = float64(cpuRequests.MilliValue()) / capacity * 100
		cpuLimitsFraction = float64(cpuLimits.MilliValue()) / capacity * 100
	}
203

204 205 206 207 208 209
	var memoryRequestsFraction, memoryLimitsFraction float64 = 0, 0
	if capacity := float64(node.Status.Capacity.Memory().MilliValue()); capacity > 0 {
		memoryRequestsFraction = float64(memoryRequests.MilliValue()) / capacity * 100
		memoryLimitsFraction = float64(memoryLimits.MilliValue()) / capacity * 100
	}

210 211 212 213 214 215
	var podFraction float64 = 0
	var podCapacity int64 = node.Status.Capacity.Pods().Value()
	if podCapacity > 0 {
		podFraction = float64(len(podList.Items)) / float64(podCapacity) * 100
	}

216 217 218 219 220 221 222 223 224 225 226 227
	return NodeAllocatedResources{
		CPURequests:            cpuRequests.MilliValue(),
		CPURequestsFraction:    cpuRequestsFraction,
		CPULimits:              cpuLimits.MilliValue(),
		CPULimitsFraction:      cpuLimitsFraction,
		CPUCapacity:            node.Status.Capacity.Cpu().MilliValue(),
		MemoryRequests:         memoryRequests.Value(),
		MemoryRequestsFraction: memoryRequestsFraction,
		MemoryLimits:           memoryLimits.Value(),
		MemoryLimitsFraction:   memoryLimitsFraction,
		MemoryCapacity:         node.Status.Capacity.Memory().Value(),
		AllocatedPods:          len(podList.Items),
228 229
		PodCapacity:            podCapacity,
		PodFraction:            podFraction,
230 231 232
	}, nil
}

233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
// PodRequestsAndLimits returns a dictionary of all defined resources summed up for all
// containers of the pod.
func PodRequestsAndLimits(pod *v1.Pod) (reqs map[v1.ResourceName]resource.Quantity, limits map[v1.ResourceName]resource.Quantity, err error) {
	reqs, limits = map[v1.ResourceName]resource.Quantity{}, map[v1.ResourceName]resource.Quantity{}
	for _, container := range pod.Spec.Containers {
		for name, quantity := range container.Resources.Requests {
			if value, ok := reqs[name]; !ok {
				reqs[name] = *quantity.Copy()
			} else {
				value.Add(quantity)
				reqs[name] = value
			}
		}
		for name, quantity := range container.Resources.Limits {
			if value, ok := limits[name]; !ok {
				limits[name] = *quantity.Copy()
			} else {
				value.Add(quantity)
				limits[name] = value
			}
		}
	}
	// init containers define the minimum of any resource
	for _, container := range pod.Spec.InitContainers {
		for name, quantity := range container.Resources.Requests {
			value, ok := reqs[name]
			if !ok {
				reqs[name] = *quantity.Copy()
				continue
			}
			if quantity.Cmp(value) > 0 {
				reqs[name] = *quantity.Copy()
			}
		}
		for name, quantity := range container.Resources.Limits {
			value, ok := limits[name]
			if !ok {
				limits[name] = *quantity.Copy()
				continue
			}
			if quantity.Cmp(value) > 0 {
				limits[name] = *quantity.Copy()
			}
		}
	}
	return
}

281
// GetNodePods return pods list in given named node
282
func GetNodePods(client k8sClient.Interface, metricClient metricapi.MetricClient,
283
	dsQuery *dataselect.DataSelectQuery, name string) (*pod.PodList, error) {
S
Sebastian Florek 已提交
284 285 286 287 288
	podList := pod.PodList{
		Pods:              []pod.Pod{},
		CumulativeMetrics: []metricapi.Metric{},
	}

289
	node, err := client.CoreV1().Nodes().Get(name, metaV1.GetOptions{})
290
	if err != nil {
S
Sebastian Florek 已提交
291
		return &podList, err
292 293 294 295
	}

	pods, err := getNodePods(client, *node)
	if err != nil {
S
Sebastian Florek 已提交
296
		return &podList, err
297 298
	}

299
	events, err := event.GetPodsEvents(client, v1.NamespaceAll, pods.Items)
S
Sebastian Florek 已提交
300 301 302
	nonCriticalErrors, criticalError := errors.HandleError(err)
	if criticalError != nil {
		return &podList, criticalError
303 304
	}

S
Sebastian Florek 已提交
305
	podList = pod.ToPodList(pods.Items, events, nonCriticalErrors, dsQuery, metricClient)
306 307 308
	return &podList, nil
}

309
func getNodePods(client k8sClient.Interface, node v1.Node) (*v1.PodList, error) {
310
	fieldSelector, err := fields.ParseSelector("spec.nodeName=" + node.Name +
311 312
		",status.phase!=" + string(v1.PodSucceeded) +
		",status.phase!=" + string(v1.PodFailed))
313 314

	if err != nil {
315
		return nil, err
316 317
	}

318
	return client.CoreV1().Pods(v1.NamespaceAll).List(metaV1.ListOptions{
S
Sebastian Florek 已提交
319
		FieldSelector: fieldSelector.String(),
320 321 322
	})
}

323
func toNodeDetail(node v1.Node, pods *pod.PodList, eventList *common.EventList,
324
	allocatedResources NodeAllocatedResources, metrics []metricapi.Metric, nonCriticalErrors []error) NodeDetail {
325
	return NodeDetail{
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
		Node: Node{
			ObjectMeta:         api.NewObjectMeta(node.ObjectMeta),
			TypeMeta:           api.NewTypeMeta(api.ResourceKindNode),
			AllocatedResources: allocatedResources,
		},
		Phase:           node.Status.Phase,
		ProviderID:      node.Spec.ProviderID,
		PodCIDR:         node.Spec.PodCIDR,
		Unschedulable:   node.Spec.Unschedulable,
		NodeInfo:        node.Status.NodeInfo,
		Conditions:      getNodeConditions(node),
		ContainerImages: getContainerImages(node),
		PodList:         *pods,
		EventList:       *eventList,
		Metrics:         metrics,
		Taints:          node.Spec.Taints,
		Addresses:       node.Status.Addresses,
		Errors:          nonCriticalErrors,
344 345
	}
}