docker_container.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  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 dockershim
  14. import (
  15. "fmt"
  16. "io"
  17. "time"
  18. dockertypes "github.com/docker/engine-api/types"
  19. dockercontainer "github.com/docker/engine-api/types/container"
  20. dockerfilters "github.com/docker/engine-api/types/filters"
  21. dockerstrslice "github.com/docker/engine-api/types/strslice"
  22. runtimeApi "k8s.io/kubernetes/pkg/kubelet/api/v1alpha1/runtime"
  23. "k8s.io/kubernetes/pkg/kubelet/dockertools"
  24. )
  25. // ListContainers lists all containers matching the filter.
  26. func (ds *dockerService) ListContainers(filter *runtimeApi.ContainerFilter) ([]*runtimeApi.Container, error) {
  27. opts := dockertypes.ContainerListOptions{All: true}
  28. opts.Filter = dockerfilters.NewArgs()
  29. f := newDockerFilter(&opts.Filter)
  30. if filter != nil {
  31. if filter.Id != nil {
  32. f.Add("id", filter.GetId())
  33. }
  34. if filter.State != nil {
  35. f.Add("status", toDockerContainerStatus(filter.GetState()))
  36. }
  37. if filter.PodSandboxId != nil {
  38. // TODO: implement this after sandbox functions are implemented.
  39. }
  40. if filter.LabelSelector != nil {
  41. for k, v := range filter.LabelSelector {
  42. f.AddLabel(k, v)
  43. }
  44. }
  45. // Filter out sandbox containers.
  46. f.AddLabel(containerTypeLabelKey, containerTypeLabelContainer)
  47. }
  48. containers, err := ds.client.ListContainers(opts)
  49. if err != nil {
  50. return nil, err
  51. }
  52. // Convert docker to runtime api containers.
  53. result := []*runtimeApi.Container{}
  54. for _, c := range containers {
  55. if len(filter.GetName()) > 0 {
  56. _, _, _, containerName, _, err := parseContainerName(c.Names[0])
  57. if err != nil || containerName != filter.GetName() {
  58. continue
  59. }
  60. }
  61. result = append(result, toRuntimeAPIContainer(&c))
  62. }
  63. return result, nil
  64. }
  65. // CreateContainer creates a new container in the given PodSandbox
  66. // Note: docker doesn't use LogPath yet.
  67. // TODO: check if the default values returned by the runtime API are ok.
  68. func (ds *dockerService) CreateContainer(podSandboxID string, config *runtimeApi.ContainerConfig, sandboxConfig *runtimeApi.PodSandboxConfig) (string, error) {
  69. if config == nil {
  70. return "", fmt.Errorf("container config is nil")
  71. }
  72. if sandboxConfig == nil {
  73. return "", fmt.Errorf("sandbox config is nil for container %q", config.Metadata.GetName())
  74. }
  75. // Merge annotations and labels because docker supports only labels.
  76. // TODO: add a prefix to annotations so that we can distinguish labels and
  77. // annotations when reading back them from the docker container.
  78. labels := makeLabels(config.GetLabels(), config.GetAnnotations())
  79. // Apply a the container type label.
  80. labels[containerTypeLabelKey] = containerTypeLabelContainer
  81. image := ""
  82. if iSpec := config.GetImage(); iSpec != nil {
  83. image = iSpec.GetImage()
  84. }
  85. createConfig := dockertypes.ContainerCreateConfig{
  86. Name: buildContainerName(sandboxConfig, config),
  87. Config: &dockercontainer.Config{
  88. // TODO: set User.
  89. Hostname: sandboxConfig.GetHostname(),
  90. Entrypoint: dockerstrslice.StrSlice(config.GetCommand()),
  91. Cmd: dockerstrslice.StrSlice(config.GetArgs()),
  92. Env: generateEnvList(config.GetEnvs()),
  93. Image: image,
  94. WorkingDir: config.GetWorkingDir(),
  95. Labels: labels,
  96. // Interactive containers:
  97. OpenStdin: config.GetStdin(),
  98. StdinOnce: config.GetStdinOnce(),
  99. Tty: config.GetTty(),
  100. },
  101. }
  102. // Fill the HostConfig.
  103. hc := &dockercontainer.HostConfig{
  104. Binds: generateMountBindings(config.GetMounts()),
  105. ReadonlyRootfs: config.GetReadonlyRootfs(),
  106. Privileged: config.GetPrivileged(),
  107. }
  108. // Apply options derived from the sandbox config.
  109. if lc := sandboxConfig.GetLinux(); lc != nil {
  110. // Apply Cgroup options.
  111. // TODO: Check if this works with per-pod cgroups.
  112. hc.CgroupParent = lc.GetCgroupParent()
  113. // Apply namespace options.
  114. sandboxNSMode := fmt.Sprintf("container:%v", podSandboxID)
  115. hc.NetworkMode = dockercontainer.NetworkMode(sandboxNSMode)
  116. hc.IpcMode = dockercontainer.IpcMode(sandboxNSMode)
  117. hc.UTSMode = ""
  118. hc.PidMode = ""
  119. nsOpts := lc.GetNamespaceOptions()
  120. if nsOpts != nil {
  121. if nsOpts.GetHostNetwork() {
  122. hc.UTSMode = namespaceModeHost
  123. }
  124. if nsOpts.GetHostPid() {
  125. hc.PidMode = namespaceModeHost
  126. }
  127. }
  128. }
  129. // Apply Linux-specific options if applicable.
  130. if lc := config.GetLinux(); lc != nil {
  131. // Apply resource options.
  132. // TODO: Check if the units are correct.
  133. // TODO: Can we assume the defaults are sane?
  134. rOpts := lc.GetResources()
  135. if rOpts != nil {
  136. hc.Resources = dockercontainer.Resources{
  137. Memory: rOpts.GetMemoryLimitInBytes(),
  138. MemorySwap: -1, // Always disable memory swap.
  139. CPUShares: rOpts.GetCpuShares(),
  140. CPUQuota: rOpts.GetCpuQuota(),
  141. CPUPeriod: rOpts.GetCpuPeriod(),
  142. // TODO: Need to set devices.
  143. }
  144. hc.OomScoreAdj = int(rOpts.GetOomScoreAdj())
  145. }
  146. // Note: ShmSize is handled in kube_docker_client.go
  147. }
  148. hc.SecurityOpt = []string{getSeccompOpts()}
  149. // TODO: Add or drop capabilities.
  150. createConfig.HostConfig = hc
  151. createResp, err := ds.client.CreateContainer(createConfig)
  152. if createResp != nil {
  153. return createResp.ID, err
  154. }
  155. return "", err
  156. }
  157. // StartContainer starts the container.
  158. func (ds *dockerService) StartContainer(containerID string) error {
  159. return ds.client.StartContainer(containerID)
  160. }
  161. // StopContainer stops a running container with a grace period (i.e., timeout).
  162. func (ds *dockerService) StopContainer(containerID string, timeout int64) error {
  163. return ds.client.StopContainer(containerID, int(timeout))
  164. }
  165. // RemoveContainer removes the container.
  166. // TODO: If a container is still running, should we forcibly remove it?
  167. func (ds *dockerService) RemoveContainer(containerID string) error {
  168. return ds.client.RemoveContainer(containerID, dockertypes.ContainerRemoveOptions{RemoveVolumes: true})
  169. }
  170. func getContainerTimestamps(r *dockertypes.ContainerJSON) (time.Time, time.Time, time.Time, error) {
  171. var createdAt, startedAt, finishedAt time.Time
  172. var err error
  173. createdAt, err = dockertools.ParseDockerTimestamp(r.Created)
  174. if err != nil {
  175. return createdAt, startedAt, finishedAt, err
  176. }
  177. startedAt, err = dockertools.ParseDockerTimestamp(r.State.StartedAt)
  178. if err != nil {
  179. return createdAt, startedAt, finishedAt, err
  180. }
  181. finishedAt, err = dockertools.ParseDockerTimestamp(r.State.FinishedAt)
  182. if err != nil {
  183. return createdAt, startedAt, finishedAt, err
  184. }
  185. return createdAt, startedAt, finishedAt, nil
  186. }
  187. // ContainerStatus returns the container status.
  188. func (ds *dockerService) ContainerStatus(containerID string) (*runtimeApi.ContainerStatus, error) {
  189. r, err := ds.client.InspectContainer(containerID)
  190. if err != nil {
  191. return nil, err
  192. }
  193. // Parse the timstamps.
  194. createdAt, startedAt, finishedAt, err := getContainerTimestamps(r)
  195. if err != nil {
  196. return nil, fmt.Errorf("failed to parse timestamp for container %q: %v", containerID, err)
  197. }
  198. // Convert the mounts.
  199. mounts := []*runtimeApi.Mount{}
  200. for _, m := range r.Mounts {
  201. readonly := !m.RW
  202. mounts = append(mounts, &runtimeApi.Mount{
  203. Name: &m.Name,
  204. HostPath: &m.Source,
  205. ContainerPath: &m.Destination,
  206. Readonly: &readonly,
  207. // Note: Can't set SeLinuxRelabel
  208. })
  209. }
  210. // Interpret container states.
  211. var state runtimeApi.ContainerState
  212. var reason string
  213. if r.State.Running {
  214. // Container is running.
  215. state = runtimeApi.ContainerState_RUNNING
  216. } else {
  217. // Container is *not* running. We need to get more details.
  218. // * Case 1: container has run and exited with non-zero finishedAt
  219. // time.
  220. // * Case 2: container has failed to start; it has a zero finishedAt
  221. // time, but a non-zero exit code.
  222. // * Case 3: container has been created, but not started (yet).
  223. if !finishedAt.IsZero() { // Case 1
  224. state = runtimeApi.ContainerState_EXITED
  225. switch {
  226. case r.State.OOMKilled:
  227. // TODO: consider exposing OOMKilled via the runtimeAPI.
  228. // Note: if an application handles OOMKilled gracefully, the
  229. // exit code could be zero.
  230. reason = "OOMKilled"
  231. case r.State.ExitCode == 0:
  232. reason = "Completed"
  233. default:
  234. reason = fmt.Sprintf("Error: %s", r.State.Error)
  235. }
  236. } else if !finishedAt.IsZero() && r.State.ExitCode != 0 { // Case 2
  237. state = runtimeApi.ContainerState_EXITED
  238. // Adjust finshedAt and startedAt time to createdAt time to avoid
  239. // the confusion.
  240. finishedAt, startedAt = createdAt, createdAt
  241. reason = "ContainerCannotRun"
  242. } else { // Case 3
  243. state = runtimeApi.ContainerState_CREATED
  244. }
  245. }
  246. // Convert to unix timestamps.
  247. ct, st, ft := createdAt.Unix(), startedAt.Unix(), finishedAt.Unix()
  248. exitCode := int32(r.State.ExitCode)
  249. _, _, _, containerName, attempt, err := parseContainerName(r.Name)
  250. if err != nil {
  251. return nil, err
  252. }
  253. return &runtimeApi.ContainerStatus{
  254. Id: &r.ID,
  255. Metadata: &runtimeApi.ContainerMetadata{
  256. Name: &containerName,
  257. Attempt: &attempt,
  258. },
  259. Image: &runtimeApi.ImageSpec{Image: &r.Config.Image},
  260. ImageRef: &r.Image,
  261. Mounts: mounts,
  262. ExitCode: &exitCode,
  263. State: &state,
  264. CreatedAt: &ct,
  265. StartedAt: &st,
  266. FinishedAt: &ft,
  267. Reason: &reason,
  268. // TODO: We write annotations as labels on the docker containers. All
  269. // these annotations will be read back as labels. Need to fix this.
  270. Labels: r.Config.Labels,
  271. }, nil
  272. }
  273. // Exec execute a command in the container.
  274. // TODO: Need to handle terminal resizing before implementing this function.
  275. // https://github.com/kubernetes/kubernetes/issues/29579.
  276. func (ds *dockerService) Exec(containerID string, cmd []string, tty bool, stdin io.Reader, stdout, stderr io.WriteCloser) error {
  277. return fmt.Errorf("not implemented")
  278. }