common.go 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. /*
  2. Copyright 2014 The Kubernetes Authors.
  3. Licensed under the Apache License, Version 2.0 (the "License");
  4. you may not use this file except in compliance with the License.
  5. You may obtain a copy of the License at
  6. http://www.apache.org/licenses/LICENSE-2.0
  7. Unless required by applicable law or agreed to in writing, software
  8. distributed under the License is distributed on an "AS IS" BASIS,
  9. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. See the License for the specific language governing permissions and
  11. limitations under the License.
  12. */
  13. package config
  14. import (
  15. "crypto/md5"
  16. "encoding/hex"
  17. "fmt"
  18. "strings"
  19. "k8s.io/api/core/v1"
  20. metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
  21. "k8s.io/apimachinery/pkg/runtime"
  22. "k8s.io/apimachinery/pkg/types"
  23. utilyaml "k8s.io/apimachinery/pkg/util/yaml"
  24. api "k8s.io/kubernetes/pkg/apis/core"
  25. "k8s.io/kubernetes/pkg/apis/core/helper"
  26. // TODO: remove this import if
  27. // api.Registry.GroupOrDie(v1.GroupName).GroupVersion.String() is changed
  28. // to "v1"?
  29. "k8s.io/kubernetes/pkg/api/legacyscheme"
  30. // Ensure that core apis are installed
  31. _ "k8s.io/kubernetes/pkg/apis/core/install"
  32. k8s_api_v1 "k8s.io/kubernetes/pkg/apis/core/v1"
  33. "k8s.io/kubernetes/pkg/apis/core/validation"
  34. kubetypes "k8s.io/kubernetes/pkg/kubelet/types"
  35. "k8s.io/kubernetes/pkg/util/hash"
  36. "k8s.io/klog"
  37. )
  38. const (
  39. maxConfigLength = 10 * 1 << 20 // 10MB
  40. )
  41. // Generate a pod name that is unique among nodes by appending the nodeName.
  42. func generatePodName(name string, nodeName types.NodeName) string {
  43. return fmt.Sprintf("%s-%s", name, strings.ToLower(string(nodeName)))
  44. }
  45. func applyDefaults(pod *api.Pod, source string, isFile bool, nodeName types.NodeName) error {
  46. if len(pod.UID) == 0 {
  47. hasher := md5.New()
  48. if isFile {
  49. fmt.Fprintf(hasher, "host:%s", nodeName)
  50. fmt.Fprintf(hasher, "file:%s", source)
  51. } else {
  52. fmt.Fprintf(hasher, "url:%s", source)
  53. }
  54. hash.DeepHashObject(hasher, pod)
  55. pod.UID = types.UID(hex.EncodeToString(hasher.Sum(nil)[0:]))
  56. klog.V(5).Infof("Generated UID %q pod %q from %s", pod.UID, pod.Name, source)
  57. }
  58. pod.Name = generatePodName(pod.Name, nodeName)
  59. klog.V(5).Infof("Generated Name %q for UID %q from URL %s", pod.Name, pod.UID, source)
  60. if pod.Namespace == "" {
  61. pod.Namespace = metav1.NamespaceDefault
  62. }
  63. klog.V(5).Infof("Using namespace %q for pod %q from %s", pod.Namespace, pod.Name, source)
  64. // Set the Host field to indicate this pod is scheduled on the current node.
  65. pod.Spec.NodeName = string(nodeName)
  66. pod.ObjectMeta.SelfLink = getSelfLink(pod.Name, pod.Namespace)
  67. if pod.Annotations == nil {
  68. pod.Annotations = make(map[string]string)
  69. }
  70. // The generated UID is the hash of the file.
  71. pod.Annotations[kubetypes.ConfigHashAnnotationKey] = string(pod.UID)
  72. if isFile {
  73. // Applying the default Taint tolerations to static pods,
  74. // so they are not evicted when there are node problems.
  75. helper.AddOrUpdateTolerationInPod(pod, &api.Toleration{
  76. Operator: "Exists",
  77. Effect: api.TaintEffectNoExecute,
  78. })
  79. }
  80. // Set the default status to pending.
  81. pod.Status.Phase = api.PodPending
  82. return nil
  83. }
  84. func getSelfLink(name, namespace string) string {
  85. var selfLink string
  86. if len(namespace) == 0 {
  87. namespace = metav1.NamespaceDefault
  88. }
  89. selfLink = fmt.Sprintf("/api/v1/namespaces/%s/pods/%s", namespace, name)
  90. return selfLink
  91. }
  92. type defaultFunc func(pod *api.Pod) error
  93. // tryDecodeSinglePod takes data and tries to extract valid Pod config information from it.
  94. func tryDecodeSinglePod(data []byte, defaultFn defaultFunc) (parsed bool, pod *v1.Pod, err error) {
  95. // JSON is valid YAML, so this should work for everything.
  96. json, err := utilyaml.ToJSON(data)
  97. if err != nil {
  98. return false, nil, err
  99. }
  100. obj, err := runtime.Decode(legacyscheme.Codecs.UniversalDecoder(), json)
  101. if err != nil {
  102. return false, pod, err
  103. }
  104. newPod, ok := obj.(*api.Pod)
  105. // Check whether the object could be converted to single pod.
  106. if !ok {
  107. return false, pod, fmt.Errorf("invalid pod: %#v", obj)
  108. }
  109. // Apply default values and validate the pod.
  110. if err = defaultFn(newPod); err != nil {
  111. return true, pod, err
  112. }
  113. if errs := validation.ValidatePod(newPod); len(errs) > 0 {
  114. return true, pod, fmt.Errorf("invalid pod: %v", errs)
  115. }
  116. v1Pod := &v1.Pod{}
  117. if err := k8s_api_v1.Convert_core_Pod_To_v1_Pod(newPod, v1Pod, nil); err != nil {
  118. klog.Errorf("Pod %q failed to convert to v1", newPod.Name)
  119. return true, nil, err
  120. }
  121. return true, v1Pod, nil
  122. }
  123. func tryDecodePodList(data []byte, defaultFn defaultFunc) (parsed bool, pods v1.PodList, err error) {
  124. obj, err := runtime.Decode(legacyscheme.Codecs.UniversalDecoder(), data)
  125. if err != nil {
  126. return false, pods, err
  127. }
  128. newPods, ok := obj.(*api.PodList)
  129. // Check whether the object could be converted to list of pods.
  130. if !ok {
  131. err = fmt.Errorf("invalid pods list: %#v", obj)
  132. return false, pods, err
  133. }
  134. // Apply default values and validate pods.
  135. for i := range newPods.Items {
  136. newPod := &newPods.Items[i]
  137. if err = defaultFn(newPod); err != nil {
  138. return true, pods, err
  139. }
  140. if errs := validation.ValidatePod(newPod); len(errs) > 0 {
  141. err = fmt.Errorf("invalid pod: %v", errs)
  142. return true, pods, err
  143. }
  144. }
  145. v1Pods := &v1.PodList{}
  146. if err := k8s_api_v1.Convert_core_PodList_To_v1_PodList(newPods, v1Pods, nil); err != nil {
  147. return true, pods, err
  148. }
  149. return true, *v1Pods, err
  150. }