helpers.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336
  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. "fmt"
  16. "hash/fnv"
  17. "strings"
  18. "k8s.io/klog"
  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. "k8s.io/apimachinery/pkg/util/sets"
  24. "k8s.io/client-go/tools/record"
  25. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  26. "k8s.io/kubernetes/pkg/kubelet/util/format"
  27. hashutil "k8s.io/kubernetes/pkg/util/hash"
  28. "k8s.io/kubernetes/third_party/forked/golang/expansion"
  29. )
  30. // HandlerRunner runs a lifecycle handler for a container.
  31. type HandlerRunner interface {
  32. Run(containerID ContainerID, pod *v1.Pod, container *v1.Container, handler *v1.Handler) (string, error)
  33. }
  34. // RuntimeHelper wraps kubelet to make container runtime
  35. // able to get necessary informations like the RunContainerOptions, DNS settings, Host IP.
  36. type RuntimeHelper interface {
  37. GenerateRunContainerOptions(pod *v1.Pod, container *v1.Container, podIP string) (contOpts *RunContainerOptions, cleanupAction func(), err error)
  38. GetPodDNS(pod *v1.Pod) (dnsConfig *runtimeapi.DNSConfig, err error)
  39. // GetPodCgroupParent returns the CgroupName identifier, and its literal cgroupfs form on the host
  40. // of a pod.
  41. GetPodCgroupParent(pod *v1.Pod) string
  42. GetPodDir(podUID types.UID) string
  43. GeneratePodHostNameAndDomain(pod *v1.Pod) (hostname string, hostDomain string, err error)
  44. // GetExtraSupplementalGroupsForPod returns a list of the extra
  45. // supplemental groups for the Pod. These extra supplemental groups come
  46. // from annotations on persistent volumes that the pod depends on.
  47. GetExtraSupplementalGroupsForPod(pod *v1.Pod) []int64
  48. }
  49. // ShouldContainerBeRestarted checks whether a container needs to be restarted.
  50. // TODO(yifan): Think about how to refactor this.
  51. func ShouldContainerBeRestarted(container *v1.Container, pod *v1.Pod, podStatus *PodStatus) bool {
  52. // Get latest container status.
  53. status := podStatus.FindContainerStatusByName(container.Name)
  54. // If the container was never started before, we should start it.
  55. // NOTE(random-liu): If all historical containers were GC'd, we'll also return true here.
  56. if status == nil {
  57. return true
  58. }
  59. // Check whether container is running
  60. if status.State == ContainerStateRunning {
  61. return false
  62. }
  63. // Always restart container in the unknown, or in the created state.
  64. if status.State == ContainerStateUnknown || status.State == ContainerStateCreated {
  65. return true
  66. }
  67. // Check RestartPolicy for dead container
  68. if pod.Spec.RestartPolicy == v1.RestartPolicyNever {
  69. klog.V(4).Infof("Already ran container %q of pod %q, do nothing", container.Name, format.Pod(pod))
  70. return false
  71. }
  72. if pod.Spec.RestartPolicy == v1.RestartPolicyOnFailure {
  73. // Check the exit code.
  74. if status.ExitCode == 0 {
  75. klog.V(4).Infof("Already successfully ran container %q of pod %q, do nothing", container.Name, format.Pod(pod))
  76. return false
  77. }
  78. }
  79. return true
  80. }
  81. // HashContainer returns the hash of the container. It is used to compare
  82. // the running container with its desired spec.
  83. func HashContainer(container *v1.Container) uint64 {
  84. hash := fnv.New32a()
  85. hashutil.DeepHashObject(hash, *container)
  86. return uint64(hash.Sum32())
  87. }
  88. // EnvVarsToMap constructs a map of environment name to value from a slice
  89. // of env vars.
  90. func EnvVarsToMap(envs []EnvVar) map[string]string {
  91. result := map[string]string{}
  92. for _, env := range envs {
  93. result[env.Name] = env.Value
  94. }
  95. return result
  96. }
  97. // V1EnvVarsToMap constructs a map of environment name to value from a slice
  98. // of env vars.
  99. func V1EnvVarsToMap(envs []v1.EnvVar) map[string]string {
  100. result := map[string]string{}
  101. for _, env := range envs {
  102. result[env.Name] = env.Value
  103. }
  104. return result
  105. }
  106. // ExpandContainerCommandOnlyStatic substitutes only static environment variable values from the
  107. // container environment definitions. This does *not* include valueFrom substitutions.
  108. // TODO: callers should use ExpandContainerCommandAndArgs with a fully resolved list of environment.
  109. func ExpandContainerCommandOnlyStatic(containerCommand []string, envs []v1.EnvVar) (command []string) {
  110. mapping := expansion.MappingFuncFor(V1EnvVarsToMap(envs))
  111. if len(containerCommand) != 0 {
  112. for _, cmd := range containerCommand {
  113. command = append(command, expansion.Expand(cmd, mapping))
  114. }
  115. }
  116. return command
  117. }
  118. func ExpandContainerVolumeMounts(mount v1.VolumeMount, envs []EnvVar) (string, error) {
  119. envmap := EnvVarsToMap(envs)
  120. missingKeys := sets.NewString()
  121. expanded := expansion.Expand(mount.SubPathExpr, func(key string) string {
  122. value, ok := envmap[key]
  123. if !ok || len(value) == 0 {
  124. missingKeys.Insert(key)
  125. }
  126. return value
  127. })
  128. if len(missingKeys) > 0 {
  129. return "", fmt.Errorf("missing value for %s", strings.Join(missingKeys.List(), ", "))
  130. }
  131. return expanded, nil
  132. }
  133. func ExpandContainerCommandAndArgs(container *v1.Container, envs []EnvVar) (command []string, args []string) {
  134. mapping := expansion.MappingFuncFor(EnvVarsToMap(envs))
  135. if len(container.Command) != 0 {
  136. for _, cmd := range container.Command {
  137. command = append(command, expansion.Expand(cmd, mapping))
  138. }
  139. }
  140. if len(container.Args) != 0 {
  141. for _, arg := range container.Args {
  142. args = append(args, expansion.Expand(arg, mapping))
  143. }
  144. }
  145. return command, args
  146. }
  147. // Create an event recorder to record object's event except implicitly required container's, like infra container.
  148. func FilterEventRecorder(recorder record.EventRecorder) record.EventRecorder {
  149. return &innerEventRecorder{
  150. recorder: recorder,
  151. }
  152. }
  153. type innerEventRecorder struct {
  154. recorder record.EventRecorder
  155. }
  156. func (irecorder *innerEventRecorder) shouldRecordEvent(object runtime.Object) (*v1.ObjectReference, bool) {
  157. if object == nil {
  158. return nil, false
  159. }
  160. if ref, ok := object.(*v1.ObjectReference); ok {
  161. if !strings.HasPrefix(ref.FieldPath, ImplicitContainerPrefix) {
  162. return ref, true
  163. }
  164. }
  165. return nil, false
  166. }
  167. func (irecorder *innerEventRecorder) Event(object runtime.Object, eventtype, reason, message string) {
  168. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  169. irecorder.recorder.Event(ref, eventtype, reason, message)
  170. }
  171. }
  172. func (irecorder *innerEventRecorder) Eventf(object runtime.Object, eventtype, reason, messageFmt string, args ...interface{}) {
  173. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  174. irecorder.recorder.Eventf(ref, eventtype, reason, messageFmt, args...)
  175. }
  176. }
  177. func (irecorder *innerEventRecorder) PastEventf(object runtime.Object, timestamp metav1.Time, eventtype, reason, messageFmt string, args ...interface{}) {
  178. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  179. irecorder.recorder.PastEventf(ref, timestamp, eventtype, reason, messageFmt, args...)
  180. }
  181. }
  182. func (irecorder *innerEventRecorder) AnnotatedEventf(object runtime.Object, annotations map[string]string, eventtype, reason, messageFmt string, args ...interface{}) {
  183. if ref, ok := irecorder.shouldRecordEvent(object); ok {
  184. irecorder.recorder.AnnotatedEventf(ref, annotations, eventtype, reason, messageFmt, args...)
  185. }
  186. }
  187. // Pod must not be nil.
  188. func IsHostNetworkPod(pod *v1.Pod) bool {
  189. return pod.Spec.HostNetwork
  190. }
  191. // TODO(random-liu): Convert PodStatus to running Pod, should be deprecated soon
  192. func ConvertPodStatusToRunningPod(runtimeName string, podStatus *PodStatus) Pod {
  193. runningPod := Pod{
  194. ID: podStatus.ID,
  195. Name: podStatus.Name,
  196. Namespace: podStatus.Namespace,
  197. }
  198. for _, containerStatus := range podStatus.ContainerStatuses {
  199. if containerStatus.State != ContainerStateRunning {
  200. continue
  201. }
  202. container := &Container{
  203. ID: containerStatus.ID,
  204. Name: containerStatus.Name,
  205. Image: containerStatus.Image,
  206. ImageID: containerStatus.ImageID,
  207. Hash: containerStatus.Hash,
  208. State: containerStatus.State,
  209. }
  210. runningPod.Containers = append(runningPod.Containers, container)
  211. }
  212. // Populate sandboxes in kubecontainer.Pod
  213. for _, sandbox := range podStatus.SandboxStatuses {
  214. runningPod.Sandboxes = append(runningPod.Sandboxes, &Container{
  215. ID: ContainerID{Type: runtimeName, ID: sandbox.Id},
  216. State: SandboxToContainerState(sandbox.State),
  217. })
  218. }
  219. return runningPod
  220. }
  221. // SandboxToContainerState converts runtimeapi.PodSandboxState to
  222. // kubecontainer.ContainerState.
  223. // This is only needed because we need to return sandboxes as if they were
  224. // kubecontainer.Containers to avoid substantial changes to PLEG.
  225. // TODO: Remove this once it becomes obsolete.
  226. func SandboxToContainerState(state runtimeapi.PodSandboxState) ContainerState {
  227. switch state {
  228. case runtimeapi.PodSandboxState_SANDBOX_READY:
  229. return ContainerStateRunning
  230. case runtimeapi.PodSandboxState_SANDBOX_NOTREADY:
  231. return ContainerStateExited
  232. }
  233. return ContainerStateUnknown
  234. }
  235. // FormatPod returns a string representing a pod in a human readable format,
  236. // with pod UID as part of the string.
  237. func FormatPod(pod *Pod) string {
  238. // Use underscore as the delimiter because it is not allowed in pod name
  239. // (DNS subdomain format), while allowed in the container name format.
  240. return fmt.Sprintf("%s_%s(%s)", pod.Name, pod.Namespace, pod.ID)
  241. }
  242. // GetContainerSpec gets the container spec by containerName.
  243. func GetContainerSpec(pod *v1.Pod, containerName string) *v1.Container {
  244. for i, c := range pod.Spec.Containers {
  245. if containerName == c.Name {
  246. return &pod.Spec.Containers[i]
  247. }
  248. }
  249. for i, c := range pod.Spec.InitContainers {
  250. if containerName == c.Name {
  251. return &pod.Spec.InitContainers[i]
  252. }
  253. }
  254. return nil
  255. }
  256. // HasPrivilegedContainer returns true if any of the containers in the pod are privileged.
  257. func HasPrivilegedContainer(pod *v1.Pod) bool {
  258. for _, c := range append(pod.Spec.Containers, pod.Spec.InitContainers...) {
  259. if c.SecurityContext != nil &&
  260. c.SecurityContext.Privileged != nil &&
  261. *c.SecurityContext.Privileged {
  262. return true
  263. }
  264. }
  265. return false
  266. }
  267. // MakePortMappings creates internal port mapping from api port mapping.
  268. func MakePortMappings(container *v1.Container) (ports []PortMapping) {
  269. names := make(map[string]struct{})
  270. for _, p := range container.Ports {
  271. pm := PortMapping{
  272. HostPort: int(p.HostPort),
  273. ContainerPort: int(p.ContainerPort),
  274. Protocol: p.Protocol,
  275. HostIP: p.HostIP,
  276. }
  277. // We need to create some default port name if it's not specified, since
  278. // this is necessary for rkt.
  279. // http://issue.k8s.io/7710
  280. if p.Name == "" {
  281. pm.Name = fmt.Sprintf("%s-%s:%d", container.Name, p.Protocol, p.ContainerPort)
  282. } else {
  283. pm.Name = fmt.Sprintf("%s-%s", container.Name, p.Name)
  284. }
  285. // Protect against exposing the same protocol-port more than once in a container.
  286. if _, ok := names[pm.Name]; ok {
  287. klog.Warningf("Port name conflicted, %q is defined more than once", pm.Name)
  288. continue
  289. }
  290. ports = append(ports, pm)
  291. names[pm.Name] = struct{}{}
  292. }
  293. return
  294. }