container_gc.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. /*
  2. Copyright 2014 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 dockertools
  14. import (
  15. "fmt"
  16. "os"
  17. "path"
  18. "path/filepath"
  19. "sort"
  20. "time"
  21. dockertypes "github.com/docker/engine-api/types"
  22. "github.com/golang/glog"
  23. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  24. "k8s.io/kubernetes/pkg/types"
  25. )
  26. type containerGC struct {
  27. client DockerInterface
  28. podGetter podGetter
  29. containerLogsDir string
  30. }
  31. func NewContainerGC(client DockerInterface, podGetter podGetter, containerLogsDir string) *containerGC {
  32. return &containerGC{
  33. client: client,
  34. podGetter: podGetter,
  35. containerLogsDir: containerLogsDir,
  36. }
  37. }
  38. // Internal information kept for containers being considered for GC.
  39. type containerGCInfo struct {
  40. // Docker ID of the container.
  41. id string
  42. // Docker name of the container.
  43. name string
  44. // Creation time for the container.
  45. createTime time.Time
  46. // Full pod name, including namespace in the format `namespace_podName`.
  47. // This comes from dockertools.ParseDockerName(...)
  48. podNameWithNamespace string
  49. // Container name in pod
  50. containerName string
  51. }
  52. // Containers are considered for eviction as units of (UID, container name) pair.
  53. type evictUnit struct {
  54. // UID of the pod.
  55. uid types.UID
  56. // Name of the container in the pod.
  57. name string
  58. }
  59. type containersByEvictUnit map[evictUnit][]containerGCInfo
  60. // Returns the number of containers in this map.
  61. func (cu containersByEvictUnit) NumContainers() int {
  62. num := 0
  63. for key := range cu {
  64. num += len(cu[key])
  65. }
  66. return num
  67. }
  68. // Returns the number of pod in this map.
  69. func (cu containersByEvictUnit) NumEvictUnits() int {
  70. return len(cu)
  71. }
  72. // Newest first.
  73. type byCreated []containerGCInfo
  74. func (a byCreated) Len() int { return len(a) }
  75. func (a byCreated) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
  76. func (a byCreated) Less(i, j int) bool { return a[i].createTime.After(a[j].createTime) }
  77. func (cgc *containerGC) enforceMaxContainersPerEvictUnit(evictUnits containersByEvictUnit, MaxContainers int) {
  78. for uid := range evictUnits {
  79. toRemove := len(evictUnits[uid]) - MaxContainers
  80. if toRemove > 0 {
  81. evictUnits[uid] = cgc.removeOldestN(evictUnits[uid], toRemove)
  82. }
  83. }
  84. }
  85. // Removes the oldest toRemove containers and returns the resulting slice.
  86. func (cgc *containerGC) removeOldestN(containers []containerGCInfo, toRemove int) []containerGCInfo {
  87. // Remove from oldest to newest (last to first).
  88. numToKeep := len(containers) - toRemove
  89. for i := numToKeep; i < len(containers); i++ {
  90. cgc.removeContainer(containers[i].id, containers[i].podNameWithNamespace, containers[i].containerName)
  91. }
  92. // Assume we removed the containers so that we're not too aggressive.
  93. return containers[:numToKeep]
  94. }
  95. // Get all containers that are evictable. Evictable containers are: not running
  96. // and created more than MinAge ago.
  97. func (cgc *containerGC) evictableContainers(minAge time.Duration) (containersByEvictUnit, []containerGCInfo, error) {
  98. containers, err := GetKubeletDockerContainers(cgc.client, true)
  99. if err != nil {
  100. return containersByEvictUnit{}, []containerGCInfo{}, err
  101. }
  102. unidentifiedContainers := make([]containerGCInfo, 0)
  103. evictUnits := make(containersByEvictUnit)
  104. newestGCTime := time.Now().Add(-minAge)
  105. for _, container := range containers {
  106. // Prune out running containers.
  107. data, err := cgc.client.InspectContainer(container.ID)
  108. if err != nil {
  109. // Container may have been removed already, skip.
  110. continue
  111. } else if data.State.Running {
  112. continue
  113. }
  114. created, err := ParseDockerTimestamp(data.Created)
  115. if err != nil {
  116. glog.Errorf("Failed to parse Created timestamp %q for container %q", data.Created, container.ID)
  117. }
  118. if newestGCTime.Before(created) {
  119. continue
  120. }
  121. containerInfo := containerGCInfo{
  122. id: container.ID,
  123. name: container.Names[0],
  124. createTime: created,
  125. }
  126. containerName, _, err := ParseDockerName(container.Names[0])
  127. if err != nil {
  128. unidentifiedContainers = append(unidentifiedContainers, containerInfo)
  129. } else {
  130. key := evictUnit{
  131. uid: containerName.PodUID,
  132. name: containerName.ContainerName,
  133. }
  134. containerInfo.podNameWithNamespace = containerName.PodFullName
  135. containerInfo.containerName = containerName.ContainerName
  136. evictUnits[key] = append(evictUnits[key], containerInfo)
  137. }
  138. }
  139. // Sort the containers by age.
  140. for uid := range evictUnits {
  141. sort.Sort(byCreated(evictUnits[uid]))
  142. }
  143. return evictUnits, unidentifiedContainers, nil
  144. }
  145. // GarbageCollect removes dead containers using the specified container gc policy
  146. func (cgc *containerGC) GarbageCollect(gcPolicy kubecontainer.ContainerGCPolicy, allSourcesReady bool) error {
  147. // Separate containers by evict units.
  148. evictUnits, unidentifiedContainers, err := cgc.evictableContainers(gcPolicy.MinAge)
  149. if err != nil {
  150. return err
  151. }
  152. // Remove unidentified containers.
  153. for _, container := range unidentifiedContainers {
  154. glog.Infof("Removing unidentified dead container %q with ID %q", container.name, container.id)
  155. err = cgc.client.RemoveContainer(container.id, dockertypes.ContainerRemoveOptions{RemoveVolumes: true})
  156. if err != nil {
  157. glog.Warningf("Failed to remove unidentified dead container %q: %v", container.name, err)
  158. }
  159. }
  160. // Remove deleted pod containers if all sources are ready.
  161. if allSourcesReady {
  162. for key, unit := range evictUnits {
  163. if cgc.isPodDeleted(key.uid) {
  164. cgc.removeOldestN(unit, len(unit)) // Remove all.
  165. delete(evictUnits, key)
  166. }
  167. }
  168. }
  169. // Enforce max containers per evict unit.
  170. if gcPolicy.MaxPerPodContainer >= 0 {
  171. cgc.enforceMaxContainersPerEvictUnit(evictUnits, gcPolicy.MaxPerPodContainer)
  172. }
  173. // Enforce max total number of containers.
  174. if gcPolicy.MaxContainers >= 0 && evictUnits.NumContainers() > gcPolicy.MaxContainers {
  175. // Leave an equal number of containers per evict unit (min: 1).
  176. numContainersPerEvictUnit := gcPolicy.MaxContainers / evictUnits.NumEvictUnits()
  177. if numContainersPerEvictUnit < 1 {
  178. numContainersPerEvictUnit = 1
  179. }
  180. cgc.enforceMaxContainersPerEvictUnit(evictUnits, numContainersPerEvictUnit)
  181. // If we still need to evict, evict oldest first.
  182. numContainers := evictUnits.NumContainers()
  183. if numContainers > gcPolicy.MaxContainers {
  184. flattened := make([]containerGCInfo, 0, numContainers)
  185. for uid := range evictUnits {
  186. flattened = append(flattened, evictUnits[uid]...)
  187. }
  188. sort.Sort(byCreated(flattened))
  189. cgc.removeOldestN(flattened, numContainers-gcPolicy.MaxContainers)
  190. }
  191. }
  192. // Remove dead symlinks - should only happen on upgrade
  193. // from a k8s version without proper log symlink cleanup
  194. logSymlinks, _ := filepath.Glob(path.Join(cgc.containerLogsDir, fmt.Sprintf("*.%s", LogSuffix)))
  195. for _, logSymlink := range logSymlinks {
  196. if _, err = os.Stat(logSymlink); os.IsNotExist(err) {
  197. err = os.Remove(logSymlink)
  198. if err != nil {
  199. glog.Warningf("Failed to remove container log dead symlink %q: %v", logSymlink, err)
  200. }
  201. }
  202. }
  203. return nil
  204. }
  205. func (cgc *containerGC) removeContainer(id string, podNameWithNamespace string, containerName string) {
  206. glog.V(4).Infof("Removing container %q name %q", id, containerName)
  207. err := cgc.client.RemoveContainer(id, dockertypes.ContainerRemoveOptions{RemoveVolumes: true})
  208. if err != nil {
  209. glog.Warningf("Failed to remove container %q: %v", id, err)
  210. }
  211. symlinkPath := LogSymlink(cgc.containerLogsDir, podNameWithNamespace, containerName, id)
  212. err = os.Remove(symlinkPath)
  213. if err != nil && !os.IsNotExist(err) {
  214. glog.Warningf("Failed to remove container %q log symlink %q: %v", id, symlinkPath, err)
  215. }
  216. }
  217. func (cgc *containerGC) deleteContainer(id string) error {
  218. containerInfo, err := cgc.client.InspectContainer(id)
  219. if err != nil {
  220. glog.Warningf("Failed to inspect container %q: %v", id, err)
  221. return err
  222. }
  223. if containerInfo.State.Running {
  224. return fmt.Errorf("container %q is still running", id)
  225. }
  226. containerName, _, err := ParseDockerName(containerInfo.Name)
  227. if err != nil {
  228. return err
  229. }
  230. cgc.removeContainer(id, containerName.PodFullName, containerName.ContainerName)
  231. return nil
  232. }
  233. func (cgc *containerGC) isPodDeleted(podUID types.UID) bool {
  234. _, found := cgc.podGetter.GetPodByUID(podUID)
  235. return !found
  236. }