docker_sandbox.go 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745
  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. "context"
  16. "encoding/json"
  17. "fmt"
  18. "os"
  19. "strings"
  20. "time"
  21. dockertypes "github.com/docker/docker/api/types"
  22. dockercontainer "github.com/docker/docker/api/types/container"
  23. dockerfilters "github.com/docker/docker/api/types/filters"
  24. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  25. runtimeapi "k8s.io/cri-api/pkg/apis/runtime/v1alpha2"
  26. "k8s.io/klog"
  27. "k8s.io/kubernetes/pkg/kubelet/checkpointmanager"
  28. "k8s.io/kubernetes/pkg/kubelet/checkpointmanager/errors"
  29. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  30. "k8s.io/kubernetes/pkg/kubelet/dockershim/libdocker"
  31. "k8s.io/kubernetes/pkg/kubelet/qos"
  32. "k8s.io/kubernetes/pkg/kubelet/types"
  33. )
  34. const (
  35. defaultSandboxImage = "k8s.gcr.io/pause:3.1"
  36. // Various default sandbox resources requests/limits.
  37. defaultSandboxCPUshares int64 = 2
  38. // Name of the underlying container runtime
  39. runtimeName = "docker"
  40. )
  41. var (
  42. // Termination grace period
  43. defaultSandboxGracePeriod = time.Duration(10) * time.Second
  44. )
  45. // Returns whether the sandbox network is ready, and whether the sandbox is known
  46. func (ds *dockerService) getNetworkReady(podSandboxID string) (bool, bool) {
  47. ds.networkReadyLock.Lock()
  48. defer ds.networkReadyLock.Unlock()
  49. ready, ok := ds.networkReady[podSandboxID]
  50. return ready, ok
  51. }
  52. func (ds *dockerService) setNetworkReady(podSandboxID string, ready bool) {
  53. ds.networkReadyLock.Lock()
  54. defer ds.networkReadyLock.Unlock()
  55. ds.networkReady[podSandboxID] = ready
  56. }
  57. func (ds *dockerService) clearNetworkReady(podSandboxID string) {
  58. ds.networkReadyLock.Lock()
  59. defer ds.networkReadyLock.Unlock()
  60. delete(ds.networkReady, podSandboxID)
  61. }
  62. // RunPodSandbox creates and starts a pod-level sandbox. Runtimes should ensure
  63. // the sandbox is in ready state.
  64. // For docker, PodSandbox is implemented by a container holding the network
  65. // namespace for the pod.
  66. // Note: docker doesn't use LogDirectory (yet).
  67. func (ds *dockerService) RunPodSandbox(ctx context.Context, r *runtimeapi.RunPodSandboxRequest) (*runtimeapi.RunPodSandboxResponse, error) {
  68. config := r.GetConfig()
  69. // Step 1: Pull the image for the sandbox.
  70. image := defaultSandboxImage
  71. podSandboxImage := ds.podSandboxImage
  72. if len(podSandboxImage) != 0 {
  73. image = podSandboxImage
  74. }
  75. // NOTE: To use a custom sandbox image in a private repository, users need to configure the nodes with credentials properly.
  76. // see: http://kubernetes.io/docs/user-guide/images/#configuring-nodes-to-authenticate-to-a-private-repository
  77. // Only pull sandbox image when it's not present - v1.PullIfNotPresent.
  78. if err := ensureSandboxImageExists(ds.client, image); err != nil {
  79. return nil, err
  80. }
  81. // Step 2: Create the sandbox container.
  82. if r.GetRuntimeHandler() != "" && r.GetRuntimeHandler() != runtimeName {
  83. return nil, fmt.Errorf("RuntimeHandler %q not supported", r.GetRuntimeHandler())
  84. }
  85. createConfig, err := ds.makeSandboxDockerConfig(config, image)
  86. if err != nil {
  87. return nil, fmt.Errorf("failed to make sandbox docker config for pod %q: %v", config.Metadata.Name, err)
  88. }
  89. createResp, err := ds.client.CreateContainer(*createConfig)
  90. if err != nil {
  91. createResp, err = recoverFromCreationConflictIfNeeded(ds.client, *createConfig, err)
  92. }
  93. if err != nil || createResp == nil {
  94. return nil, fmt.Errorf("failed to create a sandbox for pod %q: %v", config.Metadata.Name, err)
  95. }
  96. resp := &runtimeapi.RunPodSandboxResponse{PodSandboxId: createResp.ID}
  97. ds.setNetworkReady(createResp.ID, false)
  98. defer func(e *error) {
  99. // Set networking ready depending on the error return of
  100. // the parent function
  101. if *e == nil {
  102. ds.setNetworkReady(createResp.ID, true)
  103. }
  104. }(&err)
  105. // Step 3: Create Sandbox Checkpoint.
  106. if err = ds.checkpointManager.CreateCheckpoint(createResp.ID, constructPodSandboxCheckpoint(config)); err != nil {
  107. return nil, err
  108. }
  109. // Step 4: Start the sandbox container.
  110. // Assume kubelet's garbage collector would remove the sandbox later, if
  111. // startContainer failed.
  112. err = ds.client.StartContainer(createResp.ID)
  113. if err != nil {
  114. return nil, fmt.Errorf("failed to start sandbox container for pod %q: %v", config.Metadata.Name, err)
  115. }
  116. // Rewrite resolv.conf file generated by docker.
  117. // NOTE: cluster dns settings aren't passed anymore to docker api in all cases,
  118. // not only for pods with host network: the resolver conf will be overwritten
  119. // after sandbox creation to override docker's behaviour. This resolv.conf
  120. // file is shared by all containers of the same pod, and needs to be modified
  121. // only once per pod.
  122. if dnsConfig := config.GetDnsConfig(); dnsConfig != nil {
  123. containerInfo, err := ds.client.InspectContainer(createResp.ID)
  124. if err != nil {
  125. return nil, fmt.Errorf("failed to inspect sandbox container for pod %q: %v", config.Metadata.Name, err)
  126. }
  127. if err := rewriteResolvFile(containerInfo.ResolvConfPath, dnsConfig.Servers, dnsConfig.Searches, dnsConfig.Options); err != nil {
  128. return nil, fmt.Errorf("rewrite resolv.conf failed for pod %q: %v", config.Metadata.Name, err)
  129. }
  130. }
  131. // Do not invoke network plugins if in hostNetwork mode.
  132. if config.GetLinux().GetSecurityContext().GetNamespaceOptions().GetNetwork() == runtimeapi.NamespaceMode_NODE {
  133. return resp, nil
  134. }
  135. // Step 5: Setup networking for the sandbox.
  136. // All pod networking is setup by a CNI plugin discovered at startup time.
  137. // This plugin assigns the pod ip, sets up routes inside the sandbox,
  138. // creates interfaces etc. In theory, its jurisdiction ends with pod
  139. // sandbox networking, but it might insert iptables rules or open ports
  140. // on the host as well, to satisfy parts of the pod spec that aren't
  141. // recognized by the CNI standard yet.
  142. cID := kubecontainer.BuildContainerID(runtimeName, createResp.ID)
  143. networkOptions := make(map[string]string)
  144. if dnsConfig := config.GetDnsConfig(); dnsConfig != nil {
  145. // Build DNS options.
  146. dnsOption, err := json.Marshal(dnsConfig)
  147. if err != nil {
  148. return nil, fmt.Errorf("failed to marshal dns config for pod %q: %v", config.Metadata.Name, err)
  149. }
  150. networkOptions["dns"] = string(dnsOption)
  151. }
  152. err = ds.network.SetUpPod(config.GetMetadata().Namespace, config.GetMetadata().Name, cID, config.Annotations, networkOptions)
  153. if err != nil {
  154. errList := []error{fmt.Errorf("failed to set up sandbox container %q network for pod %q: %v", createResp.ID, config.Metadata.Name, err)}
  155. // Ensure network resources are cleaned up even if the plugin
  156. // succeeded but an error happened between that success and here.
  157. err = ds.network.TearDownPod(config.GetMetadata().Namespace, config.GetMetadata().Name, cID)
  158. if err != nil {
  159. errList = append(errList, fmt.Errorf("failed to clean up sandbox container %q network for pod %q: %v", createResp.ID, config.Metadata.Name, err))
  160. }
  161. err = ds.client.StopContainer(createResp.ID, defaultSandboxGracePeriod)
  162. if err != nil {
  163. errList = append(errList, fmt.Errorf("failed to stop sandbox container %q for pod %q: %v", createResp.ID, config.Metadata.Name, err))
  164. }
  165. return resp, utilerrors.NewAggregate(errList)
  166. }
  167. return resp, nil
  168. }
  169. // StopPodSandbox stops the sandbox. If there are any running containers in the
  170. // sandbox, they should be force terminated.
  171. // TODO: This function blocks sandbox teardown on networking teardown. Is it
  172. // better to cut our losses assuming an out of band GC routine will cleanup
  173. // after us?
  174. func (ds *dockerService) StopPodSandbox(ctx context.Context, r *runtimeapi.StopPodSandboxRequest) (*runtimeapi.StopPodSandboxResponse, error) {
  175. var namespace, name string
  176. var hostNetwork bool
  177. podSandboxID := r.PodSandboxId
  178. resp := &runtimeapi.StopPodSandboxResponse{}
  179. // Try to retrieve minimal sandbox information from docker daemon or sandbox checkpoint.
  180. inspectResult, metadata, statusErr := ds.getPodSandboxDetails(podSandboxID)
  181. if statusErr == nil {
  182. namespace = metadata.Namespace
  183. name = metadata.Name
  184. hostNetwork = (networkNamespaceMode(inspectResult) == runtimeapi.NamespaceMode_NODE)
  185. } else {
  186. checkpoint := NewPodSandboxCheckpoint("", "", &CheckpointData{})
  187. checkpointErr := ds.checkpointManager.GetCheckpoint(podSandboxID, checkpoint)
  188. // Proceed if both sandbox container and checkpoint could not be found. This means that following
  189. // actions will only have sandbox ID and not have pod namespace and name information.
  190. // Return error if encounter any unexpected error.
  191. if checkpointErr != nil {
  192. if checkpointErr != errors.ErrCheckpointNotFound {
  193. err := ds.checkpointManager.RemoveCheckpoint(podSandboxID)
  194. if err != nil {
  195. klog.Errorf("Failed to delete corrupt checkpoint for sandbox %q: %v", podSandboxID, err)
  196. }
  197. }
  198. if libdocker.IsContainerNotFoundError(statusErr) {
  199. klog.Warningf("Both sandbox container and checkpoint for id %q could not be found. "+
  200. "Proceed without further sandbox information.", podSandboxID)
  201. } else {
  202. return nil, utilerrors.NewAggregate([]error{
  203. fmt.Errorf("failed to get checkpoint for sandbox %q: %v", podSandboxID, checkpointErr),
  204. fmt.Errorf("failed to get sandbox status: %v", statusErr)})
  205. }
  206. } else {
  207. _, name, namespace, _, hostNetwork = checkpoint.GetData()
  208. }
  209. }
  210. // WARNING: The following operations made the following assumption:
  211. // 1. kubelet will retry on any error returned by StopPodSandbox.
  212. // 2. tearing down network and stopping sandbox container can succeed in any sequence.
  213. // This depends on the implementation detail of network plugin and proper error handling.
  214. // For kubenet, if tearing down network failed and sandbox container is stopped, kubelet
  215. // will retry. On retry, kubenet will not be able to retrieve network namespace of the sandbox
  216. // since it is stopped. With empty network namespcae, CNI bridge plugin will conduct best
  217. // effort clean up and will not return error.
  218. errList := []error{}
  219. ready, ok := ds.getNetworkReady(podSandboxID)
  220. if !hostNetwork && (ready || !ok) {
  221. // Only tear down the pod network if we haven't done so already
  222. cID := kubecontainer.BuildContainerID(runtimeName, podSandboxID)
  223. err := ds.network.TearDownPod(namespace, name, cID)
  224. if err == nil {
  225. ds.setNetworkReady(podSandboxID, false)
  226. } else {
  227. errList = append(errList, err)
  228. }
  229. }
  230. if err := ds.client.StopContainer(podSandboxID, defaultSandboxGracePeriod); err != nil {
  231. // Do not return error if the container does not exist
  232. if !libdocker.IsContainerNotFoundError(err) {
  233. klog.Errorf("Failed to stop sandbox %q: %v", podSandboxID, err)
  234. errList = append(errList, err)
  235. } else {
  236. // remove the checkpoint for any sandbox that is not found in the runtime
  237. ds.checkpointManager.RemoveCheckpoint(podSandboxID)
  238. }
  239. }
  240. if len(errList) == 0 {
  241. return resp, nil
  242. }
  243. // TODO: Stop all running containers in the sandbox.
  244. return nil, utilerrors.NewAggregate(errList)
  245. }
  246. // RemovePodSandbox removes the sandbox. If there are running containers in the
  247. // sandbox, they should be forcibly removed.
  248. func (ds *dockerService) RemovePodSandbox(ctx context.Context, r *runtimeapi.RemovePodSandboxRequest) (*runtimeapi.RemovePodSandboxResponse, error) {
  249. podSandboxID := r.PodSandboxId
  250. var errs []error
  251. opts := dockertypes.ContainerListOptions{All: true}
  252. opts.Filters = dockerfilters.NewArgs()
  253. f := newDockerFilter(&opts.Filters)
  254. f.AddLabel(sandboxIDLabelKey, podSandboxID)
  255. containers, err := ds.client.ListContainers(opts)
  256. if err != nil {
  257. errs = append(errs, err)
  258. }
  259. // Remove all containers in the sandbox.
  260. for i := range containers {
  261. if _, err := ds.RemoveContainer(ctx, &runtimeapi.RemoveContainerRequest{ContainerId: containers[i].ID}); err != nil && !libdocker.IsContainerNotFoundError(err) {
  262. errs = append(errs, err)
  263. }
  264. }
  265. // Remove the sandbox container.
  266. err = ds.client.RemoveContainer(podSandboxID, dockertypes.ContainerRemoveOptions{RemoveVolumes: true, Force: true})
  267. if err == nil || libdocker.IsContainerNotFoundError(err) {
  268. // Only clear network ready when the sandbox has actually been
  269. // removed from docker or doesn't exist
  270. ds.clearNetworkReady(podSandboxID)
  271. } else {
  272. errs = append(errs, err)
  273. }
  274. // Remove the checkpoint of the sandbox.
  275. if err := ds.checkpointManager.RemoveCheckpoint(podSandboxID); err != nil {
  276. errs = append(errs, err)
  277. }
  278. if len(errs) == 0 {
  279. return &runtimeapi.RemovePodSandboxResponse{}, nil
  280. }
  281. return nil, utilerrors.NewAggregate(errs)
  282. }
  283. // getIPFromPlugin interrogates the network plugin for an IP.
  284. func (ds *dockerService) getIPFromPlugin(sandbox *dockertypes.ContainerJSON) (string, error) {
  285. metadata, err := parseSandboxName(sandbox.Name)
  286. if err != nil {
  287. return "", err
  288. }
  289. msg := fmt.Sprintf("Couldn't find network status for %s/%s through plugin", metadata.Namespace, metadata.Name)
  290. cID := kubecontainer.BuildContainerID(runtimeName, sandbox.ID)
  291. networkStatus, err := ds.network.GetPodNetworkStatus(metadata.Namespace, metadata.Name, cID)
  292. if err != nil {
  293. return "", err
  294. }
  295. if networkStatus == nil {
  296. return "", fmt.Errorf("%v: invalid network status for", msg)
  297. }
  298. return networkStatus.IP.String(), nil
  299. }
  300. // getIP returns the ip given the output of `docker inspect` on a pod sandbox,
  301. // first interrogating any registered plugins, then simply trusting the ip
  302. // in the sandbox itself. We look for an ipv4 address before ipv6.
  303. func (ds *dockerService) getIP(podSandboxID string, sandbox *dockertypes.ContainerJSON) string {
  304. if sandbox.NetworkSettings == nil {
  305. return ""
  306. }
  307. if networkNamespaceMode(sandbox) == runtimeapi.NamespaceMode_NODE {
  308. // For sandboxes using host network, the shim is not responsible for
  309. // reporting the IP.
  310. return ""
  311. }
  312. // Don't bother getting IP if the pod is known and networking isn't ready
  313. ready, ok := ds.getNetworkReady(podSandboxID)
  314. if ok && !ready {
  315. return ""
  316. }
  317. ip, err := ds.getIPFromPlugin(sandbox)
  318. if err == nil {
  319. return ip
  320. }
  321. // TODO: trusting the docker ip is not a great idea. However docker uses
  322. // eth0 by default and so does CNI, so if we find a docker IP here, we
  323. // conclude that the plugin must have failed setup, or forgotten its ip.
  324. // This is not a sensible assumption for plugins across the board, but if
  325. // a plugin doesn't want this behavior, it can throw an error.
  326. if sandbox.NetworkSettings.IPAddress != "" {
  327. return sandbox.NetworkSettings.IPAddress
  328. }
  329. if sandbox.NetworkSettings.GlobalIPv6Address != "" {
  330. return sandbox.NetworkSettings.GlobalIPv6Address
  331. }
  332. // If all else fails, warn but don't return an error, as pod status
  333. // should generally not return anything except fatal errors
  334. // FIXME: handle network errors by restarting the pod somehow?
  335. klog.Warningf("failed to read pod IP from plugin/docker: %v", err)
  336. return ""
  337. }
  338. // Returns the inspect container response, the sandbox metadata, and network namespace mode
  339. func (ds *dockerService) getPodSandboxDetails(podSandboxID string) (*dockertypes.ContainerJSON, *runtimeapi.PodSandboxMetadata, error) {
  340. resp, err := ds.client.InspectContainer(podSandboxID)
  341. if err != nil {
  342. return nil, nil, err
  343. }
  344. metadata, err := parseSandboxName(resp.Name)
  345. if err != nil {
  346. return nil, nil, err
  347. }
  348. return resp, metadata, nil
  349. }
  350. // PodSandboxStatus returns the status of the PodSandbox.
  351. func (ds *dockerService) PodSandboxStatus(ctx context.Context, req *runtimeapi.PodSandboxStatusRequest) (*runtimeapi.PodSandboxStatusResponse, error) {
  352. podSandboxID := req.PodSandboxId
  353. r, metadata, err := ds.getPodSandboxDetails(podSandboxID)
  354. if err != nil {
  355. return nil, err
  356. }
  357. // Parse the timestamps.
  358. createdAt, _, _, err := getContainerTimestamps(r)
  359. if err != nil {
  360. return nil, fmt.Errorf("failed to parse timestamp for container %q: %v", podSandboxID, err)
  361. }
  362. ct := createdAt.UnixNano()
  363. // Translate container to sandbox state.
  364. state := runtimeapi.PodSandboxState_SANDBOX_NOTREADY
  365. if r.State.Running {
  366. state = runtimeapi.PodSandboxState_SANDBOX_READY
  367. }
  368. var IP string
  369. // TODO: Remove this when sandbox is available on windows
  370. // This is a workaround for windows, where sandbox is not in use, and pod IP is determined through containers belonging to the Pod.
  371. if IP = ds.determinePodIPBySandboxID(podSandboxID); IP == "" {
  372. IP = ds.getIP(podSandboxID, r)
  373. }
  374. labels, annotations := extractLabels(r.Config.Labels)
  375. status := &runtimeapi.PodSandboxStatus{
  376. Id: r.ID,
  377. State: state,
  378. CreatedAt: ct,
  379. Metadata: metadata,
  380. Labels: labels,
  381. Annotations: annotations,
  382. Network: &runtimeapi.PodSandboxNetworkStatus{
  383. Ip: IP,
  384. },
  385. Linux: &runtimeapi.LinuxPodSandboxStatus{
  386. Namespaces: &runtimeapi.Namespace{
  387. Options: &runtimeapi.NamespaceOption{
  388. Network: networkNamespaceMode(r),
  389. Pid: pidNamespaceMode(r),
  390. Ipc: ipcNamespaceMode(r),
  391. },
  392. },
  393. },
  394. }
  395. return &runtimeapi.PodSandboxStatusResponse{Status: status}, nil
  396. }
  397. // ListPodSandbox returns a list of Sandbox.
  398. func (ds *dockerService) ListPodSandbox(_ context.Context, r *runtimeapi.ListPodSandboxRequest) (*runtimeapi.ListPodSandboxResponse, error) {
  399. filter := r.GetFilter()
  400. // By default, list all containers whether they are running or not.
  401. opts := dockertypes.ContainerListOptions{All: true}
  402. filterOutReadySandboxes := false
  403. opts.Filters = dockerfilters.NewArgs()
  404. f := newDockerFilter(&opts.Filters)
  405. // Add filter to select only sandbox containers.
  406. f.AddLabel(containerTypeLabelKey, containerTypeLabelSandbox)
  407. if filter != nil {
  408. if filter.Id != "" {
  409. f.Add("id", filter.Id)
  410. }
  411. if filter.State != nil {
  412. if filter.GetState().State == runtimeapi.PodSandboxState_SANDBOX_READY {
  413. // Only list running containers.
  414. opts.All = false
  415. } else {
  416. // runtimeapi.PodSandboxState_SANDBOX_NOTREADY can mean the
  417. // container is in any of the non-running state (e.g., created,
  418. // exited). We can't tell docker to filter out running
  419. // containers directly, so we'll need to filter them out
  420. // ourselves after getting the results.
  421. filterOutReadySandboxes = true
  422. }
  423. }
  424. if filter.LabelSelector != nil {
  425. for k, v := range filter.LabelSelector {
  426. f.AddLabel(k, v)
  427. }
  428. }
  429. }
  430. // Make sure we get the list of checkpoints first so that we don't include
  431. // new PodSandboxes that are being created right now.
  432. var err error
  433. checkpoints := []string{}
  434. if filter == nil {
  435. checkpoints, err = ds.checkpointManager.ListCheckpoints()
  436. if err != nil {
  437. klog.Errorf("Failed to list checkpoints: %v", err)
  438. }
  439. }
  440. containers, err := ds.client.ListContainers(opts)
  441. if err != nil {
  442. return nil, err
  443. }
  444. // Convert docker containers to runtime api sandboxes.
  445. result := []*runtimeapi.PodSandbox{}
  446. // using map as set
  447. sandboxIDs := make(map[string]bool)
  448. for i := range containers {
  449. c := containers[i]
  450. converted, err := containerToRuntimeAPISandbox(&c)
  451. if err != nil {
  452. klog.V(4).Infof("Unable to convert docker to runtime API sandbox %+v: %v", c, err)
  453. continue
  454. }
  455. if filterOutReadySandboxes && converted.State == runtimeapi.PodSandboxState_SANDBOX_READY {
  456. continue
  457. }
  458. sandboxIDs[converted.Id] = true
  459. result = append(result, converted)
  460. }
  461. // Include sandbox that could only be found with its checkpoint if no filter is applied
  462. // These PodSandbox will only include PodSandboxID, Name, Namespace.
  463. // These PodSandbox will be in PodSandboxState_SANDBOX_NOTREADY state.
  464. for _, id := range checkpoints {
  465. if _, ok := sandboxIDs[id]; ok {
  466. continue
  467. }
  468. checkpoint := NewPodSandboxCheckpoint("", "", &CheckpointData{})
  469. err := ds.checkpointManager.GetCheckpoint(id, checkpoint)
  470. if err != nil {
  471. klog.Errorf("Failed to retrieve checkpoint for sandbox %q: %v", id, err)
  472. if err == errors.ErrCorruptCheckpoint {
  473. err = ds.checkpointManager.RemoveCheckpoint(id)
  474. if err != nil {
  475. klog.Errorf("Failed to delete corrupt checkpoint for sandbox %q: %v", id, err)
  476. }
  477. }
  478. continue
  479. }
  480. result = append(result, checkpointToRuntimeAPISandbox(id, checkpoint))
  481. }
  482. return &runtimeapi.ListPodSandboxResponse{Items: result}, nil
  483. }
  484. // applySandboxLinuxOptions applies LinuxPodSandboxConfig to dockercontainer.HostConfig and dockercontainer.ContainerCreateConfig.
  485. func (ds *dockerService) applySandboxLinuxOptions(hc *dockercontainer.HostConfig, lc *runtimeapi.LinuxPodSandboxConfig, createConfig *dockertypes.ContainerCreateConfig, image string, separator rune) error {
  486. if lc == nil {
  487. return nil
  488. }
  489. // Apply security context.
  490. if err := applySandboxSecurityContext(lc, createConfig.Config, hc, ds.network, separator); err != nil {
  491. return err
  492. }
  493. // Set sysctls.
  494. hc.Sysctls = lc.Sysctls
  495. return nil
  496. }
  497. func (ds *dockerService) applySandboxResources(hc *dockercontainer.HostConfig, lc *runtimeapi.LinuxPodSandboxConfig) error {
  498. hc.Resources = dockercontainer.Resources{
  499. MemorySwap: DefaultMemorySwap(),
  500. CPUShares: defaultSandboxCPUshares,
  501. // Use docker's default cpu quota/period.
  502. }
  503. if lc != nil {
  504. // Apply Cgroup options.
  505. cgroupParent, err := ds.GenerateExpectedCgroupParent(lc.CgroupParent)
  506. if err != nil {
  507. return err
  508. }
  509. hc.CgroupParent = cgroupParent
  510. }
  511. return nil
  512. }
  513. // makeSandboxDockerConfig returns dockertypes.ContainerCreateConfig based on runtimeapi.PodSandboxConfig.
  514. func (ds *dockerService) makeSandboxDockerConfig(c *runtimeapi.PodSandboxConfig, image string) (*dockertypes.ContainerCreateConfig, error) {
  515. // Merge annotations and labels because docker supports only labels.
  516. labels := makeLabels(c.GetLabels(), c.GetAnnotations())
  517. // Apply a label to distinguish sandboxes from regular containers.
  518. labels[containerTypeLabelKey] = containerTypeLabelSandbox
  519. // Apply a container name label for infra container. This is used in summary v1.
  520. // TODO(random-liu): Deprecate this label once container metrics is directly got from CRI.
  521. labels[types.KubernetesContainerNameLabel] = sandboxContainerName
  522. hc := &dockercontainer.HostConfig{
  523. IpcMode: dockercontainer.IpcMode("shareable"),
  524. }
  525. createConfig := &dockertypes.ContainerCreateConfig{
  526. Name: makeSandboxName(c),
  527. Config: &dockercontainer.Config{
  528. Hostname: c.Hostname,
  529. // TODO: Handle environment variables.
  530. Image: image,
  531. Labels: labels,
  532. },
  533. HostConfig: hc,
  534. }
  535. // Apply linux-specific options.
  536. if err := ds.applySandboxLinuxOptions(hc, c.GetLinux(), createConfig, image, securityOptSeparator); err != nil {
  537. return nil, err
  538. }
  539. // Set port mappings.
  540. exposedPorts, portBindings := makePortsAndBindings(c.GetPortMappings())
  541. createConfig.Config.ExposedPorts = exposedPorts
  542. hc.PortBindings = portBindings
  543. // TODO: Get rid of the dependency on kubelet internal package.
  544. hc.OomScoreAdj = qos.PodInfraOOMAdj
  545. // Apply resource options.
  546. if err := ds.applySandboxResources(hc, c.GetLinux()); err != nil {
  547. return nil, err
  548. }
  549. // Set security options.
  550. securityOpts, err := ds.getSecurityOpts(c.GetLinux().GetSecurityContext().GetSeccompProfilePath(), securityOptSeparator)
  551. if err != nil {
  552. return nil, fmt.Errorf("failed to generate sandbox security options for sandbox %q: %v", c.Metadata.Name, err)
  553. }
  554. hc.SecurityOpt = append(hc.SecurityOpt, securityOpts...)
  555. applyExperimentalCreateConfig(createConfig, c.Annotations)
  556. return createConfig, nil
  557. }
  558. // networkNamespaceMode returns the network runtimeapi.NamespaceMode for this container.
  559. // Supports: POD, NODE
  560. func networkNamespaceMode(container *dockertypes.ContainerJSON) runtimeapi.NamespaceMode {
  561. if container != nil && container.HostConfig != nil && string(container.HostConfig.NetworkMode) == namespaceModeHost {
  562. return runtimeapi.NamespaceMode_NODE
  563. }
  564. return runtimeapi.NamespaceMode_POD
  565. }
  566. // pidNamespaceMode returns the PID runtimeapi.NamespaceMode for this container.
  567. // Supports: CONTAINER, NODE
  568. // TODO(verb): add support for POD PID namespace sharing
  569. func pidNamespaceMode(container *dockertypes.ContainerJSON) runtimeapi.NamespaceMode {
  570. if container != nil && container.HostConfig != nil && string(container.HostConfig.PidMode) == namespaceModeHost {
  571. return runtimeapi.NamespaceMode_NODE
  572. }
  573. return runtimeapi.NamespaceMode_CONTAINER
  574. }
  575. // ipcNamespaceMode returns the IPC runtimeapi.NamespaceMode for this container.
  576. // Supports: POD, NODE
  577. func ipcNamespaceMode(container *dockertypes.ContainerJSON) runtimeapi.NamespaceMode {
  578. if container != nil && container.HostConfig != nil && string(container.HostConfig.IpcMode) == namespaceModeHost {
  579. return runtimeapi.NamespaceMode_NODE
  580. }
  581. return runtimeapi.NamespaceMode_POD
  582. }
  583. func constructPodSandboxCheckpoint(config *runtimeapi.PodSandboxConfig) checkpointmanager.Checkpoint {
  584. data := CheckpointData{}
  585. for _, pm := range config.GetPortMappings() {
  586. proto := toCheckpointProtocol(pm.Protocol)
  587. data.PortMappings = append(data.PortMappings, &PortMapping{
  588. HostPort: &pm.HostPort,
  589. ContainerPort: &pm.ContainerPort,
  590. Protocol: &proto,
  591. HostIP: pm.HostIp,
  592. })
  593. }
  594. if config.GetLinux().GetSecurityContext().GetNamespaceOptions().GetNetwork() == runtimeapi.NamespaceMode_NODE {
  595. data.HostNetwork = true
  596. }
  597. return NewPodSandboxCheckpoint(config.Metadata.Namespace, config.Metadata.Name, &data)
  598. }
  599. func toCheckpointProtocol(protocol runtimeapi.Protocol) Protocol {
  600. switch protocol {
  601. case runtimeapi.Protocol_TCP:
  602. return protocolTCP
  603. case runtimeapi.Protocol_UDP:
  604. return protocolUDP
  605. case runtimeapi.Protocol_SCTP:
  606. return protocolSCTP
  607. }
  608. klog.Warningf("Unknown protocol %q: defaulting to TCP", protocol)
  609. return protocolTCP
  610. }
  611. // rewriteResolvFile rewrites resolv.conf file generated by docker.
  612. func rewriteResolvFile(resolvFilePath string, dns []string, dnsSearch []string, dnsOptions []string) error {
  613. if len(resolvFilePath) == 0 {
  614. klog.Errorf("ResolvConfPath is empty.")
  615. return nil
  616. }
  617. if _, err := os.Stat(resolvFilePath); os.IsNotExist(err) {
  618. return fmt.Errorf("ResolvConfPath %q does not exist", resolvFilePath)
  619. }
  620. var resolvFileContent []string
  621. for _, srv := range dns {
  622. resolvFileContent = append(resolvFileContent, "nameserver "+srv)
  623. }
  624. if len(dnsSearch) > 0 {
  625. resolvFileContent = append(resolvFileContent, "search "+strings.Join(dnsSearch, " "))
  626. }
  627. if len(dnsOptions) > 0 {
  628. resolvFileContent = append(resolvFileContent, "options "+strings.Join(dnsOptions, " "))
  629. }
  630. if len(resolvFileContent) > 0 {
  631. resolvFileContentStr := strings.Join(resolvFileContent, "\n")
  632. resolvFileContentStr += "\n"
  633. klog.V(4).Infof("Will attempt to re-write config file %s with: \n%s", resolvFilePath, resolvFileContent)
  634. if err := rewriteFile(resolvFilePath, resolvFileContentStr); err != nil {
  635. klog.Errorf("resolv.conf could not be updated: %v", err)
  636. return err
  637. }
  638. }
  639. return nil
  640. }
  641. func rewriteFile(filePath, stringToWrite string) error {
  642. f, err := os.OpenFile(filePath, os.O_TRUNC|os.O_WRONLY, 0644)
  643. if err != nil {
  644. return err
  645. }
  646. defer f.Close()
  647. _, err = f.WriteString(stringToWrite)
  648. return err
  649. }