container_manager_linux.go 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913
  1. // +build linux
  2. /*
  3. Copyright 2015 The Kubernetes Authors.
  4. Licensed under the Apache License, Version 2.0 (the "License");
  5. you may not use this file except in compliance with the License.
  6. You may obtain a copy of the License at
  7. http://www.apache.org/licenses/LICENSE-2.0
  8. Unless required by applicable law or agreed to in writing, software
  9. distributed under the License is distributed on an "AS IS" BASIS,
  10. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. See the License for the specific language governing permissions and
  12. limitations under the License.
  13. */
  14. package cm
  15. import (
  16. "bytes"
  17. "fmt"
  18. "io/ioutil"
  19. "os"
  20. "path"
  21. "strconv"
  22. "strings"
  23. "sync"
  24. "time"
  25. "github.com/opencontainers/runc/libcontainer/cgroups"
  26. "github.com/opencontainers/runc/libcontainer/cgroups/fs"
  27. "github.com/opencontainers/runc/libcontainer/configs"
  28. "k8s.io/klog"
  29. v1 "k8s.io/api/core/v1"
  30. "k8s.io/apimachinery/pkg/api/resource"
  31. utilerrors "k8s.io/apimachinery/pkg/util/errors"
  32. "k8s.io/apimachinery/pkg/util/sets"
  33. utilversion "k8s.io/apimachinery/pkg/util/version"
  34. "k8s.io/apimachinery/pkg/util/wait"
  35. utilfeature "k8s.io/apiserver/pkg/util/feature"
  36. "k8s.io/client-go/tools/record"
  37. internalapi "k8s.io/cri-api/pkg/apis"
  38. kubefeatures "k8s.io/kubernetes/pkg/features"
  39. podresourcesapi "k8s.io/kubernetes/pkg/kubelet/apis/podresources/v1alpha1"
  40. "k8s.io/kubernetes/pkg/kubelet/cadvisor"
  41. "k8s.io/kubernetes/pkg/kubelet/cm/cpumanager"
  42. "k8s.io/kubernetes/pkg/kubelet/cm/devicemanager"
  43. cmutil "k8s.io/kubernetes/pkg/kubelet/cm/util"
  44. "k8s.io/kubernetes/pkg/kubelet/config"
  45. kubecontainer "k8s.io/kubernetes/pkg/kubelet/container"
  46. "k8s.io/kubernetes/pkg/kubelet/lifecycle"
  47. "k8s.io/kubernetes/pkg/kubelet/pluginmanager/cache"
  48. "k8s.io/kubernetes/pkg/kubelet/qos"
  49. "k8s.io/kubernetes/pkg/kubelet/stats/pidlimit"
  50. "k8s.io/kubernetes/pkg/kubelet/status"
  51. schedulernodeinfo "k8s.io/kubernetes/pkg/scheduler/nodeinfo"
  52. "k8s.io/kubernetes/pkg/util/mount"
  53. "k8s.io/kubernetes/pkg/util/oom"
  54. "k8s.io/kubernetes/pkg/util/procfs"
  55. utilsysctl "k8s.io/kubernetes/pkg/util/sysctl"
  56. utilpath "k8s.io/utils/path"
  57. )
  58. const (
  59. // The percent of the machine memory capacity. The value is used to calculate
  60. // docker memory resource container's hardlimit to workaround docker memory
  61. // leakage issue. Please see kubernetes/issues/9881 for more detail.
  62. DockerMemoryLimitThresholdPercent = 70
  63. // The minimum memory limit allocated to docker container: 150Mi
  64. MinDockerMemoryLimit = 150 * 1024 * 1024
  65. dockerProcessName = "docker"
  66. dockerPidFile = "/var/run/docker.pid"
  67. containerdProcessName = "docker-containerd"
  68. containerdPidFile = "/run/docker/libcontainerd/docker-containerd.pid"
  69. )
  70. var (
  71. // The docker version in which containerd was introduced.
  72. containerdAPIVersion = utilversion.MustParseGeneric("1.23")
  73. )
  74. // A non-user container tracked by the Kubelet.
  75. type systemContainer struct {
  76. // Absolute name of the container.
  77. name string
  78. // CPU limit in millicores.
  79. cpuMillicores int64
  80. // Function that ensures the state of the container.
  81. // m is the cgroup manager for the specified container.
  82. ensureStateFunc func(m *fs.Manager) error
  83. // Manager for the cgroups of the external container.
  84. manager *fs.Manager
  85. }
  86. func newSystemCgroups(containerName string) *systemContainer {
  87. return &systemContainer{
  88. name: containerName,
  89. manager: createManager(containerName),
  90. }
  91. }
  92. type containerManagerImpl struct {
  93. sync.RWMutex
  94. cadvisorInterface cadvisor.Interface
  95. mountUtil mount.Interface
  96. NodeConfig
  97. status Status
  98. // External containers being managed.
  99. systemContainers []*systemContainer
  100. qosContainers QOSContainersInfo
  101. // Tasks that are run periodically
  102. periodicTasks []func()
  103. // Holds all the mounted cgroup subsystems
  104. subsystems *CgroupSubsystems
  105. nodeInfo *v1.Node
  106. // Interface for cgroup management
  107. cgroupManager CgroupManager
  108. // Capacity of this node.
  109. capacity v1.ResourceList
  110. // Capacity of this node, including internal resources.
  111. internalCapacity v1.ResourceList
  112. // Absolute cgroupfs path to a cgroup that Kubelet needs to place all pods under.
  113. // This path include a top level container for enforcing Node Allocatable.
  114. cgroupRoot CgroupName
  115. // Event recorder interface.
  116. recorder record.EventRecorder
  117. // Interface for QoS cgroup management
  118. qosContainerManager QOSContainerManager
  119. // Interface for exporting and allocating devices reported by device plugins.
  120. deviceManager devicemanager.Manager
  121. // Interface for CPU affinity management.
  122. cpuManager cpumanager.Manager
  123. }
  124. type features struct {
  125. cpuHardcapping bool
  126. }
  127. var _ ContainerManager = &containerManagerImpl{}
  128. // checks if the required cgroups subsystems are mounted.
  129. // As of now, only 'cpu' and 'memory' are required.
  130. // cpu quota is a soft requirement.
  131. func validateSystemRequirements(mountUtil mount.Interface) (features, error) {
  132. const (
  133. cgroupMountType = "cgroup"
  134. localErr = "system validation failed"
  135. )
  136. var (
  137. cpuMountPoint string
  138. f features
  139. )
  140. mountPoints, err := mountUtil.List()
  141. if err != nil {
  142. return f, fmt.Errorf("%s - %v", localErr, err)
  143. }
  144. expectedCgroups := sets.NewString("cpu", "cpuacct", "cpuset", "memory")
  145. for _, mountPoint := range mountPoints {
  146. if mountPoint.Type == cgroupMountType {
  147. for _, opt := range mountPoint.Opts {
  148. if expectedCgroups.Has(opt) {
  149. expectedCgroups.Delete(opt)
  150. }
  151. if opt == "cpu" {
  152. cpuMountPoint = mountPoint.Path
  153. }
  154. }
  155. }
  156. }
  157. if expectedCgroups.Len() > 0 {
  158. return f, fmt.Errorf("%s - Following Cgroup subsystem not mounted: %v", localErr, expectedCgroups.List())
  159. }
  160. // Check if cpu quota is available.
  161. // CPU cgroup is required and so it expected to be mounted at this point.
  162. periodExists, err := utilpath.Exists(utilpath.CheckFollowSymlink, path.Join(cpuMountPoint, "cpu.cfs_period_us"))
  163. if err != nil {
  164. klog.Errorf("failed to detect if CPU cgroup cpu.cfs_period_us is available - %v", err)
  165. }
  166. quotaExists, err := utilpath.Exists(utilpath.CheckFollowSymlink, path.Join(cpuMountPoint, "cpu.cfs_quota_us"))
  167. if err != nil {
  168. klog.Errorf("failed to detect if CPU cgroup cpu.cfs_quota_us is available - %v", err)
  169. }
  170. if quotaExists && periodExists {
  171. f.cpuHardcapping = true
  172. }
  173. return f, nil
  174. }
  175. // TODO(vmarmol): Add limits to the system containers.
  176. // Takes the absolute name of the specified containers.
  177. // Empty container name disables use of the specified container.
  178. func NewContainerManager(mountUtil mount.Interface, cadvisorInterface cadvisor.Interface, nodeConfig NodeConfig, failSwapOn bool, devicePluginEnabled bool, recorder record.EventRecorder) (ContainerManager, error) {
  179. // Mitigation of the issue fixed in master where hugetlb prefix for page sizes with "KiB"
  180. // is "kB" in runc, but the correct is "KB"
  181. // See https://github.com/opencontainers/runc/pull/2065
  182. // and https://github.com/kubernetes/kubernetes/pull/78495
  183. // for more info.
  184. for i, pageSize := range fs.HugePageSizes {
  185. fs.HugePageSizes[i] = strings.ReplaceAll(pageSize, "kB", "KB")
  186. }
  187. subsystems, err := GetCgroupSubsystems()
  188. if err != nil {
  189. return nil, fmt.Errorf("failed to get mounted cgroup subsystems: %v", err)
  190. }
  191. if failSwapOn {
  192. // Check whether swap is enabled. The Kubelet does not support running with swap enabled.
  193. swapData, err := ioutil.ReadFile("/proc/swaps")
  194. if err != nil {
  195. return nil, err
  196. }
  197. swapData = bytes.TrimSpace(swapData) // extra trailing \n
  198. swapLines := strings.Split(string(swapData), "\n")
  199. // If there is more than one line (table headers) in /proc/swaps, swap is enabled and we should
  200. // error out unless --fail-swap-on is set to false.
  201. if len(swapLines) > 1 {
  202. return nil, fmt.Errorf("Running with swap on is not supported, please disable swap! or set --fail-swap-on flag to false. /proc/swaps contained: %v", swapLines)
  203. }
  204. }
  205. var capacity = v1.ResourceList{}
  206. var internalCapacity = v1.ResourceList{}
  207. // It is safe to invoke `MachineInfo` on cAdvisor before logically initializing cAdvisor here because
  208. // machine info is computed and cached once as part of cAdvisor object creation.
  209. // But `RootFsInfo` and `ImagesFsInfo` are not available at this moment so they will be called later during manager starts
  210. machineInfo, err := cadvisorInterface.MachineInfo()
  211. if err != nil {
  212. return nil, err
  213. }
  214. capacity = cadvisor.CapacityFromMachineInfo(machineInfo)
  215. for k, v := range capacity {
  216. internalCapacity[k] = v
  217. }
  218. pidlimits, err := pidlimit.Stats()
  219. if err == nil && pidlimits != nil && pidlimits.MaxPID != nil {
  220. internalCapacity[pidlimit.PIDs] = *resource.NewQuantity(
  221. int64(*pidlimits.MaxPID),
  222. resource.DecimalSI)
  223. }
  224. // Turn CgroupRoot from a string (in cgroupfs path format) to internal CgroupName
  225. cgroupRoot := ParseCgroupfsToCgroupName(nodeConfig.CgroupRoot)
  226. cgroupManager := NewCgroupManager(subsystems, nodeConfig.CgroupDriver)
  227. // Check if Cgroup-root actually exists on the node
  228. if nodeConfig.CgroupsPerQOS {
  229. // this does default to / when enabled, but this tests against regressions.
  230. if nodeConfig.CgroupRoot == "" {
  231. return nil, fmt.Errorf("invalid configuration: cgroups-per-qos was specified and cgroup-root was not specified. To enable the QoS cgroup hierarchy you need to specify a valid cgroup-root")
  232. }
  233. // we need to check that the cgroup root actually exists for each subsystem
  234. // of note, we always use the cgroupfs driver when performing this check since
  235. // the input is provided in that format.
  236. // this is important because we do not want any name conversion to occur.
  237. if !cgroupManager.Exists(cgroupRoot) {
  238. return nil, fmt.Errorf("invalid configuration: cgroup-root %q doesn't exist", cgroupRoot)
  239. }
  240. klog.Infof("container manager verified user specified cgroup-root exists: %v", cgroupRoot)
  241. // Include the top level cgroup for enforcing node allocatable into cgroup-root.
  242. // This way, all sub modules can avoid having to understand the concept of node allocatable.
  243. cgroupRoot = NewCgroupName(cgroupRoot, defaultNodeAllocatableCgroupName)
  244. }
  245. klog.Infof("Creating Container Manager object based on Node Config: %+v", nodeConfig)
  246. qosContainerManager, err := NewQOSContainerManager(subsystems, cgroupRoot, nodeConfig, cgroupManager)
  247. if err != nil {
  248. return nil, err
  249. }
  250. cm := &containerManagerImpl{
  251. cadvisorInterface: cadvisorInterface,
  252. mountUtil: mountUtil,
  253. NodeConfig: nodeConfig,
  254. subsystems: subsystems,
  255. cgroupManager: cgroupManager,
  256. capacity: capacity,
  257. internalCapacity: internalCapacity,
  258. cgroupRoot: cgroupRoot,
  259. recorder: recorder,
  260. qosContainerManager: qosContainerManager,
  261. }
  262. klog.Infof("Creating device plugin manager: %t", devicePluginEnabled)
  263. if devicePluginEnabled {
  264. cm.deviceManager, err = devicemanager.NewManagerImpl()
  265. } else {
  266. cm.deviceManager, err = devicemanager.NewManagerStub()
  267. }
  268. if err != nil {
  269. return nil, err
  270. }
  271. // Initialize CPU manager
  272. if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CPUManager) {
  273. cm.cpuManager, err = cpumanager.NewManager(
  274. nodeConfig.ExperimentalCPUManagerPolicy,
  275. nodeConfig.ExperimentalCPUManagerReconcilePeriod,
  276. machineInfo,
  277. cm.GetNodeAllocatableReservation(),
  278. nodeConfig.KubeletRootDir,
  279. )
  280. if err != nil {
  281. klog.Errorf("failed to initialize cpu manager: %v", err)
  282. return nil, err
  283. }
  284. }
  285. return cm, nil
  286. }
  287. // NewPodContainerManager is a factory method returns a PodContainerManager object
  288. // If qosCgroups are enabled then it returns the general pod container manager
  289. // otherwise it returns a no-op manager which essentially does nothing
  290. func (cm *containerManagerImpl) NewPodContainerManager() PodContainerManager {
  291. if cm.NodeConfig.CgroupsPerQOS {
  292. return &podContainerManagerImpl{
  293. qosContainersInfo: cm.GetQOSContainersInfo(),
  294. subsystems: cm.subsystems,
  295. cgroupManager: cm.cgroupManager,
  296. podPidsLimit: cm.ExperimentalPodPidsLimit,
  297. enforceCPULimits: cm.EnforceCPULimits,
  298. cpuCFSQuotaPeriod: uint64(cm.CPUCFSQuotaPeriod / time.Microsecond),
  299. }
  300. }
  301. return &podContainerManagerNoop{
  302. cgroupRoot: cm.cgroupRoot,
  303. }
  304. }
  305. func (cm *containerManagerImpl) InternalContainerLifecycle() InternalContainerLifecycle {
  306. return &internalContainerLifecycleImpl{cm.cpuManager}
  307. }
  308. // Create a cgroup container manager.
  309. func createManager(containerName string) *fs.Manager {
  310. allowAllDevices := true
  311. return &fs.Manager{
  312. Cgroups: &configs.Cgroup{
  313. Parent: "/",
  314. Name: containerName,
  315. Resources: &configs.Resources{
  316. AllowAllDevices: &allowAllDevices,
  317. },
  318. },
  319. }
  320. }
  321. type KernelTunableBehavior string
  322. const (
  323. KernelTunableWarn KernelTunableBehavior = "warn"
  324. KernelTunableError KernelTunableBehavior = "error"
  325. KernelTunableModify KernelTunableBehavior = "modify"
  326. )
  327. // setupKernelTunables validates kernel tunable flags are set as expected
  328. // depending upon the specified option, it will either warn, error, or modify the kernel tunable flags
  329. func setupKernelTunables(option KernelTunableBehavior) error {
  330. desiredState := map[string]int{
  331. utilsysctl.VmOvercommitMemory: utilsysctl.VmOvercommitMemoryAlways,
  332. utilsysctl.VmPanicOnOOM: utilsysctl.VmPanicOnOOMInvokeOOMKiller,
  333. utilsysctl.KernelPanic: utilsysctl.KernelPanicRebootTimeout,
  334. utilsysctl.KernelPanicOnOops: utilsysctl.KernelPanicOnOopsAlways,
  335. utilsysctl.RootMaxKeys: utilsysctl.RootMaxKeysSetting,
  336. utilsysctl.RootMaxBytes: utilsysctl.RootMaxBytesSetting,
  337. }
  338. sysctl := utilsysctl.New()
  339. errList := []error{}
  340. for flag, expectedValue := range desiredState {
  341. val, err := sysctl.GetSysctl(flag)
  342. if err != nil {
  343. errList = append(errList, err)
  344. continue
  345. }
  346. if val == expectedValue {
  347. continue
  348. }
  349. switch option {
  350. case KernelTunableError:
  351. errList = append(errList, fmt.Errorf("Invalid kernel flag: %v, expected value: %v, actual value: %v", flag, expectedValue, val))
  352. case KernelTunableWarn:
  353. klog.V(2).Infof("Invalid kernel flag: %v, expected value: %v, actual value: %v", flag, expectedValue, val)
  354. case KernelTunableModify:
  355. klog.V(2).Infof("Updating kernel flag: %v, expected value: %v, actual value: %v", flag, expectedValue, val)
  356. err = sysctl.SetSysctl(flag, expectedValue)
  357. if err != nil {
  358. errList = append(errList, err)
  359. }
  360. }
  361. }
  362. return utilerrors.NewAggregate(errList)
  363. }
  364. func (cm *containerManagerImpl) setupNode(activePods ActivePodsFunc) error {
  365. f, err := validateSystemRequirements(cm.mountUtil)
  366. if err != nil {
  367. return err
  368. }
  369. if !f.cpuHardcapping {
  370. cm.status.SoftRequirements = fmt.Errorf("CPU hardcapping unsupported")
  371. }
  372. b := KernelTunableModify
  373. if cm.GetNodeConfig().ProtectKernelDefaults {
  374. b = KernelTunableError
  375. }
  376. if err := setupKernelTunables(b); err != nil {
  377. return err
  378. }
  379. // Setup top level qos containers only if CgroupsPerQOS flag is specified as true
  380. if cm.NodeConfig.CgroupsPerQOS {
  381. if err := cm.createNodeAllocatableCgroups(); err != nil {
  382. return err
  383. }
  384. err = cm.qosContainerManager.Start(cm.getNodeAllocatableAbsolute, activePods)
  385. if err != nil {
  386. return fmt.Errorf("failed to initialize top level QOS containers: %v", err)
  387. }
  388. }
  389. // Enforce Node Allocatable (if required)
  390. if err := cm.enforceNodeAllocatableCgroups(); err != nil {
  391. return err
  392. }
  393. systemContainers := []*systemContainer{}
  394. if cm.ContainerRuntime == "docker" {
  395. // With the docker-CRI integration, dockershim will manage the cgroups
  396. // and oom score for the docker processes.
  397. // In the future, NodeSpec should mandate the cgroup that the
  398. // runtime processes need to be in. For now, we still check the
  399. // cgroup for docker periodically, so that kubelet can recognize
  400. // the cgroup for docker and serve stats for the runtime.
  401. // TODO(#27097): Fix this after NodeSpec is clearly defined.
  402. cm.periodicTasks = append(cm.periodicTasks, func() {
  403. klog.V(4).Infof("[ContainerManager]: Adding periodic tasks for docker CRI integration")
  404. cont, err := getContainerNameForProcess(dockerProcessName, dockerPidFile)
  405. if err != nil {
  406. klog.Error(err)
  407. return
  408. }
  409. klog.V(2).Infof("[ContainerManager]: Discovered runtime cgroups name: %s", cont)
  410. cm.Lock()
  411. defer cm.Unlock()
  412. cm.RuntimeCgroupsName = cont
  413. })
  414. }
  415. if cm.SystemCgroupsName != "" {
  416. if cm.SystemCgroupsName == "/" {
  417. return fmt.Errorf("system container cannot be root (\"/\")")
  418. }
  419. cont := newSystemCgroups(cm.SystemCgroupsName)
  420. cont.ensureStateFunc = func(manager *fs.Manager) error {
  421. return ensureSystemCgroups("/", manager)
  422. }
  423. systemContainers = append(systemContainers, cont)
  424. }
  425. if cm.KubeletCgroupsName != "" {
  426. cont := newSystemCgroups(cm.KubeletCgroupsName)
  427. allowAllDevices := true
  428. manager := fs.Manager{
  429. Cgroups: &configs.Cgroup{
  430. Parent: "/",
  431. Name: cm.KubeletCgroupsName,
  432. Resources: &configs.Resources{
  433. AllowAllDevices: &allowAllDevices,
  434. },
  435. },
  436. }
  437. cont.ensureStateFunc = func(_ *fs.Manager) error {
  438. return ensureProcessInContainerWithOOMScore(os.Getpid(), qos.KubeletOOMScoreAdj, &manager)
  439. }
  440. systemContainers = append(systemContainers, cont)
  441. } else {
  442. cm.periodicTasks = append(cm.periodicTasks, func() {
  443. if err := ensureProcessInContainerWithOOMScore(os.Getpid(), qos.KubeletOOMScoreAdj, nil); err != nil {
  444. klog.Error(err)
  445. return
  446. }
  447. cont, err := getContainer(os.Getpid())
  448. if err != nil {
  449. klog.Errorf("failed to find cgroups of kubelet - %v", err)
  450. return
  451. }
  452. cm.Lock()
  453. defer cm.Unlock()
  454. cm.KubeletCgroupsName = cont
  455. })
  456. }
  457. cm.systemContainers = systemContainers
  458. return nil
  459. }
  460. func getContainerNameForProcess(name, pidFile string) (string, error) {
  461. pids, err := getPidsForProcess(name, pidFile)
  462. if err != nil {
  463. return "", fmt.Errorf("failed to detect process id for %q - %v", name, err)
  464. }
  465. if len(pids) == 0 {
  466. return "", nil
  467. }
  468. cont, err := getContainer(pids[0])
  469. if err != nil {
  470. return "", err
  471. }
  472. return cont, nil
  473. }
  474. func (cm *containerManagerImpl) GetNodeConfig() NodeConfig {
  475. cm.RLock()
  476. defer cm.RUnlock()
  477. return cm.NodeConfig
  478. }
  479. // GetPodCgroupRoot returns the literal cgroupfs value for the cgroup containing all pods.
  480. func (cm *containerManagerImpl) GetPodCgroupRoot() string {
  481. return cm.cgroupManager.Name(cm.cgroupRoot)
  482. }
  483. func (cm *containerManagerImpl) GetMountedSubsystems() *CgroupSubsystems {
  484. return cm.subsystems
  485. }
  486. func (cm *containerManagerImpl) GetQOSContainersInfo() QOSContainersInfo {
  487. return cm.qosContainerManager.GetQOSContainersInfo()
  488. }
  489. func (cm *containerManagerImpl) UpdateQOSCgroups() error {
  490. return cm.qosContainerManager.UpdateCgroups()
  491. }
  492. func (cm *containerManagerImpl) Status() Status {
  493. cm.RLock()
  494. defer cm.RUnlock()
  495. return cm.status
  496. }
  497. func (cm *containerManagerImpl) Start(node *v1.Node,
  498. activePods ActivePodsFunc,
  499. sourcesReady config.SourcesReady,
  500. podStatusProvider status.PodStatusProvider,
  501. runtimeService internalapi.RuntimeService) error {
  502. // Initialize CPU manager
  503. if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.CPUManager) {
  504. cm.cpuManager.Start(cpumanager.ActivePodsFunc(activePods), podStatusProvider, runtimeService)
  505. }
  506. // cache the node Info including resource capacity and
  507. // allocatable of the node
  508. cm.nodeInfo = node
  509. if utilfeature.DefaultFeatureGate.Enabled(kubefeatures.LocalStorageCapacityIsolation) {
  510. rootfs, err := cm.cadvisorInterface.RootFsInfo()
  511. if err != nil {
  512. return fmt.Errorf("failed to get rootfs info: %v", err)
  513. }
  514. for rName, rCap := range cadvisor.EphemeralStorageCapacityFromFsInfo(rootfs) {
  515. cm.capacity[rName] = rCap
  516. }
  517. }
  518. // Ensure that node allocatable configuration is valid.
  519. if err := cm.validateNodeAllocatable(); err != nil {
  520. return err
  521. }
  522. // Setup the node
  523. if err := cm.setupNode(activePods); err != nil {
  524. return err
  525. }
  526. // Don't run a background thread if there are no ensureStateFuncs.
  527. hasEnsureStateFuncs := false
  528. for _, cont := range cm.systemContainers {
  529. if cont.ensureStateFunc != nil {
  530. hasEnsureStateFuncs = true
  531. break
  532. }
  533. }
  534. if hasEnsureStateFuncs {
  535. // Run ensure state functions every minute.
  536. go wait.Until(func() {
  537. for _, cont := range cm.systemContainers {
  538. if cont.ensureStateFunc != nil {
  539. if err := cont.ensureStateFunc(cont.manager); err != nil {
  540. klog.Warningf("[ContainerManager] Failed to ensure state of %q: %v", cont.name, err)
  541. }
  542. }
  543. }
  544. }, time.Minute, wait.NeverStop)
  545. }
  546. if len(cm.periodicTasks) > 0 {
  547. go wait.Until(func() {
  548. for _, task := range cm.periodicTasks {
  549. if task != nil {
  550. task()
  551. }
  552. }
  553. }, 5*time.Minute, wait.NeverStop)
  554. }
  555. // Starts device manager.
  556. if err := cm.deviceManager.Start(devicemanager.ActivePodsFunc(activePods), sourcesReady); err != nil {
  557. return err
  558. }
  559. return nil
  560. }
  561. func (cm *containerManagerImpl) GetPluginRegistrationHandler() cache.PluginHandler {
  562. return cm.deviceManager.GetWatcherHandler()
  563. }
  564. // TODO: move the GetResources logic to PodContainerManager.
  565. func (cm *containerManagerImpl) GetResources(pod *v1.Pod, container *v1.Container) (*kubecontainer.RunContainerOptions, error) {
  566. opts := &kubecontainer.RunContainerOptions{}
  567. // Allocate should already be called during predicateAdmitHandler.Admit(),
  568. // just try to fetch device runtime information from cached state here
  569. devOpts, err := cm.deviceManager.GetDeviceRunContainerOptions(pod, container)
  570. if err != nil {
  571. return nil, err
  572. } else if devOpts == nil {
  573. return opts, nil
  574. }
  575. opts.Devices = append(opts.Devices, devOpts.Devices...)
  576. opts.Mounts = append(opts.Mounts, devOpts.Mounts...)
  577. opts.Envs = append(opts.Envs, devOpts.Envs...)
  578. opts.Annotations = append(opts.Annotations, devOpts.Annotations...)
  579. return opts, nil
  580. }
  581. func (cm *containerManagerImpl) UpdatePluginResources(node *schedulernodeinfo.NodeInfo, attrs *lifecycle.PodAdmitAttributes) error {
  582. return cm.deviceManager.Allocate(node, attrs)
  583. }
  584. func (cm *containerManagerImpl) SystemCgroupsLimit() v1.ResourceList {
  585. cpuLimit := int64(0)
  586. // Sum up resources of all external containers.
  587. for _, cont := range cm.systemContainers {
  588. cpuLimit += cont.cpuMillicores
  589. }
  590. return v1.ResourceList{
  591. v1.ResourceCPU: *resource.NewMilliQuantity(
  592. cpuLimit,
  593. resource.DecimalSI),
  594. }
  595. }
  596. func isProcessRunningInHost(pid int) (bool, error) {
  597. // Get init pid namespace.
  598. initPidNs, err := os.Readlink("/proc/1/ns/pid")
  599. if err != nil {
  600. return false, fmt.Errorf("failed to find pid namespace of init process")
  601. }
  602. klog.V(10).Infof("init pid ns is %q", initPidNs)
  603. processPidNs, err := os.Readlink(fmt.Sprintf("/proc/%d/ns/pid", pid))
  604. if err != nil {
  605. return false, fmt.Errorf("failed to find pid namespace of process %q", pid)
  606. }
  607. klog.V(10).Infof("Pid %d pid ns is %q", pid, processPidNs)
  608. return initPidNs == processPidNs, nil
  609. }
  610. func getPidFromPidFile(pidFile string) (int, error) {
  611. file, err := os.Open(pidFile)
  612. if err != nil {
  613. return 0, fmt.Errorf("error opening pid file %s: %v", pidFile, err)
  614. }
  615. defer file.Close()
  616. data, err := ioutil.ReadAll(file)
  617. if err != nil {
  618. return 0, fmt.Errorf("error reading pid file %s: %v", pidFile, err)
  619. }
  620. pid, err := strconv.Atoi(string(data))
  621. if err != nil {
  622. return 0, fmt.Errorf("error parsing %s as a number: %v", string(data), err)
  623. }
  624. return pid, nil
  625. }
  626. func getPidsForProcess(name, pidFile string) ([]int, error) {
  627. if len(pidFile) == 0 {
  628. return procfs.PidOf(name)
  629. }
  630. pid, err := getPidFromPidFile(pidFile)
  631. if err == nil {
  632. return []int{pid}, nil
  633. }
  634. // Try to lookup pid by process name
  635. pids, err2 := procfs.PidOf(name)
  636. if err2 == nil {
  637. return pids, nil
  638. }
  639. // Return error from getPidFromPidFile since that should have worked
  640. // and is the real source of the problem.
  641. klog.V(4).Infof("unable to get pid from %s: %v", pidFile, err)
  642. return []int{}, err
  643. }
  644. // Ensures that the Docker daemon is in the desired container.
  645. // Temporarily export the function to be used by dockershim.
  646. // TODO(yujuhong): Move this function to dockershim once kubelet migrates to
  647. // dockershim as the default.
  648. func EnsureDockerInContainer(dockerAPIVersion *utilversion.Version, oomScoreAdj int, manager *fs.Manager) error {
  649. type process struct{ name, file string }
  650. dockerProcs := []process{{dockerProcessName, dockerPidFile}}
  651. if dockerAPIVersion.AtLeast(containerdAPIVersion) {
  652. dockerProcs = append(dockerProcs, process{containerdProcessName, containerdPidFile})
  653. }
  654. var errs []error
  655. for _, proc := range dockerProcs {
  656. pids, err := getPidsForProcess(proc.name, proc.file)
  657. if err != nil {
  658. errs = append(errs, fmt.Errorf("failed to get pids for %q: %v", proc.name, err))
  659. continue
  660. }
  661. // Move if the pid is not already in the desired container.
  662. for _, pid := range pids {
  663. if err := ensureProcessInContainerWithOOMScore(pid, oomScoreAdj, manager); err != nil {
  664. errs = append(errs, fmt.Errorf("errors moving %q pid: %v", proc.name, err))
  665. }
  666. }
  667. }
  668. return utilerrors.NewAggregate(errs)
  669. }
  670. func ensureProcessInContainerWithOOMScore(pid int, oomScoreAdj int, manager *fs.Manager) error {
  671. if runningInHost, err := isProcessRunningInHost(pid); err != nil {
  672. // Err on the side of caution. Avoid moving the docker daemon unless we are able to identify its context.
  673. return err
  674. } else if !runningInHost {
  675. // Process is running inside a container. Don't touch that.
  676. klog.V(2).Infof("pid %d is not running in the host namespaces", pid)
  677. return nil
  678. }
  679. var errs []error
  680. if manager != nil {
  681. cont, err := getContainer(pid)
  682. if err != nil {
  683. errs = append(errs, fmt.Errorf("failed to find container of PID %d: %v", pid, err))
  684. }
  685. if cont != manager.Cgroups.Name {
  686. err = manager.Apply(pid)
  687. if err != nil {
  688. errs = append(errs, fmt.Errorf("failed to move PID %d (in %q) to %q: %v", pid, cont, manager.Cgroups.Name, err))
  689. }
  690. }
  691. }
  692. // Also apply oom-score-adj to processes
  693. oomAdjuster := oom.NewOOMAdjuster()
  694. klog.V(5).Infof("attempting to apply oom_score_adj of %d to pid %d", oomScoreAdj, pid)
  695. if err := oomAdjuster.ApplyOOMScoreAdj(pid, oomScoreAdj); err != nil {
  696. klog.V(3).Infof("Failed to apply oom_score_adj %d for pid %d: %v", oomScoreAdj, pid, err)
  697. errs = append(errs, fmt.Errorf("failed to apply oom score %d to PID %d: %v", oomScoreAdj, pid, err))
  698. }
  699. return utilerrors.NewAggregate(errs)
  700. }
  701. // getContainer returns the cgroup associated with the specified pid.
  702. // It enforces a unified hierarchy for memory and cpu cgroups.
  703. // On systemd environments, it uses the name=systemd cgroup for the specified pid.
  704. func getContainer(pid int) (string, error) {
  705. cgs, err := cgroups.ParseCgroupFile(fmt.Sprintf("/proc/%d/cgroup", pid))
  706. if err != nil {
  707. return "", err
  708. }
  709. cpu, found := cgs["cpu"]
  710. if !found {
  711. return "", cgroups.NewNotFoundError("cpu")
  712. }
  713. memory, found := cgs["memory"]
  714. if !found {
  715. return "", cgroups.NewNotFoundError("memory")
  716. }
  717. // since we use this container for accounting, we need to ensure its a unified hierarchy.
  718. if cpu != memory {
  719. return "", fmt.Errorf("cpu and memory cgroup hierarchy not unified. cpu: %s, memory: %s", cpu, memory)
  720. }
  721. // on systemd, every pid is in a unified cgroup hierarchy (name=systemd as seen in systemd-cgls)
  722. // cpu and memory accounting is off by default, users may choose to enable it per unit or globally.
  723. // users could enable CPU and memory accounting globally via /etc/systemd/system.conf (DefaultCPUAccounting=true DefaultMemoryAccounting=true).
  724. // users could also enable CPU and memory accounting per unit via CPUAccounting=true and MemoryAccounting=true
  725. // we only warn if accounting is not enabled for CPU or memory so as to not break local development flows where kubelet is launched in a terminal.
  726. // for example, the cgroup for the user session will be something like /user.slice/user-X.slice/session-X.scope, but the cpu and memory
  727. // cgroup will be the closest ancestor where accounting is performed (most likely /) on systems that launch docker containers.
  728. // as a result, on those systems, you will not get cpu or memory accounting statistics for kubelet.
  729. // in addition, you would not get memory or cpu accounting for the runtime unless accounting was enabled on its unit (or globally).
  730. if systemd, found := cgs["name=systemd"]; found {
  731. if systemd != cpu {
  732. klog.Warningf("CPUAccounting not enabled for pid: %d", pid)
  733. }
  734. if systemd != memory {
  735. klog.Warningf("MemoryAccounting not enabled for pid: %d", pid)
  736. }
  737. return systemd, nil
  738. }
  739. return cpu, nil
  740. }
  741. // Ensures the system container is created and all non-kernel threads and process 1
  742. // without a container are moved to it.
  743. //
  744. // The reason of leaving kernel threads at root cgroup is that we don't want to tie the
  745. // execution of these threads with to-be defined /system quota and create priority inversions.
  746. //
  747. func ensureSystemCgroups(rootCgroupPath string, manager *fs.Manager) error {
  748. // Move non-kernel PIDs to the system container.
  749. attemptsRemaining := 10
  750. var errs []error
  751. for attemptsRemaining >= 0 {
  752. // Only keep errors on latest attempt.
  753. errs = []error{}
  754. attemptsRemaining--
  755. allPids, err := cmutil.GetPids(rootCgroupPath)
  756. if err != nil {
  757. errs = append(errs, fmt.Errorf("failed to list PIDs for root: %v", err))
  758. continue
  759. }
  760. // Remove kernel pids and other protected PIDs (pid 1, PIDs already in system & kubelet containers)
  761. pids := make([]int, 0, len(allPids))
  762. for _, pid := range allPids {
  763. if pid == 1 || isKernelPid(pid) {
  764. continue
  765. }
  766. pids = append(pids, pid)
  767. }
  768. klog.Infof("Found %d PIDs in root, %d of them are not to be moved", len(allPids), len(allPids)-len(pids))
  769. // Check if we have moved all the non-kernel PIDs.
  770. if len(pids) == 0 {
  771. break
  772. }
  773. klog.Infof("Moving non-kernel processes: %v", pids)
  774. for _, pid := range pids {
  775. err := manager.Apply(pid)
  776. if err != nil {
  777. errs = append(errs, fmt.Errorf("failed to move PID %d into the system container %q: %v", pid, manager.Cgroups.Name, err))
  778. }
  779. }
  780. }
  781. if attemptsRemaining < 0 {
  782. errs = append(errs, fmt.Errorf("ran out of attempts to create system containers %q", manager.Cgroups.Name))
  783. }
  784. return utilerrors.NewAggregate(errs)
  785. }
  786. // Determines whether the specified PID is a kernel PID.
  787. func isKernelPid(pid int) bool {
  788. // Kernel threads have no associated executable.
  789. _, err := os.Readlink(fmt.Sprintf("/proc/%d/exe", pid))
  790. return err != nil
  791. }
  792. func (cm *containerManagerImpl) GetCapacity() v1.ResourceList {
  793. return cm.capacity
  794. }
  795. func (cm *containerManagerImpl) GetDevicePluginResourceCapacity() (v1.ResourceList, v1.ResourceList, []string) {
  796. return cm.deviceManager.GetCapacity()
  797. }
  798. func (cm *containerManagerImpl) GetDevices(podUID, containerName string) []*podresourcesapi.ContainerDevices {
  799. return cm.deviceManager.GetDevices(podUID, containerName)
  800. }
  801. func (cm *containerManagerImpl) ShouldResetExtendedResourceCapacity() bool {
  802. return cm.deviceManager.ShouldResetExtendedResourceCapacity()
  803. }