helpers.go 6.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192
  1. /*
  2. Copyright 2015 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 container
  14. import (
  15. "hash/adler32"
  16. "strings"
  17. "k8s.io/kubernetes/pkg/api"
  18. "k8s.io/kubernetes/pkg/api/unversioned"
  19. "k8s.io/kubernetes/pkg/client/record"
  20. "k8s.io/kubernetes/pkg/kubelet/util/format"
  21. "k8s.io/kubernetes/pkg/runtime"
  22. "k8s.io/kubernetes/pkg/types"
  23. hashutil "k8s.io/kubernetes/pkg/util/hash"
  24. "k8s.io/kubernetes/third_party/forked/golang/expansion"
  25. "github.com/golang/glog"
  26. )
  27. // HandlerRunner runs a lifecycle handler for a container.
  28. type HandlerRunner interface {
  29. Run(containerID ContainerID, pod *api.Pod, container *api.Container, handler *api.Handler) (string, error)
  30. }
  31. // RuntimeHelper wraps kubelet to make container runtime
  32. // able to get necessary informations like the RunContainerOptions, DNS settings.
  33. type RuntimeHelper interface {
  34. GenerateRunContainerOptions(pod *api.Pod, container *api.Container, podIP string) (*RunContainerOptions, error)
  35. GetClusterDNS(pod *api.Pod) (dnsServers []string, dnsSearches []string, err error)
  36. GetPodDir(podUID types.UID) string
  37. GeneratePodHostNameAndDomain(pod *api.Pod) (hostname string, hostDomain string, err error)
  38. // GetExtraSupplementalGroupsForPod returns a list of the extra
  39. // supplemental groups for the Pod. These extra supplemental groups come
  40. // from annotations on persistent volumes that the pod depends on.
  41. GetExtraSupplementalGroupsForPod(pod *api.Pod) []int64
  42. }
  43. // ShouldContainerBeRestarted checks whether a container needs to be restarted.
  44. // TODO(yifan): Think about how to refactor this.
  45. func ShouldContainerBeRestarted(container *api.Container, pod *api.Pod, podStatus *PodStatus) bool {
  46. // Get latest container status.
  47. status := podStatus.FindContainerStatusByName(container.Name)
  48. // If the container was never started before, we should start it.
  49. // NOTE(random-liu): If all historical containers were GC'd, we'll also return true here.
  50. if status == nil {
  51. return true
  52. }
  53. // Check whether container is running
  54. if status.State == ContainerStateRunning {
  55. return false
  56. }
  57. // Always restart container in unknown state now
  58. if status.State == ContainerStateUnknown {
  59. return true
  60. }
  61. // Check RestartPolicy for dead container
  62. if pod.Spec.RestartPolicy == api.RestartPolicyNever {
  63. glog.V(4).Infof("Already ran container %q of pod %q, do nothing", container.Name, format.Pod(pod))
  64. return false
  65. }
  66. if pod.Spec.RestartPolicy == api.RestartPolicyOnFailure {
  67. // Check the exit code.
  68. if status.ExitCode == 0 {
  69. glog.V(4).Infof("Already successfully ran container %q of pod %q, do nothing", container.Name, format.Pod(pod))
  70. return false
  71. }
  72. }
  73. return true
  74. }
  75. // TODO(random-liu): Convert PodStatus to running Pod, should be deprecated soon
  76. func ConvertPodStatusToRunningPod(podStatus *PodStatus) Pod {
  77. runningPod := Pod{
  78. ID: podStatus.ID,
  79. Name: podStatus.Name,
  80. Namespace: podStatus.Namespace,
  81. }
  82. for _, containerStatus := range podStatus.ContainerStatuses {
  83. if containerStatus.State != ContainerStateRunning {
  84. continue
  85. }
  86. container := &Container{
  87. ID: containerStatus.ID,
  88. Name: containerStatus.Name,
  89. Image: containerStatus.Image,
  90. ImageID: containerStatus.ImageID,
  91. Hash: containerStatus.Hash,
  92. State: containerStatus.State,
  93. }
  94. runningPod.Containers = append(runningPod.Containers, container)
  95. }
  96. return runningPod
  97. }
  98. // HashContainer returns the hash of the container. It is used to compare
  99. // the running container with its desired spec.
  100. func HashContainer(container *api.Container) uint64 {
  101. hash := adler32.New()
  102. hashutil.DeepHashObject(hash, *container)
  103. return uint64(hash.Sum32())
  104. }
  105. // EnvVarsToMap constructs a map of environment name to value from a slice
  106. // of env vars.
  107. func EnvVarsToMap(envs []EnvVar) map[string]string {
  108. result := map[string]string{}
  109. for _, env := range envs {
  110. result[env.Name] = env.Value
  111. }
  112. return result
  113. }
  114. func ExpandContainerCommandAndArgs(container *api.Container, envs []EnvVar) (command []string, args []string) {
  115. mapping := expansion.MappingFuncFor(EnvVarsToMap(envs))
  116. if len(container.Command) != 0 {
  117. for _, cmd := range container.Command {
  118. command = append(command, expansion.Expand(cmd, mapping))
  119. }
  120. }
  121. if len(container.Args) != 0 {
  122. for _, arg := range container.Args {
  123. args = append(args, expansion.Expand(arg, mapping))
  124. }
  125. }
  126. return command, args
  127. }
  128. // Create an event recorder to record object's event except implicitly required container's, like infra container.
  129. func FilterEventRecorder(recorder record.EventRecorder) record.EventRecorder {
  130. return &innerEventRecorder{
  131. recorder: recorder,
  132. }
  133. }
  134. type innerEventRecorder struct {
  135. recorder record.EventRecorder
  136. }
  137. func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*api.ObjectReference, bool) {
  138. if object == nil {
  139. return nil, false
  140. }
  141. if ref, ok := object.(*api.ObjectReference); ok {
  142. if !strings.HasPrefix(ref.FieldPath, ImplicitContainerPrefix) {
  143. return ref, true
  144. }
  145. }
  146. return nil, false
  147. }
  148. func (irecorder *innerEventRecorder) Event(object runtime.Object, eventtype, reason, message string) {
  149. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  150. irecorder.recorder.Event(ref, eventtype, reason, message)
  151. }
  152. }
  153. func (irecorder *innerEventRecorder) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
  154. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  155. irecorder.recorder.Eventf(ref, eventtype, reason, messageFmt, args...)
  156. }
  157. }
  158. func (irecorder *innerEventRecorder) PastEventf(object runtime.Object, timestamp unversioned.Time, eventtype, reason, messageFmt string, args ...interface{}) {
  159. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  160. irecorder.recorder.PastEventf(ref, timestamp, eventtype, reason, messageFmt, args...)
  161. }
  162. }
  163. // Pod must not be nil.
  164. func IsHostNetworkPod(pod *api.Pod) bool {
  165. return pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.HostNetwork
  166. }