k3s/pkg/apis/core/helper/helpers.go

586 lines
19 KiB
Go
Raw Normal View History

/*
Copyright 2014 The Kubernetes 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.
*/
2017-04-10 17:49:54 +00:00
package helper
import (
"encoding/json"
"fmt"
"strings"
2017-01-25 13:13:07 +00:00
"k8s.io/apimachinery/pkg/api/resource"
2017-01-11 14:09:48 +00:00
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/conversion"
2017-01-19 14:50:16 +00:00
"k8s.io/apimachinery/pkg/fields"
2017-01-11 14:09:48 +00:00
"k8s.io/apimachinery/pkg/labels"
"k8s.io/apimachinery/pkg/selection"
"k8s.io/apimachinery/pkg/util/sets"
2017-10-09 15:58:37 +00:00
"k8s.io/kubernetes/pkg/apis/core"
)
2017-08-17 18:16:37 +00:00
// IsHugePageResourceName returns true if the resource name has the huge page
// resource prefix.
2017-10-09 15:58:37 +00:00
func IsHugePageResourceName(name core.ResourceName) bool {
return strings.HasPrefix(string(name), core.ResourceHugePagesPrefix)
2017-08-17 18:16:37 +00:00
}
2017-11-13 01:37:06 +00:00
// IsQuotaHugePageResourceName returns true if the resource name has the quota
// related huge page resource prefix.
func IsQuotaHugePageResourceName(name core.ResourceName) bool {
return strings.HasPrefix(string(name), core.ResourceHugePagesPrefix) || strings.HasPrefix(string(name), core.ResourceRequestsHugePagesPrefix)
}
2017-08-17 18:16:37 +00:00
// HugePageResourceName returns a ResourceName with the canonical hugepage
// prefix prepended for the specified page size. The page size is converted
// to its canonical representation.
2017-10-09 15:58:37 +00:00
func HugePageResourceName(pageSize resource.Quantity) core.ResourceName {
return core.ResourceName(fmt.Sprintf("%s%s", core.ResourceHugePagesPrefix, pageSize.String()))
2017-08-17 18:16:37 +00:00
}
// HugePageSizeFromResourceName returns the page size for the specified huge page
// resource name. If the specified input is not a valid huge page resource name
// an error is returned.
2017-10-09 15:58:37 +00:00
func HugePageSizeFromResourceName(name core.ResourceName) (resource.Quantity, error) {
2017-08-17 18:16:37 +00:00
if !IsHugePageResourceName(name) {
return resource.Quantity{}, fmt.Errorf("resource name: %s is not valid hugepage name", name)
}
2017-10-09 15:58:37 +00:00
pageSize := strings.TrimPrefix(string(name), core.ResourceHugePagesPrefix)
2017-08-17 18:16:37 +00:00
return resource.ParseQuantity(pageSize)
}
// NonConvertibleFields iterates over the provided map and filters out all but
// any keys with the "non-convertible.kubernetes.io" prefix.
func NonConvertibleFields(annotations map[string]string) map[string]string {
nonConvertibleKeys := map[string]string{}
for key, value := range annotations {
2017-10-09 15:58:37 +00:00
if strings.HasPrefix(key, core.NonConvertibleAnnotationPrefix) {
nonConvertibleKeys[key] = value
}
}
return nonConvertibleKeys
}
2017-10-09 15:58:37 +00:00
// Semantic can do semantic deep equality checks for core objects.
// Example: apiequality.Semantic.DeepEqual(aPod, aPodWithNonNilButEmptyMaps) == true
var Semantic = conversion.EqualitiesOrDie(
func(a, b resource.Quantity) bool {
// Ignore formatting, only care that numeric value stayed the same.
// TODO: if we decide it's important, it should be safe to start comparing the format.
//
// Uninitialized quantities are equivalent to 0 quantities.
return a.Cmp(b) == 0
},
2017-08-04 12:02:53 +00:00
func(a, b metav1.MicroTime) bool {
return a.UTC() == b.UTC()
},
2016-12-03 18:57:26 +00:00
func(a, b metav1.Time) bool {
2015-03-06 05:03:21 +00:00
return a.UTC() == b.UTC()
},
func(a, b labels.Selector) bool {
return a.String() == b.String()
},
func(a, b fields.Selector) bool {
return a.String() == b.String()
},
)
var standardResourceQuotaScopes = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourceQuotaScopeTerminating),
string(core.ResourceQuotaScopeNotTerminating),
string(core.ResourceQuotaScopeBestEffort),
string(core.ResourceQuotaScopeNotBestEffort),
)
// IsStandardResourceQuotaScope returns true if the scope is a standard value
func IsStandardResourceQuotaScope(str string) bool {
return standardResourceQuotaScopes.Has(str)
}
var podObjectCountQuotaResources = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourcePods),
)
var podComputeQuotaResources = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourceCPU),
string(core.ResourceMemory),
string(core.ResourceLimitsCPU),
string(core.ResourceLimitsMemory),
string(core.ResourceRequestsCPU),
string(core.ResourceRequestsMemory),
)
// IsResourceQuotaScopeValidForResource returns true if the resource applies to the specified scope
2017-10-09 15:58:37 +00:00
func IsResourceQuotaScopeValidForResource(scope core.ResourceQuotaScope, resource string) bool {
switch scope {
2017-10-09 15:58:37 +00:00
case core.ResourceQuotaScopeTerminating, core.ResourceQuotaScopeNotTerminating, core.ResourceQuotaScopeNotBestEffort:
return podObjectCountQuotaResources.Has(resource) || podComputeQuotaResources.Has(resource)
2017-10-09 15:58:37 +00:00
case core.ResourceQuotaScopeBestEffort:
return podObjectCountQuotaResources.Has(resource)
default:
return true
}
}
var standardContainerResources = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourceCPU),
string(core.ResourceMemory),
string(core.ResourceEphemeralStorage),
)
// IsStandardContainerResourceName returns true if the container can make a resource request
// for the specified resource
func IsStandardContainerResourceName(str string) bool {
2017-10-09 15:58:37 +00:00
return standardContainerResources.Has(str) || IsHugePageResourceName(core.ResourceName(str))
}
// IsExtendedResourceName returns true if the resource name is not in the
2017-11-04 07:52:15 +00:00
// default namespace.
2017-10-09 15:58:37 +00:00
func IsExtendedResourceName(name core.ResourceName) bool {
2017-11-04 07:52:15 +00:00
return !IsDefaultNamespaceResource(name)
}
// IsDefaultNamespaceResource returns true if the resource name is in the
// *kubernetes.io/ namespace. Partially-qualified (unprefixed) names are
// implicitly in the kubernetes.io/ namespace.
2017-10-09 15:58:37 +00:00
func IsDefaultNamespaceResource(name core.ResourceName) bool {
return !strings.Contains(string(name), "/") ||
2017-10-09 15:58:37 +00:00
strings.Contains(string(name), core.ResourceDefaultNamespacePrefix)
}
2017-10-09 15:58:37 +00:00
var overcommitBlacklist = sets.NewString(string(core.ResourceNvidiaGPU))
// IsOvercommitAllowed returns true if the resource is in the default
// namespace and not blacklisted.
2017-10-09 15:58:37 +00:00
func IsOvercommitAllowed(name core.ResourceName) bool {
return IsDefaultNamespaceResource(name) &&
2017-08-17 18:16:37 +00:00
!IsHugePageResourceName(name) &&
!overcommitBlacklist.Has(string(name))
}
var standardLimitRangeTypes = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.LimitTypePod),
string(core.LimitTypeContainer),
string(core.LimitTypePersistentVolumeClaim),
)
// IsStandardLimitRangeType returns true if the type is Pod or Container
func IsStandardLimitRangeType(str string) bool {
return standardLimitRangeTypes.Has(str)
}
var standardQuotaResources = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourceCPU),
string(core.ResourceMemory),
string(core.ResourceEphemeralStorage),
string(core.ResourceRequestsCPU),
string(core.ResourceRequestsMemory),
string(core.ResourceRequestsStorage),
string(core.ResourceRequestsEphemeralStorage),
string(core.ResourceLimitsCPU),
string(core.ResourceLimitsMemory),
string(core.ResourceLimitsEphemeralStorage),
string(core.ResourcePods),
string(core.ResourceQuotas),
string(core.ResourceServices),
string(core.ResourceReplicationControllers),
string(core.ResourceSecrets),
string(core.ResourcePersistentVolumeClaims),
string(core.ResourceConfigMaps),
string(core.ResourceServicesNodePorts),
string(core.ResourceServicesLoadBalancers),
)
// IsStandardQuotaResourceName returns true if the resource is known to
// the quota tracking system
func IsStandardQuotaResourceName(str string) bool {
2017-11-13 01:37:06 +00:00
return standardQuotaResources.Has(str) || IsQuotaHugePageResourceName(core.ResourceName(str))
}
var standardResources = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourceCPU),
string(core.ResourceMemory),
string(core.ResourceEphemeralStorage),
string(core.ResourceRequestsCPU),
string(core.ResourceRequestsMemory),
string(core.ResourceRequestsEphemeralStorage),
string(core.ResourceLimitsCPU),
string(core.ResourceLimitsMemory),
string(core.ResourceLimitsEphemeralStorage),
string(core.ResourcePods),
string(core.ResourceQuotas),
string(core.ResourceServices),
string(core.ResourceReplicationControllers),
string(core.ResourceSecrets),
string(core.ResourceConfigMaps),
string(core.ResourcePersistentVolumeClaims),
string(core.ResourceStorage),
string(core.ResourceRequestsStorage),
string(core.ResourceServicesNodePorts),
string(core.ResourceServicesLoadBalancers),
)
// IsStandardResourceName returns true if the resource is known to the system
func IsStandardResourceName(str string) bool {
2017-11-13 01:37:06 +00:00
return standardResources.Has(str) || IsQuotaHugePageResourceName(core.ResourceName(str))
}
var integerResources = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.ResourcePods),
string(core.ResourceQuotas),
string(core.ResourceServices),
string(core.ResourceReplicationControllers),
string(core.ResourceSecrets),
string(core.ResourceConfigMaps),
string(core.ResourcePersistentVolumeClaims),
string(core.ResourceServicesNodePorts),
string(core.ResourceServicesLoadBalancers),
)
// IsIntegerResourceName returns true if the resource is measured in integer values
func IsIntegerResourceName(str string) bool {
2017-10-09 15:58:37 +00:00
return integerResources.Has(str) || IsExtendedResourceName(core.ResourceName(str))
}
// this function aims to check if the service's ClusterIP is set or not
// the objective is not to perform validation here
2017-10-09 15:58:37 +00:00
func IsServiceIPSet(service *core.Service) bool {
return service.Spec.ClusterIP != core.ClusterIPNone && service.Spec.ClusterIP != ""
}
var standardFinalizers = sets.NewString(
2017-10-09 15:58:37 +00:00
string(core.FinalizerKubernetes),
2017-02-23 19:14:55 +00:00
metav1.FinalizerOrphanDependents,
metav1.FinalizerDeleteDependents,
)
2015-03-20 16:48:12 +00:00
func IsStandardFinalizerName(str string) bool {
return standardFinalizers.Has(str)
}
// AddToNodeAddresses appends the NodeAddresses to the passed-by-pointer slice,
// only if they do not already exist
2017-10-09 15:58:37 +00:00
func AddToNodeAddresses(addresses *[]core.NodeAddress, addAddresses ...core.NodeAddress) {
for _, add := range addAddresses {
exists := false
for _, existing := range *addresses {
if existing.Address == add.Address && existing.Type == add.Type {
exists = true
break
}
}
if !exists {
*addresses = append(*addresses, add)
}
}
}
// TODO: make method on LoadBalancerStatus?
2017-10-09 15:58:37 +00:00
func LoadBalancerStatusEqual(l, r *core.LoadBalancerStatus) bool {
return ingressSliceEqual(l.Ingress, r.Ingress)
}
2017-10-09 15:58:37 +00:00
func ingressSliceEqual(lhs, rhs []core.LoadBalancerIngress) bool {
if len(lhs) != len(rhs) {
return false
}
for i := range lhs {
if !ingressEqual(&lhs[i], &rhs[i]) {
return false
}
}
return true
}
2017-10-09 15:58:37 +00:00
func ingressEqual(lhs, rhs *core.LoadBalancerIngress) bool {
if lhs.IP != rhs.IP {
return false
}
if lhs.Hostname != rhs.Hostname {
return false
}
return true
}
// TODO: make method on LoadBalancerStatus?
2017-10-09 15:58:37 +00:00
func LoadBalancerStatusDeepCopy(lb *core.LoadBalancerStatus) *core.LoadBalancerStatus {
c := &core.LoadBalancerStatus{}
c.Ingress = make([]core.LoadBalancerIngress, len(lb.Ingress))
for i := range lb.Ingress {
c.Ingress[i] = lb.Ingress[i]
}
return c
}
// GetAccessModesAsString returns a string representation of an array of access modes.
// modes, when present, are always in the same order: RWO,ROX,RWX.
2017-10-09 15:58:37 +00:00
func GetAccessModesAsString(modes []core.PersistentVolumeAccessMode) string {
modes = removeDuplicateAccessModes(modes)
modesStr := []string{}
2017-10-09 15:58:37 +00:00
if containsAccessMode(modes, core.ReadWriteOnce) {
modesStr = append(modesStr, "RWO")
}
2017-10-09 15:58:37 +00:00
if containsAccessMode(modes, core.ReadOnlyMany) {
modesStr = append(modesStr, "ROX")
}
2017-10-09 15:58:37 +00:00
if containsAccessMode(modes, core.ReadWriteMany) {
modesStr = append(modesStr, "RWX")
}
return strings.Join(modesStr, ",")
}
// GetAccessModesAsString returns an array of AccessModes from a string created by GetAccessModesAsString
2017-10-09 15:58:37 +00:00
func GetAccessModesFromString(modes string) []core.PersistentVolumeAccessMode {
strmodes := strings.Split(modes, ",")
2017-10-09 15:58:37 +00:00
accessModes := []core.PersistentVolumeAccessMode{}
for _, s := range strmodes {
s = strings.Trim(s, " ")
switch {
case s == "RWO":
2017-10-09 15:58:37 +00:00
accessModes = append(accessModes, core.ReadWriteOnce)
case s == "ROX":
2017-10-09 15:58:37 +00:00
accessModes = append(accessModes, core.ReadOnlyMany)
case s == "RWX":
2017-10-09 15:58:37 +00:00
accessModes = append(accessModes, core.ReadWriteMany)
}
}
return accessModes
}
// removeDuplicateAccessModes returns an array of access modes without any duplicates
2017-10-09 15:58:37 +00:00
func removeDuplicateAccessModes(modes []core.PersistentVolumeAccessMode) []core.PersistentVolumeAccessMode {
accessModes := []core.PersistentVolumeAccessMode{}
for _, m := range modes {
if !containsAccessMode(accessModes, m) {
accessModes = append(accessModes, m)
}
}
return accessModes
}
2017-10-09 15:58:37 +00:00
func containsAccessMode(modes []core.PersistentVolumeAccessMode, mode core.PersistentVolumeAccessMode) bool {
for _, m := range modes {
if m == mode {
return true
}
}
return false
}
2017-10-09 15:58:37 +00:00
// NodeSelectorRequirementsAsSelector converts the []NodeSelectorRequirement core type into a struct that implements
// labels.Selector.
2017-10-09 15:58:37 +00:00
func NodeSelectorRequirementsAsSelector(nsm []core.NodeSelectorRequirement) (labels.Selector, error) {
if len(nsm) == 0 {
return labels.Nothing(), nil
}
selector := labels.NewSelector()
for _, expr := range nsm {
var op selection.Operator
switch expr.Operator {
2017-10-09 15:58:37 +00:00
case core.NodeSelectorOpIn:
op = selection.In
2017-10-09 15:58:37 +00:00
case core.NodeSelectorOpNotIn:
op = selection.NotIn
2017-10-09 15:58:37 +00:00
case core.NodeSelectorOpExists:
op = selection.Exists
2017-10-09 15:58:37 +00:00
case core.NodeSelectorOpDoesNotExist:
op = selection.DoesNotExist
2017-10-09 15:58:37 +00:00
case core.NodeSelectorOpGt:
op = selection.GreaterThan
2017-10-09 15:58:37 +00:00
case core.NodeSelectorOpLt:
op = selection.LessThan
default:
return nil, fmt.Errorf("%q is not a valid node selector operator", expr.Operator)
}
2016-10-20 09:46:03 +00:00
r, err := labels.NewRequirement(expr.Key, op, expr.Values)
if err != nil {
return nil, err
}
selector = selector.Add(*r)
}
return selector, nil
}
// GetTolerationsFromPodAnnotations gets the json serialized tolerations data from Pod.Annotations
2017-10-09 15:58:37 +00:00
// and converts it to the []Toleration type in core.
func GetTolerationsFromPodAnnotations(annotations map[string]string) ([]core.Toleration, error) {
var tolerations []core.Toleration
if len(annotations) > 0 && annotations[core.TolerationsAnnotationKey] != "" {
err := json.Unmarshal([]byte(annotations[core.TolerationsAnnotationKey]), &tolerations)
if err != nil {
return tolerations, err
}
}
return tolerations, nil
}
// AddOrUpdateTolerationInPod tries to add a toleration to the pod's toleration list.
// Returns true if something was updated, false otherwise.
2017-10-09 15:58:37 +00:00
func AddOrUpdateTolerationInPod(pod *core.Pod, toleration *core.Toleration) bool {
podTolerations := pod.Spec.Tolerations
2017-10-09 15:58:37 +00:00
var newTolerations []core.Toleration
updated := false
for i := range podTolerations {
if toleration.MatchToleration(&podTolerations[i]) {
if Semantic.DeepEqual(toleration, podTolerations[i]) {
return false
}
newTolerations = append(newTolerations, *toleration)
updated = true
continue
}
newTolerations = append(newTolerations, podTolerations[i])
}
if !updated {
newTolerations = append(newTolerations, *toleration)
}
pod.Spec.Tolerations = newTolerations
return true
}
2017-03-22 05:01:49 +00:00
// GetTaintsFromNodeAnnotations gets the json serialized taints data from Pod.Annotations
2017-10-09 15:58:37 +00:00
// and converts it to the []Taint type in core.
func GetTaintsFromNodeAnnotations(annotations map[string]string) ([]core.Taint, error) {
var taints []core.Taint
if len(annotations) > 0 && annotations[core.TaintsAnnotationKey] != "" {
err := json.Unmarshal([]byte(annotations[core.TaintsAnnotationKey]), &taints)
2017-03-22 05:01:49 +00:00
if err != nil {
2017-10-09 15:58:37 +00:00
return []core.Taint{}, err
2017-03-22 05:01:49 +00:00
}
}
return taints, nil
}
// SysctlsFromPodAnnotations parses the sysctl annotations into a slice of safe Sysctls
// and a slice of unsafe Sysctls. This is only a convenience wrapper around
// SysctlsFromPodAnnotation.
2017-10-09 15:58:37 +00:00
func SysctlsFromPodAnnotations(a map[string]string) ([]core.Sysctl, []core.Sysctl, error) {
safe, err := SysctlsFromPodAnnotation(a[core.SysctlsPodAnnotationKey])
if err != nil {
return nil, nil, err
}
2017-10-09 15:58:37 +00:00
unsafe, err := SysctlsFromPodAnnotation(a[core.UnsafeSysctlsPodAnnotationKey])
if err != nil {
return nil, nil, err
}
return safe, unsafe, nil
}
// SysctlsFromPodAnnotation parses an annotation value into a slice of Sysctls.
2017-10-09 15:58:37 +00:00
func SysctlsFromPodAnnotation(annotation string) ([]core.Sysctl, error) {
if len(annotation) == 0 {
return nil, nil
}
kvs := strings.Split(annotation, ",")
2017-10-09 15:58:37 +00:00
sysctls := make([]core.Sysctl, len(kvs))
for i, kv := range kvs {
cs := strings.Split(kv, "=")
2016-09-30 09:07:04 +00:00
if len(cs) != 2 || len(cs[0]) == 0 {
return nil, fmt.Errorf("sysctl %q not of the format sysctl_name=value", kv)
}
sysctls[i].Name = cs[0]
sysctls[i].Value = cs[1]
}
return sysctls, nil
}
// PodAnnotationsFromSysctls creates an annotation value for a slice of Sysctls.
2017-10-09 15:58:37 +00:00
func PodAnnotationsFromSysctls(sysctls []core.Sysctl) string {
if len(sysctls) == 0 {
return ""
}
kvs := make([]string, len(sysctls))
for i := range sysctls {
kvs[i] = fmt.Sprintf("%s=%s", sysctls[i].Name, sysctls[i].Value)
}
return strings.Join(kvs, ",")
}
// GetPersistentVolumeClass returns StorageClassName.
2017-10-09 15:58:37 +00:00
func GetPersistentVolumeClass(volume *core.PersistentVolume) string {
// Use beta annotation first
2017-10-09 15:58:37 +00:00
if class, found := volume.Annotations[core.BetaStorageClassAnnotation]; found {
return class
}
return volume.Spec.StorageClassName
}
// GetPersistentVolumeClaimClass returns StorageClassName. If no storage class was
// requested, it returns "".
2017-10-09 15:58:37 +00:00
func GetPersistentVolumeClaimClass(claim *core.PersistentVolumeClaim) string {
// Use beta annotation first
2017-10-09 15:58:37 +00:00
if class, found := claim.Annotations[core.BetaStorageClassAnnotation]; found {
return class
}
if claim.Spec.StorageClassName != nil {
return *claim.Spec.StorageClassName
}
return ""
}
// PersistentVolumeClaimHasClass returns true if given claim has set StorageClassName field.
2017-10-09 15:58:37 +00:00
func PersistentVolumeClaimHasClass(claim *core.PersistentVolumeClaim) bool {
// Use beta annotation first
2017-10-09 15:58:37 +00:00
if _, found := claim.Annotations[core.BetaStorageClassAnnotation]; found {
return true
}
if claim.Spec.StorageClassName != nil {
return true
}
return false
}
// GetStorageNodeAffinityFromAnnotation gets the json serialized data from PersistentVolume.Annotations
2017-10-09 15:58:37 +00:00
// and converts it to the NodeAffinity type in core.
// TODO: update when storage node affinity graduates to beta
2017-10-09 15:58:37 +00:00
func GetStorageNodeAffinityFromAnnotation(annotations map[string]string) (*core.NodeAffinity, error) {
if len(annotations) > 0 && annotations[core.AlphaStorageNodeAffinityAnnotation] != "" {
var affinity core.NodeAffinity
err := json.Unmarshal([]byte(annotations[core.AlphaStorageNodeAffinityAnnotation]), &affinity)
if err != nil {
return nil, err
}
return &affinity, nil
}
return nil, nil
}
// Converts NodeAffinity type to Alpha annotation for use in PersistentVolumes
// TODO: update when storage node affinity graduates to beta
2017-10-09 15:58:37 +00:00
func StorageNodeAffinityToAlphaAnnotation(annotations map[string]string, affinity *core.NodeAffinity) error {
2017-05-22 22:30:27 +00:00
if affinity == nil {
return nil
}
json, err := json.Marshal(*affinity)
if err != nil {
return err
}
2017-10-09 15:58:37 +00:00
annotations[core.AlphaStorageNodeAffinityAnnotation] = string(json)
return nil
}