kuberuntime_container.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  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. "io"
  17. "math/rand"
  18. "os"
  19. "path"
  20. "github.com/golang/glog"
  21. "k8s.io/kubernetes/pkg/api"
  22. runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
  23. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  24. "k8s.io/kubernetes/pkg/types"
  25. "k8s.io/kubernetes/pkg/util/term"
  26. )
  27. // getContainerLogsPath gets log path for container.
  28. func getContainerLogsPath(containerName string, podUID types.UID) string {
  29. return path.Join(podLogsRootDirectory, string(podUID), fmt.Sprintf("%s.log", containerName))
  30. }
  31. // generateContainerConfig generates container config for kubelet runtime api.
  32. func (m *kubeGenericRuntimeManager) generateContainerConfig(container *api.Container, pod *api.Pod, restartCount int, podIP string) (*runtimeApi.ContainerConfig, error) {
  33. opts, err := m.runtimeHelper.GenerateRunContainerOptions(pod, container, podIP)
  34. if err != nil {
  35. return nil, err
  36. }
  37. command, args := kubecontainer.ExpandContainerCommandAndArgs(container, opts.Envs)
  38. containerLogsPath := getContainerLogsPath(container.Name, pod.UID)
  39. podHasSELinuxLabel := pod.Spec.SecurityContext != nil && pod.Spec.SecurityContext.SELinuxOptions != nil
  40. restartCountUint32 := uint32(restartCount)
  41. config := &runtimeApi.ContainerConfig{
  42. Metadata: &runtimeApi.ContainerMetadata{
  43. Name: &container.Name,
  44. Attempt: &restartCountUint32,
  45. },
  46. Image: &runtimeApi.ImageSpec{Image: &container.Image},
  47. Command: command,
  48. Args: args,
  49. WorkingDir: &container.WorkingDir,
  50. Labels: newContainerLabels(container, pod),
  51. Annotations: newContainerAnnotations(container, pod, restartCount),
  52. Mounts: makeMounts(opts, container, podHasSELinuxLabel),
  53. LogPath: &containerLogsPath,
  54. Stdin: &container.Stdin,
  55. StdinOnce: &container.StdinOnce,
  56. Tty: &container.TTY,
  57. Linux: m.generateLinuxContainerConfig(container),
  58. }
  59. // set priviledged and readonlyRootfs
  60. if container.SecurityContext != nil {
  61. securityContext := container.SecurityContext
  62. if securityContext.Privileged != nil {
  63. config.Privileged = securityContext.Privileged
  64. }
  65. if securityContext.ReadOnlyRootFilesystem != nil {
  66. config.ReadonlyRootfs = securityContext.ReadOnlyRootFilesystem
  67. }
  68. }
  69. // set environment variables
  70. envs := make([]*runtimeApi.KeyValue, len(opts.Envs))
  71. for idx := range opts.Envs {
  72. e := opts.Envs[idx]
  73. envs[idx] = &runtimeApi.KeyValue{
  74. Key: &e.Name,
  75. Value: &e.Value,
  76. }
  77. }
  78. config.Envs = envs
  79. return config, nil
  80. }
  81. // generateLinuxContainerConfig generates linux container config for kubelet runtime api.
  82. func (m *kubeGenericRuntimeManager) generateLinuxContainerConfig(container *api.Container) *runtimeApi.LinuxContainerConfig {
  83. linuxConfig := &runtimeApi.LinuxContainerConfig{
  84. Resources: &runtimeApi.LinuxContainerResources{},
  85. }
  86. // set linux container resources
  87. var cpuShares int64
  88. cpuRequest := container.Resources.Requests.Cpu()
  89. cpuLimit := container.Resources.Limits.Cpu()
  90. memoryLimit := container.Resources.Limits.Memory().Value()
  91. // If request is not specified, but limit is, we want request to default to limit.
  92. // API server does this for new containers, but we repeat this logic in Kubelet
  93. // for containers running on existing Kubernetes clusters.
  94. if cpuRequest.IsZero() && !cpuLimit.IsZero() {
  95. cpuShares = milliCPUToShares(cpuLimit.MilliValue())
  96. } else {
  97. // if cpuRequest.Amount is nil, then milliCPUToShares will return the minimal number
  98. // of CPU shares.
  99. cpuShares = milliCPUToShares(cpuRequest.MilliValue())
  100. }
  101. linuxConfig.Resources.CpuShares = &cpuShares
  102. if memoryLimit != 0 {
  103. linuxConfig.Resources.MemoryLimitInBytes = &memoryLimit
  104. }
  105. if m.cpuCFSQuota {
  106. // if cpuLimit.Amount is nil, then the appropriate default value is returned
  107. // to allow full usage of cpu resource.
  108. cpuQuota, cpuPeriod := milliCPUToQuota(cpuLimit.MilliValue())
  109. linuxConfig.Resources.CpuQuota = &cpuQuota
  110. linuxConfig.Resources.CpuPeriod = &cpuPeriod
  111. }
  112. // set security context options
  113. if container.SecurityContext != nil {
  114. securityContext := container.SecurityContext
  115. if securityContext.Capabilities != nil {
  116. linuxConfig.Capabilities = &runtimeApi.Capability{
  117. AddCapabilities: make([]string, 0, len(securityContext.Capabilities.Add)),
  118. DropCapabilities: make([]string, 0, len(securityContext.Capabilities.Drop)),
  119. }
  120. for index, value := range securityContext.Capabilities.Add {
  121. linuxConfig.Capabilities.AddCapabilities[index] = string(value)
  122. }
  123. for index, value := range securityContext.Capabilities.Drop {
  124. linuxConfig.Capabilities.DropCapabilities[index] = string(value)
  125. }
  126. }
  127. if securityContext.SELinuxOptions != nil {
  128. linuxConfig.SelinuxOptions = &runtimeApi.SELinuxOption{
  129. User: &securityContext.SELinuxOptions.User,
  130. Role: &securityContext.SELinuxOptions.Role,
  131. Type: &securityContext.SELinuxOptions.Type,
  132. Level: &securityContext.SELinuxOptions.Level,
  133. }
  134. }
  135. }
  136. return linuxConfig
  137. }
  138. // makeMounts generates container volume mounts for kubelet runtime api.
  139. func makeMounts(opts *kubecontainer.RunContainerOptions, container *api.Container, podHasSELinuxLabel bool) []*runtimeApi.Mount {
  140. volumeMounts := []*runtimeApi.Mount{}
  141. for idx := range opts.Mounts {
  142. v := opts.Mounts[idx]
  143. m := &runtimeApi.Mount{
  144. Name: &v.Name,
  145. HostPath: &v.HostPath,
  146. ContainerPath: &v.ContainerPath,
  147. Readonly: &v.ReadOnly,
  148. }
  149. if podHasSELinuxLabel && v.SELinuxRelabel {
  150. m.SelinuxRelabel = &v.SELinuxRelabel
  151. }
  152. volumeMounts = append(volumeMounts, m)
  153. }
  154. // The reason we create and mount the log file in here (not in kubelet) is because
  155. // the file's location depends on the ID of the container, and we need to create and
  156. // mount the file before actually starting the container.
  157. if opts.PodContainerDir != "" && len(container.TerminationMessagePath) != 0 {
  158. // Because the PodContainerDir contains pod uid and container name which is unique enough,
  159. // here we just add a random id to make the path unique for different instances
  160. // of the same container.
  161. cid := makeUID()
  162. containerLogPath := path.Join(opts.PodContainerDir, cid)
  163. fs, err := os.Create(containerLogPath)
  164. if err != nil {
  165. glog.Errorf("Error on creating termination-log file %q: %v", containerLogPath, err)
  166. } else {
  167. fs.Close()
  168. volumeMounts = append(volumeMounts, &runtimeApi.Mount{
  169. HostPath: &containerLogPath,
  170. ContainerPath: &container.TerminationMessagePath,
  171. })
  172. }
  173. }
  174. return volumeMounts
  175. }
  176. // getKubeletContainers lists containers managed by kubelet.
  177. // The boolean parameter specifies whether returns all containers including
  178. // those already exited and dead containers (used for garbage collection).
  179. func (m *kubeGenericRuntimeManager) getKubeletContainers(allContainers bool) ([]*runtimeApi.Container, error) {
  180. filter := &runtimeApi.ContainerFilter{
  181. LabelSelector: map[string]string{kubernetesManagedLabel: "true"},
  182. }
  183. if !allContainers {
  184. runningState := runtimeApi.ContainerState_RUNNING
  185. filter.State = &runningState
  186. }
  187. containers, err := m.getContainersHelper(filter)
  188. if err != nil {
  189. glog.Errorf("getKubeletContainers failed: %v", err)
  190. return nil, err
  191. }
  192. return containers, nil
  193. }
  194. // getContainers lists containers by filter.
  195. func (m *kubeGenericRuntimeManager) getContainersHelper(filter *runtimeApi.ContainerFilter) ([]*runtimeApi.Container, error) {
  196. resp, err := m.runtimeService.ListContainers(filter)
  197. if err != nil {
  198. return nil, err
  199. }
  200. return resp, err
  201. }
  202. // makeUID returns a randomly generated string.
  203. func makeUID() string {
  204. return fmt.Sprintf("%08x", rand.Uint32())
  205. }
  206. // AttachContainer attaches to the container's console
  207. func (m *kubeGenericRuntimeManager) AttachContainer(id kubecontainer.ContainerID, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) (err error) {
  208. return fmt.Errorf("not implemented")
  209. }
  210. // GetContainerLogs returns logs of a specific container.
  211. func (m *kubeGenericRuntimeManager) GetContainerLogs(pod *api.Pod, containerID kubecontainer.ContainerID, logOptions *api.PodLogOptions, stdout, stderr io.Writer) (err error) {
  212. return fmt.Errorf("not implemented")
  213. }
  214. // Runs the command in the container of the specified pod using nsenter.
  215. // Attaches the processes stdin, stdout, and stderr. Optionally uses a
  216. // tty.
  217. // TODO: handle terminal resizing, refer https://github.com/kubernetes/kubernetes/issues/29579
  218. func (m *kubeGenericRuntimeManager) ExecInContainer(containerID kubecontainer.ContainerID, cmd []string, stdin io.Reader, stdout, stderr io.WriteCloser, tty bool, resize <-chan term.Size) error {
  219. return fmt.Errorf("not implemented")
  220. }
  221. // DeleteContainer removes a container.
  222. func (m *kubeGenericRuntimeManager) DeleteContainer(containerID kubecontainer.ContainerID) error {
  223. return m.runtimeService.RemoveContainer(containerID.ID)
  224. }