kuberuntime_sandbox.go 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. Copyright 2016 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 kuberuntime
  14. import (
  15. "fmt"
  16. "net"
  17. "net/url"
  18. "sort"
  19. "k8s.io/api/core/v1"
  20. kubetypes "k8s.io/apimachinery/pkg/types"
  21. utilfeature "k8s.io/apiserver/pkg/util/feature"
  22. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  23. "k8s.io/klog"
  24. "k8s.io/kubernetes/pkg/features"
  25. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  26. "k8s.io/kubernetes/pkg/kubelet/types"
  27. "k8s.io/kubernetes/pkg/kubelet/util/format"
  28. )
  29. // createPodSandbox creates a pod sandbox and returns (podSandBoxID, message, error).
  30. func (m *kubeGenericRuntimeManager) createPodSandbox(pod *v1.Pod, attempt uint32) (string, string, error) {
  31. podSandboxConfig, err := m.generatePodSandboxConfig(pod, attempt)
  32. if err != nil {
  33. message := fmt.Sprintf("GeneratePodSandboxConfig for pod %q failed: %v", format.Pod(pod), err)
  34. klog.Error(message)
  35. return "", message, err
  36. }
  37. // Create pod logs directory
  38. err = m.osInterface.MkdirAll(podSandboxConfig.LogDirectory, 0755)
  39. if err != nil {
  40. message := fmt.Sprintf("Create pod log directory for pod %q failed: %v", format.Pod(pod), err)
  41. klog.Errorf(message)
  42. return "", message, err
  43. }
  44. runtimeHandler := ""
  45. if utilfeature.DefaultFeatureGate.Enabled(features.RuntimeClass) && m.runtimeClassManager != nil {
  46. runtimeHandler, err = m.runtimeClassManager.LookupRuntimeHandler(pod.Spec.RuntimeClassName)
  47. if err != nil {
  48. message := fmt.Sprintf("CreatePodSandbox for pod %q failed: %v", format.Pod(pod), err)
  49. return "", message, err
  50. }
  51. if runtimeHandler != "" {
  52. klog.V(2).Infof("Running pod %s with RuntimeHandler %q", format.Pod(pod), runtimeHandler)
  53. }
  54. }
  55. podSandBoxID, err := m.runtimeService.RunPodSandbox(podSandboxConfig, runtimeHandler)
  56. if err != nil {
  57. message := fmt.Sprintf("CreatePodSandbox for pod %q failed: %v", format.Pod(pod), err)
  58. klog.Error(message)
  59. return "", message, err
  60. }
  61. return podSandBoxID, "", nil
  62. }
  63. // generatePodSandboxConfig generates pod sandbox config from v1.Pod.
  64. func (m *kubeGenericRuntimeManager) generatePodSandboxConfig(pod *v1.Pod, attempt uint32) (*runtimeapi.PodSandboxConfig, error) {
  65. // TODO: deprecating podsandbox resource requirements in favor of the pod level cgroup
  66. // Refer https://github.com/kubernetes/kubernetes/issues/29871
  67. podUID := string(pod.UID)
  68. podSandboxConfig := &runtimeapi.PodSandboxConfig{
  69. Metadata: &runtimeapi.PodSandboxMetadata{
  70. Name: pod.Name,
  71. Namespace: pod.Namespace,
  72. Uid: podUID,
  73. Attempt: attempt,
  74. },
  75. Labels: newPodLabels(pod),
  76. Annotations: newPodAnnotations(pod),
  77. }
  78. dnsConfig, err := m.runtimeHelper.GetPodDNS(pod)
  79. if err != nil {
  80. return nil, err
  81. }
  82. podSandboxConfig.DnsConfig = dnsConfig
  83. if !kubecontainer.IsHostNetworkPod(pod) {
  84. // TODO: Add domain support in new runtime interface
  85. hostname, _, err := m.runtimeHelper.GeneratePodHostNameAndDomain(pod)
  86. if err != nil {
  87. return nil, err
  88. }
  89. podSandboxConfig.Hostname = hostname
  90. }
  91. logDir := BuildPodLogsDirectory(pod.Namespace, pod.Name, pod.UID)
  92. podSandboxConfig.LogDirectory = logDir
  93. portMappings := []*runtimeapi.PortMapping{}
  94. for _, c := range pod.Spec.Containers {
  95. containerPortMappings := kubecontainer.MakePortMappings(&c)
  96. for idx := range containerPortMappings {
  97. port := containerPortMappings[idx]
  98. hostPort := int32(port.HostPort)
  99. containerPort := int32(port.ContainerPort)
  100. protocol := toRuntimeProtocol(port.Protocol)
  101. portMappings = append(portMappings, &runtimeapi.PortMapping{
  102. HostIp: port.HostIP,
  103. HostPort: hostPort,
  104. ContainerPort: containerPort,
  105. Protocol: protocol,
  106. })
  107. }
  108. }
  109. if len(portMappings) > 0 {
  110. podSandboxConfig.PortMappings = portMappings
  111. }
  112. lc, err := m.generatePodSandboxLinuxConfig(pod)
  113. if err != nil {
  114. return nil, err
  115. }
  116. podSandboxConfig.Linux = lc
  117. return podSandboxConfig, nil
  118. }
  119. // generatePodSandboxLinuxConfig generates LinuxPodSandboxConfig from v1.Pod.
  120. func (m *kubeGenericRuntimeManager) generatePodSandboxLinuxConfig(pod *v1.Pod) (*runtimeapi.LinuxPodSandboxConfig, error) {
  121. cgroupParent := m.runtimeHelper.GetPodCgroupParent(pod)
  122. lc := &runtimeapi.LinuxPodSandboxConfig{
  123. CgroupParent: cgroupParent,
  124. SecurityContext: &runtimeapi.LinuxSandboxSecurityContext{
  125. Privileged: kubecontainer.HasPrivilegedContainer(pod),
  126. SeccompProfilePath: m.getSeccompProfileFromAnnotations(pod.Annotations, ""),
  127. },
  128. }
  129. sysctls := make(map[string]string)
  130. if utilfeature.DefaultFeatureGate.Enabled(features.Sysctls) {
  131. if pod.Spec.SecurityContext != nil {
  132. for _, c := range pod.Spec.SecurityContext.Sysctls {
  133. sysctls[c.Name] = c.Value
  134. }
  135. }
  136. }
  137. lc.Sysctls = sysctls
  138. if pod.Spec.SecurityContext != nil {
  139. sc := pod.Spec.SecurityContext
  140. if sc.RunAsUser != nil {
  141. lc.SecurityContext.RunAsUser = &runtimeapi.Int64Value{Value: int64(*sc.RunAsUser)}
  142. }
  143. if sc.RunAsGroup != nil {
  144. lc.SecurityContext.RunAsGroup = &runtimeapi.Int64Value{Value: int64(*sc.RunAsGroup)}
  145. }
  146. lc.SecurityContext.NamespaceOptions = namespacesForPod(pod)
  147. if sc.FSGroup != nil {
  148. lc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, int64(*sc.FSGroup))
  149. }
  150. if groups := m.runtimeHelper.GetExtraSupplementalGroupsForPod(pod); len(groups) > 0 {
  151. lc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, groups...)
  152. }
  153. if sc.SupplementalGroups != nil {
  154. for _, sg := range sc.SupplementalGroups {
  155. lc.SecurityContext.SupplementalGroups = append(lc.SecurityContext.SupplementalGroups, int64(sg))
  156. }
  157. }
  158. if sc.SELinuxOptions != nil {
  159. lc.SecurityContext.SelinuxOptions = &runtimeapi.SELinuxOption{
  160. User: sc.SELinuxOptions.User,
  161. Role: sc.SELinuxOptions.Role,
  162. Type: sc.SELinuxOptions.Type,
  163. Level: sc.SELinuxOptions.Level,
  164. }
  165. }
  166. }
  167. return lc, nil
  168. }
  169. // getKubeletSandboxes lists all (or just the running) sandboxes managed by kubelet.
  170. func (m *kubeGenericRuntimeManager) getKubeletSandboxes(all bool) ([]*runtimeapi.PodSandbox, error) {
  171. var filter *runtimeapi.PodSandboxFilter
  172. if !all {
  173. readyState := runtimeapi.PodSandboxState_SANDBOX_READY
  174. filter = &runtimeapi.PodSandboxFilter{
  175. State: &runtimeapi.PodSandboxStateValue{
  176. State: readyState,
  177. },
  178. }
  179. }
  180. resp, err := m.runtimeService.ListPodSandbox(filter)
  181. if err != nil {
  182. klog.Errorf("ListPodSandbox failed: %v", err)
  183. return nil, err
  184. }
  185. return resp, nil
  186. }
  187. // determinePodSandboxIP determines the IP address of the given pod sandbox.
  188. func (m *kubeGenericRuntimeManager) determinePodSandboxIP(podNamespace, podName string, podSandbox *runtimeapi.PodSandboxStatus) string {
  189. if podSandbox.Network == nil {
  190. klog.Warningf("Pod Sandbox status doesn't have network information, cannot report IP")
  191. return ""
  192. }
  193. ip := podSandbox.Network.Ip
  194. if len(ip) != 0 && net.ParseIP(ip) == nil {
  195. // ip could be an empty string if runtime is not responsible for the
  196. // IP (e.g., host networking).
  197. klog.Warningf("Pod Sandbox reported an unparseable IP %v", ip)
  198. return ""
  199. }
  200. return ip
  201. }
  202. // getPodSandboxID gets the sandbox id by podUID and returns ([]sandboxID, error).
  203. // Param state could be nil in order to get all sandboxes belonging to same pod.
  204. func (m *kubeGenericRuntimeManager) getSandboxIDByPodUID(podUID kubetypes.UID, state *runtimeapi.PodSandboxState) ([]string, error) {
  205. filter := &runtimeapi.PodSandboxFilter{
  206. LabelSelector: map[string]string{types.KubernetesPodUIDLabel: string(podUID)},
  207. }
  208. if state != nil {
  209. filter.State = &runtimeapi.PodSandboxStateValue{
  210. State: *state,
  211. }
  212. }
  213. sandboxes, err := m.runtimeService.ListPodSandbox(filter)
  214. if err != nil {
  215. klog.Errorf("ListPodSandbox with pod UID %q failed: %v", podUID, err)
  216. return nil, err
  217. }
  218. if len(sandboxes) == 0 {
  219. return nil, nil
  220. }
  221. // Sort with newest first.
  222. sandboxIDs := make([]string, len(sandboxes))
  223. sort.Sort(podSandboxByCreated(sandboxes))
  224. for i, s := range sandboxes {
  225. sandboxIDs[i] = s.Id
  226. }
  227. return sandboxIDs, nil
  228. }
  229. // GetPortForward gets the endpoint the runtime will serve the port-forward request from.
  230. func (m *kubeGenericRuntimeManager) GetPortForward(podName, podNamespace string, podUID kubetypes.UID, ports []int32) (*url.URL, error) {
  231. sandboxIDs, err := m.getSandboxIDByPodUID(podUID, nil)
  232. if err != nil {
  233. return nil, fmt.Errorf("failed to find sandboxID for pod %s: %v", format.PodDesc(podName, podNamespace, podUID), err)
  234. }
  235. if len(sandboxIDs) == 0 {
  236. return nil, fmt.Errorf("failed to find sandboxID for pod %s", format.PodDesc(podName, podNamespace, podUID))
  237. }
  238. req := &runtimeapi.PortForwardRequest{
  239. PodSandboxId: sandboxIDs[0],
  240. Port: ports,
  241. }
  242. resp, err := m.runtimeService.PortForward(req)
  243. if err != nil {
  244. return nil, err
  245. }
  246. return url.Parse(resp.Url)
  247. }