daemon_unix.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "runtime/debug"
  11. "strconv"
  12. "strings"
  13. "syscall"
  14. "time"
  15. "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/container"
  17. "github.com/docker/docker/image"
  18. "github.com/docker/docker/layer"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/parsers"
  21. "github.com/docker/docker/pkg/parsers/kernel"
  22. "github.com/docker/docker/pkg/sysinfo"
  23. "github.com/docker/docker/reference"
  24. "github.com/docker/docker/runconfig"
  25. runconfigopts "github.com/docker/docker/runconfig/opts"
  26. "github.com/docker/engine-api/types"
  27. "github.com/docker/engine-api/types/blkiodev"
  28. pblkiodev "github.com/docker/engine-api/types/blkiodev"
  29. containertypes "github.com/docker/engine-api/types/container"
  30. "github.com/docker/libnetwork"
  31. nwconfig "github.com/docker/libnetwork/config"
  32. "github.com/docker/libnetwork/drivers/bridge"
  33. "github.com/docker/libnetwork/netlabel"
  34. "github.com/docker/libnetwork/netutils"
  35. "github.com/docker/libnetwork/options"
  36. lntypes "github.com/docker/libnetwork/types"
  37. "github.com/opencontainers/runc/libcontainer/label"
  38. "github.com/opencontainers/runc/libcontainer/user"
  39. "github.com/opencontainers/specs/specs-go"
  40. )
  41. const (
  42. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  43. linuxMinCPUShares = 2
  44. linuxMaxCPUShares = 262144
  45. platformSupported = true
  46. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  47. linuxMinMemory = 4194304
  48. // constants for remapped root settings
  49. defaultIDSpecifier string = "default"
  50. defaultRemappedID string = "dockremap"
  51. // constant for cgroup drivers
  52. cgroupFsDriver = "cgroupfs"
  53. cgroupSystemdDriver = "systemd"
  54. )
  55. func getMemoryResources(config containertypes.Resources) *specs.Memory {
  56. memory := specs.Memory{}
  57. if config.Memory > 0 {
  58. limit := uint64(config.Memory)
  59. memory.Limit = &limit
  60. }
  61. if config.MemoryReservation > 0 {
  62. reservation := uint64(config.MemoryReservation)
  63. memory.Reservation = &reservation
  64. }
  65. if config.MemorySwap != 0 {
  66. swap := uint64(config.MemorySwap)
  67. memory.Swap = &swap
  68. }
  69. if config.MemorySwappiness != nil {
  70. swappiness := uint64(*config.MemorySwappiness)
  71. memory.Swappiness = &swappiness
  72. }
  73. if config.KernelMemory != 0 {
  74. kernelMemory := uint64(config.KernelMemory)
  75. memory.Kernel = &kernelMemory
  76. }
  77. return &memory
  78. }
  79. func getCPUResources(config containertypes.Resources) *specs.CPU {
  80. cpu := specs.CPU{}
  81. if config.CPUShares != 0 {
  82. shares := uint64(config.CPUShares)
  83. cpu.Shares = &shares
  84. }
  85. if config.CpusetCpus != "" {
  86. cpuset := config.CpusetCpus
  87. cpu.Cpus = &cpuset
  88. }
  89. if config.CpusetMems != "" {
  90. cpuset := config.CpusetMems
  91. cpu.Mems = &cpuset
  92. }
  93. if config.CPUPeriod != 0 {
  94. period := uint64(config.CPUPeriod)
  95. cpu.Period = &period
  96. }
  97. if config.CPUQuota != 0 {
  98. quota := uint64(config.CPUQuota)
  99. cpu.Quota = &quota
  100. }
  101. return &cpu
  102. }
  103. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.WeightDevice, error) {
  104. var stat syscall.Stat_t
  105. var blkioWeightDevices []specs.WeightDevice
  106. for _, weightDevice := range config.BlkioWeightDevice {
  107. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  108. return nil, err
  109. }
  110. weight := weightDevice.Weight
  111. d := specs.WeightDevice{Weight: &weight}
  112. d.Major = int64(stat.Rdev / 256)
  113. d.Minor = int64(stat.Rdev % 256)
  114. blkioWeightDevices = append(blkioWeightDevices, d)
  115. }
  116. return blkioWeightDevices, nil
  117. }
  118. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  119. var (
  120. labelOpts []string
  121. err error
  122. )
  123. for _, opt := range config.SecurityOpt {
  124. if opt == "no-new-privileges" {
  125. container.NoNewPrivileges = true
  126. } else {
  127. var con []string
  128. if strings.Contains(opt, "=") {
  129. con = strings.SplitN(opt, "=", 2)
  130. } else if strings.Contains(opt, ":") {
  131. con = strings.SplitN(opt, ":", 2)
  132. logrus.Warnf("Security options with `:` as a separator are deprecated and will be completely unsupported in 1.13, use `=` instead.")
  133. }
  134. if len(con) != 2 {
  135. return fmt.Errorf("Invalid --security-opt 1: %q", opt)
  136. }
  137. switch con[0] {
  138. case "label":
  139. labelOpts = append(labelOpts, con[1])
  140. case "apparmor":
  141. container.AppArmorProfile = con[1]
  142. case "seccomp":
  143. container.SeccompProfile = con[1]
  144. default:
  145. return fmt.Errorf("Invalid --security-opt 2: %q", opt)
  146. }
  147. }
  148. }
  149. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  150. return err
  151. }
  152. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.ThrottleDevice, error) {
  153. var throttleDevices []specs.ThrottleDevice
  154. var stat syscall.Stat_t
  155. for _, d := range devs {
  156. if err := syscall.Stat(d.Path, &stat); err != nil {
  157. return nil, err
  158. }
  159. rate := d.Rate
  160. d := specs.ThrottleDevice{Rate: &rate}
  161. d.Major = int64(stat.Rdev / 256)
  162. d.Minor = int64(stat.Rdev % 256)
  163. throttleDevices = append(throttleDevices, d)
  164. }
  165. return throttleDevices, nil
  166. }
  167. func checkKernelVersion(k, major, minor int) bool {
  168. if v, err := kernel.GetKernelVersion(); err != nil {
  169. logrus.Warnf("%s", err)
  170. } else {
  171. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  172. return false
  173. }
  174. }
  175. return true
  176. }
  177. func checkKernel() error {
  178. // Check for unsupported kernel versions
  179. // FIXME: it would be cleaner to not test for specific versions, but rather
  180. // test for specific functionalities.
  181. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  182. // without actually causing a kernel panic, so we need this workaround until
  183. // the circumstances of pre-3.10 crashes are clearer.
  184. // For details see https://github.com/docker/docker/issues/407
  185. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  186. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  187. if !checkKernelVersion(3, 10, 0) {
  188. v, _ := kernel.GetKernelVersion()
  189. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  190. logrus.Fatalf("Your Linux kernel version %s is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.", v.String())
  191. }
  192. }
  193. return nil
  194. }
  195. // adaptContainerSettings is called during container creation to modify any
  196. // settings necessary in the HostConfig structure.
  197. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  198. if adjustCPUShares && hostConfig.CPUShares > 0 {
  199. // Handle unsupported CPUShares
  200. if hostConfig.CPUShares < linuxMinCPUShares {
  201. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  202. hostConfig.CPUShares = linuxMinCPUShares
  203. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  204. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  205. hostConfig.CPUShares = linuxMaxCPUShares
  206. }
  207. }
  208. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  209. // By default, MemorySwap is set to twice the size of Memory.
  210. hostConfig.MemorySwap = hostConfig.Memory * 2
  211. }
  212. if hostConfig.ShmSize == 0 {
  213. hostConfig.ShmSize = container.DefaultSHMSize
  214. }
  215. var err error
  216. if hostConfig.SecurityOpt == nil {
  217. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode, hostConfig.Privileged)
  218. if err != nil {
  219. return err
  220. }
  221. }
  222. if hostConfig.MemorySwappiness == nil {
  223. defaultSwappiness := int64(-1)
  224. hostConfig.MemorySwappiness = &defaultSwappiness
  225. }
  226. if hostConfig.OomKillDisable == nil {
  227. defaultOomKillDisable := false
  228. hostConfig.OomKillDisable = &defaultOomKillDisable
  229. }
  230. return nil
  231. }
  232. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  233. warnings := []string{}
  234. // memory subsystem checks and adjustments
  235. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  236. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  237. }
  238. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  239. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  240. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  241. resources.Memory = 0
  242. resources.MemorySwap = -1
  243. }
  244. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  245. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  246. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  247. resources.MemorySwap = -1
  248. }
  249. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  250. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  251. }
  252. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  253. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  254. }
  255. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  256. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  257. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  258. resources.MemorySwappiness = nil
  259. }
  260. if resources.MemorySwappiness != nil {
  261. swappiness := *resources.MemorySwappiness
  262. if swappiness < -1 || swappiness > 100 {
  263. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  264. }
  265. }
  266. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  267. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  268. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  269. resources.MemoryReservation = 0
  270. }
  271. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  272. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  273. }
  274. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  275. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage")
  276. }
  277. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  278. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  279. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  280. resources.KernelMemory = 0
  281. }
  282. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  283. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  284. }
  285. if resources.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  286. warnings = append(warnings, "You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  287. logrus.Warnf("You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  288. }
  289. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  290. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  291. // warning the caller if they already wanted the feature to be off
  292. if *resources.OomKillDisable {
  293. warnings = append(warnings, "Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  294. logrus.Warnf("Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  295. }
  296. resources.OomKillDisable = nil
  297. }
  298. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  299. warnings = append(warnings, "Your kernel does not support pids limit capabilities, pids limit discarded.")
  300. logrus.Warnf("Your kernel does not support pids limit capabilities, pids limit discarded.")
  301. resources.PidsLimit = 0
  302. }
  303. // cpu subsystem checks and adjustments
  304. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  305. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  306. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  307. resources.CPUShares = 0
  308. }
  309. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  310. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  311. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  312. resources.CPUPeriod = 0
  313. }
  314. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  315. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  316. }
  317. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  318. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  319. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  320. resources.CPUQuota = 0
  321. }
  322. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  323. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  324. }
  325. if resources.CPUPercent > 0 {
  326. warnings = append(warnings, "%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  327. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  328. resources.CPUPercent = 0
  329. }
  330. // cpuset subsystem checks and adjustments
  331. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  332. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  333. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  334. resources.CpusetCpus = ""
  335. resources.CpusetMems = ""
  336. }
  337. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  338. if err != nil {
  339. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  340. }
  341. if !cpusAvailable {
  342. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  343. }
  344. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  345. if err != nil {
  346. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  347. }
  348. if !memsAvailable {
  349. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  350. }
  351. // blkio subsystem checks and adjustments
  352. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  353. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  354. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  355. resources.BlkioWeight = 0
  356. }
  357. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  358. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  359. }
  360. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  361. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  362. }
  363. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  364. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  365. logrus.Warnf("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  366. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  367. }
  368. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  369. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  370. logrus.Warnf("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  371. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  372. }
  373. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  374. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  375. logrus.Warnf("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  376. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  377. }
  378. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  379. warnings = append(warnings, "Your kernel does not support Block read limit in IO per second.")
  380. logrus.Warnf("Your kernel does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
  381. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  382. }
  383. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  384. warnings = append(warnings, "Your kernel does not support Block write limit in IO per second.")
  385. logrus.Warnf("Your kernel does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
  386. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  387. }
  388. return warnings, nil
  389. }
  390. func (daemon *Daemon) getCgroupDriver() string {
  391. cgroupDriver := cgroupFsDriver
  392. if UsingSystemd(daemon.configStore) {
  393. cgroupDriver = cgroupSystemdDriver
  394. }
  395. return cgroupDriver
  396. }
  397. // getCD gets the raw value of the native.cgroupdriver option, if set.
  398. func getCD(config *Config) string {
  399. for _, option := range config.ExecOptions {
  400. key, val, err := parsers.ParseKeyValueOpt(option)
  401. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  402. continue
  403. }
  404. return val
  405. }
  406. return ""
  407. }
  408. // VerifyCgroupDriver validates native.cgroupdriver
  409. func VerifyCgroupDriver(config *Config) error {
  410. cd := getCD(config)
  411. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  412. return nil
  413. }
  414. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  415. }
  416. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  417. func UsingSystemd(config *Config) bool {
  418. return getCD(config) == cgroupSystemdDriver
  419. }
  420. // verifyPlatformContainerSettings performs platform-specific validation of the
  421. // hostconfig and config structures.
  422. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  423. warnings := []string{}
  424. sysInfo := sysinfo.New(true)
  425. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  426. if err != nil {
  427. return warnings, err
  428. }
  429. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  430. if err != nil {
  431. return warnings, err
  432. }
  433. warnings = append(warnings, w...)
  434. if hostConfig.ShmSize < 0 {
  435. return warnings, fmt.Errorf("SHM size must be greater than 0")
  436. }
  437. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  438. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  439. }
  440. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  441. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  442. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  443. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  444. }
  445. // check for various conflicting options with user namespaces
  446. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  447. if hostConfig.Privileged {
  448. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
  449. }
  450. if hostConfig.NetworkMode.IsHost() {
  451. return warnings, fmt.Errorf("Cannot share the host's network namespace when user namespaces are enabled")
  452. }
  453. if hostConfig.PidMode.IsHost() {
  454. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
  455. }
  456. if hostConfig.ReadonlyRootfs {
  457. return warnings, fmt.Errorf("Cannot use the --read-only option when user namespaces are enabled")
  458. }
  459. }
  460. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  461. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  462. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  463. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  464. }
  465. }
  466. return warnings, nil
  467. }
  468. // verifyDaemonSettings performs validation of daemon config struct
  469. func verifyDaemonSettings(config *Config) error {
  470. // Check for mutually incompatible config options
  471. if config.bridgeConfig.Iface != "" && config.bridgeConfig.IP != "" {
  472. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  473. }
  474. if !config.bridgeConfig.EnableIPTables && !config.bridgeConfig.InterContainerCommunication {
  475. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  476. }
  477. if !config.bridgeConfig.EnableIPTables && config.bridgeConfig.EnableIPMasq {
  478. config.bridgeConfig.EnableIPMasq = false
  479. }
  480. if err := VerifyCgroupDriver(config); err != nil {
  481. return err
  482. }
  483. if config.CgroupParent != "" && UsingSystemd(config) {
  484. if len(config.CgroupParent) <= 6 || !strings.HasSuffix(config.CgroupParent, ".slice") {
  485. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  486. }
  487. }
  488. return nil
  489. }
  490. // checkSystem validates platform-specific requirements
  491. func checkSystem() error {
  492. if os.Geteuid() != 0 {
  493. return fmt.Errorf("The Docker daemon needs to be run as root")
  494. }
  495. return checkKernel()
  496. }
  497. // configureMaxThreads sets the Go runtime max threads threshold
  498. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  499. func configureMaxThreads(config *Config) error {
  500. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  501. if err != nil {
  502. return err
  503. }
  504. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  505. if err != nil {
  506. return err
  507. }
  508. maxThreads := (mtint / 100) * 90
  509. debug.SetMaxThreads(maxThreads)
  510. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  511. return nil
  512. }
  513. // configureKernelSecuritySupport configures and validates security support for the kernel
  514. func configureKernelSecuritySupport(config *Config, driverName string) error {
  515. if config.EnableSelinuxSupport {
  516. if selinuxEnabled() {
  517. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  518. if driverName == "overlay" {
  519. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  520. }
  521. logrus.Debug("SELinux enabled successfully")
  522. } else {
  523. logrus.Warn("Docker could not enable SELinux on the host system")
  524. }
  525. } else {
  526. selinuxSetDisabled()
  527. }
  528. return nil
  529. }
  530. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  531. netOptions, err := daemon.networkOptions(config)
  532. if err != nil {
  533. return nil, err
  534. }
  535. controller, err := libnetwork.New(netOptions...)
  536. if err != nil {
  537. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  538. }
  539. // Initialize default network on "null"
  540. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(false)); err != nil {
  541. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  542. }
  543. // Initialize default network on "host"
  544. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(false)); err != nil {
  545. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  546. }
  547. if !config.DisableBridge {
  548. // Initialize default driver "bridge"
  549. if err := initBridgeDriver(controller, config); err != nil {
  550. return nil, err
  551. }
  552. }
  553. return controller, nil
  554. }
  555. func driverOptions(config *Config) []nwconfig.Option {
  556. bridgeConfig := options.Generic{
  557. "EnableIPForwarding": config.bridgeConfig.EnableIPForward,
  558. "EnableIPTables": config.bridgeConfig.EnableIPTables,
  559. "EnableUserlandProxy": config.bridgeConfig.EnableUserlandProxy}
  560. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  561. dOptions := []nwconfig.Option{}
  562. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  563. return dOptions
  564. }
  565. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  566. if n, err := controller.NetworkByName("bridge"); err == nil {
  567. if err = n.Delete(); err != nil {
  568. return fmt.Errorf("could not delete the default bridge network: %v", err)
  569. }
  570. }
  571. bridgeName := bridge.DefaultBridgeName
  572. if config.bridgeConfig.Iface != "" {
  573. bridgeName = config.bridgeConfig.Iface
  574. }
  575. netOption := map[string]string{
  576. bridge.BridgeName: bridgeName,
  577. bridge.DefaultBridge: strconv.FormatBool(true),
  578. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  579. bridge.EnableIPMasquerade: strconv.FormatBool(config.bridgeConfig.EnableIPMasq),
  580. bridge.EnableICC: strconv.FormatBool(config.bridgeConfig.InterContainerCommunication),
  581. }
  582. // --ip processing
  583. if config.bridgeConfig.DefaultIP != nil {
  584. netOption[bridge.DefaultBindingIP] = config.bridgeConfig.DefaultIP.String()
  585. }
  586. var (
  587. ipamV4Conf *libnetwork.IpamConf
  588. ipamV6Conf *libnetwork.IpamConf
  589. )
  590. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  591. nw, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  592. if err == nil {
  593. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  594. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  595. if hip.IsGlobalUnicast() {
  596. ipamV4Conf.Gateway = nw.IP.String()
  597. }
  598. }
  599. if config.bridgeConfig.IP != "" {
  600. ipamV4Conf.PreferredPool = config.bridgeConfig.IP
  601. ip, _, err := net.ParseCIDR(config.bridgeConfig.IP)
  602. if err != nil {
  603. return err
  604. }
  605. ipamV4Conf.Gateway = ip.String()
  606. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  607. logrus.Infof("Default bridge (%s) is assigned with an IP address %s. Daemon option --bip can be used to set a preferred IP address", bridgeName, ipamV4Conf.PreferredPool)
  608. }
  609. if config.bridgeConfig.FixedCIDR != "" {
  610. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  611. if err != nil {
  612. return err
  613. }
  614. ipamV4Conf.SubPool = fCIDR.String()
  615. }
  616. if config.bridgeConfig.DefaultGatewayIPv4 != nil {
  617. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.bridgeConfig.DefaultGatewayIPv4.String()
  618. }
  619. var deferIPv6Alloc bool
  620. if config.bridgeConfig.FixedCIDRv6 != "" {
  621. _, fCIDRv6, err := net.ParseCIDR(config.bridgeConfig.FixedCIDRv6)
  622. if err != nil {
  623. return err
  624. }
  625. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  626. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  627. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  628. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  629. // on this network until after the driver has created the endpoint and returned the
  630. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  631. ones, _ := fCIDRv6.Mask.Size()
  632. deferIPv6Alloc = ones <= 80
  633. if ipamV6Conf == nil {
  634. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  635. }
  636. ipamV6Conf.PreferredPool = fCIDRv6.String()
  637. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  638. // address belongs to the same network, we need to inform libnetwork about it, so
  639. // that it can be reserved with IPAM and it will not be given away to somebody else
  640. for _, nw6 := range nw6List {
  641. if fCIDRv6.Contains(nw6.IP) {
  642. ipamV6Conf.Gateway = nw6.IP.String()
  643. break
  644. }
  645. }
  646. }
  647. if config.bridgeConfig.DefaultGatewayIPv6 != nil {
  648. if ipamV6Conf == nil {
  649. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  650. }
  651. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.bridgeConfig.DefaultGatewayIPv6.String()
  652. }
  653. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  654. v6Conf := []*libnetwork.IpamConf{}
  655. if ipamV6Conf != nil {
  656. v6Conf = append(v6Conf, ipamV6Conf)
  657. }
  658. // Initialize default network on "bridge" with the same name
  659. _, err = controller.NewNetwork("bridge", "bridge", "",
  660. libnetwork.NetworkOptionEnableIPv6(config.bridgeConfig.EnableIPv6),
  661. libnetwork.NetworkOptionDriverOpts(netOption),
  662. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  663. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  664. if err != nil {
  665. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  666. }
  667. return nil
  668. }
  669. // setupInitLayer populates a directory with mountpoints suitable
  670. // for bind-mounting things into the container.
  671. //
  672. // This extra layer is used by all containers as the top-most ro layer. It protects
  673. // the container from unwanted side-effects on the rw layer.
  674. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  675. for pth, typ := range map[string]string{
  676. "/dev/pts": "dir",
  677. "/dev/shm": "dir",
  678. "/proc": "dir",
  679. "/sys": "dir",
  680. "/.dockerenv": "file",
  681. "/etc/resolv.conf": "file",
  682. "/etc/hosts": "file",
  683. "/etc/hostname": "file",
  684. "/dev/console": "file",
  685. "/etc/mtab": "/proc/mounts",
  686. } {
  687. parts := strings.Split(pth, "/")
  688. prev := "/"
  689. for _, p := range parts[1:] {
  690. prev = filepath.Join(prev, p)
  691. syscall.Unlink(filepath.Join(initLayer, prev))
  692. }
  693. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  694. if os.IsNotExist(err) {
  695. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  696. return err
  697. }
  698. switch typ {
  699. case "dir":
  700. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  701. return err
  702. }
  703. case "file":
  704. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  705. if err != nil {
  706. return err
  707. }
  708. f.Chown(rootUID, rootGID)
  709. f.Close()
  710. default:
  711. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  712. return err
  713. }
  714. }
  715. } else {
  716. return err
  717. }
  718. }
  719. }
  720. // Layer is ready to use, if it wasn't before.
  721. return nil
  722. }
  723. // Parse the remapped root (user namespace) option, which can be one of:
  724. // username - valid username from /etc/passwd
  725. // username:groupname - valid username; valid groupname from /etc/group
  726. // uid - 32-bit unsigned int valid Linux UID value
  727. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  728. //
  729. // If no groupname is specified, and a username is specified, an attempt
  730. // will be made to lookup a gid for that username as a groupname
  731. //
  732. // If names are used, they are verified to exist in passwd/group
  733. func parseRemappedRoot(usergrp string) (string, string, error) {
  734. var (
  735. userID, groupID int
  736. username, groupname string
  737. )
  738. idparts := strings.Split(usergrp, ":")
  739. if len(idparts) > 2 {
  740. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  741. }
  742. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  743. // must be a uid; take it as valid
  744. userID = int(uid)
  745. luser, err := user.LookupUid(userID)
  746. if err != nil {
  747. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  748. }
  749. username = luser.Name
  750. if len(idparts) == 1 {
  751. // if the uid was numeric and no gid was specified, take the uid as the gid
  752. groupID = userID
  753. lgrp, err := user.LookupGid(groupID)
  754. if err != nil {
  755. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  756. }
  757. groupname = lgrp.Name
  758. }
  759. } else {
  760. lookupName := idparts[0]
  761. // special case: if the user specified "default", they want Docker to create or
  762. // use (after creation) the "dockremap" user/group for root remapping
  763. if lookupName == defaultIDSpecifier {
  764. lookupName = defaultRemappedID
  765. }
  766. luser, err := user.LookupUser(lookupName)
  767. if err != nil && idparts[0] != defaultIDSpecifier {
  768. // error if the name requested isn't the special "dockremap" ID
  769. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  770. } else if err != nil {
  771. // special case-- if the username == "default", then we have been asked
  772. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  773. // ranges will be used for the user and group mappings in user namespaced containers
  774. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  775. if err == nil {
  776. return defaultRemappedID, defaultRemappedID, nil
  777. }
  778. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  779. }
  780. username = luser.Name
  781. if len(idparts) == 1 {
  782. // we only have a string username, and no group specified; look up gid from username as group
  783. group, err := user.LookupGroup(lookupName)
  784. if err != nil {
  785. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  786. }
  787. groupID = group.Gid
  788. groupname = group.Name
  789. }
  790. }
  791. if len(idparts) == 2 {
  792. // groupname or gid is separately specified and must be resolved
  793. // to an unsigned 32-bit gid
  794. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  795. // must be a gid, take it as valid
  796. groupID = int(gid)
  797. lgrp, err := user.LookupGid(groupID)
  798. if err != nil {
  799. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  800. }
  801. groupname = lgrp.Name
  802. } else {
  803. // not a number; attempt a lookup
  804. if _, err := user.LookupGroup(idparts[1]); err != nil {
  805. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  806. }
  807. groupname = idparts[1]
  808. }
  809. }
  810. return username, groupname, nil
  811. }
  812. func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) {
  813. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  814. return nil, nil, fmt.Errorf("User namespaces are only supported on Linux")
  815. }
  816. // if the daemon was started with remapped root option, parse
  817. // the config option to the int uid,gid values
  818. var (
  819. uidMaps, gidMaps []idtools.IDMap
  820. )
  821. if config.RemappedRoot != "" {
  822. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  823. if err != nil {
  824. return nil, nil, err
  825. }
  826. if username == "root" {
  827. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  828. // effectively
  829. logrus.Warnf("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  830. return uidMaps, gidMaps, nil
  831. }
  832. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  833. // update remapped root setting now that we have resolved them to actual names
  834. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  835. uidMaps, gidMaps, err = idtools.CreateIDMappings(username, groupname)
  836. if err != nil {
  837. return nil, nil, fmt.Errorf("Can't create ID mappings: %v", err)
  838. }
  839. }
  840. return uidMaps, gidMaps, nil
  841. }
  842. func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
  843. config.Root = rootDir
  844. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  845. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  846. // (e.g. mounted layers of a container) can traverse this path.
  847. // The user namespace support will create subdirectories for the remapped root host uid:gid
  848. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  849. // layer content subtrees.
  850. if _, err := os.Stat(rootDir); err == nil {
  851. // root current exists; verify the access bits are correct by setting them
  852. if err = os.Chmod(rootDir, 0711); err != nil {
  853. return err
  854. }
  855. } else if os.IsNotExist(err) {
  856. // no root exists yet, create it 0711 with root:root ownership
  857. if err := os.MkdirAll(rootDir, 0711); err != nil {
  858. return err
  859. }
  860. }
  861. // if user namespaces are enabled we will create a subtree underneath the specified root
  862. // with any/all specified remapped root uid/gid options on the daemon creating
  863. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  864. // `chdir()` to work for containers namespaced to that uid/gid)
  865. if config.RemappedRoot != "" {
  866. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
  867. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  868. // Create the root directory if it doesn't exist
  869. if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
  870. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  871. }
  872. }
  873. return nil
  874. }
  875. // registerLinks writes the links to a file.
  876. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  877. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  878. return nil
  879. }
  880. for _, l := range hostConfig.Links {
  881. name, alias, err := runconfigopts.ParseLink(l)
  882. if err != nil {
  883. return err
  884. }
  885. child, err := daemon.GetContainer(name)
  886. if err != nil {
  887. return fmt.Errorf("Could not get container for %s", name)
  888. }
  889. for child.HostConfig.NetworkMode.IsContainer() {
  890. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  891. child, err = daemon.GetContainer(parts[1])
  892. if err != nil {
  893. return fmt.Errorf("Could not get container for %s", parts[1])
  894. }
  895. }
  896. if child.HostConfig.NetworkMode.IsHost() {
  897. return runconfig.ErrConflictHostNetworkAndLinks
  898. }
  899. if err := daemon.registerLink(container, child, alias); err != nil {
  900. return err
  901. }
  902. }
  903. // After we load all the links into the daemon
  904. // set them to nil on the hostconfig
  905. return container.WriteHostConfig()
  906. }
  907. // conditionalMountOnStart is a platform specific helper function during the
  908. // container start to call mount.
  909. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  910. return daemon.Mount(container)
  911. }
  912. // conditionalUnmountOnCleanup is a platform specific helper function called
  913. // during the cleanup of a container to unmount.
  914. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  915. return daemon.Unmount(container)
  916. }
  917. func restoreCustomImage(is image.Store, ls layer.Store, rs reference.Store) error {
  918. // Unix has no custom images to register
  919. return nil
  920. }
  921. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  922. if !c.IsRunning() {
  923. return nil, errNotRunning{c.ID}
  924. }
  925. stats, err := daemon.containerd.Stats(c.ID)
  926. if err != nil {
  927. return nil, err
  928. }
  929. s := &types.StatsJSON{}
  930. cgs := stats.CgroupStats
  931. if cgs != nil {
  932. s.BlkioStats = types.BlkioStats{
  933. IoServiceBytesRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceBytesRecursive),
  934. IoServicedRecursive: copyBlkioEntry(cgs.BlkioStats.IoServicedRecursive),
  935. IoQueuedRecursive: copyBlkioEntry(cgs.BlkioStats.IoQueuedRecursive),
  936. IoServiceTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceTimeRecursive),
  937. IoWaitTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoWaitTimeRecursive),
  938. IoMergedRecursive: copyBlkioEntry(cgs.BlkioStats.IoMergedRecursive),
  939. IoTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoTimeRecursive),
  940. SectorsRecursive: copyBlkioEntry(cgs.BlkioStats.SectorsRecursive),
  941. }
  942. cpu := cgs.CpuStats
  943. s.CPUStats = types.CPUStats{
  944. CPUUsage: types.CPUUsage{
  945. TotalUsage: cpu.CpuUsage.TotalUsage,
  946. PercpuUsage: cpu.CpuUsage.PercpuUsage,
  947. UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode,
  948. UsageInUsermode: cpu.CpuUsage.UsageInUsermode,
  949. },
  950. ThrottlingData: types.ThrottlingData{
  951. Periods: cpu.ThrottlingData.Periods,
  952. ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods,
  953. ThrottledTime: cpu.ThrottlingData.ThrottledTime,
  954. },
  955. }
  956. mem := cgs.MemoryStats.Usage
  957. s.MemoryStats = types.MemoryStats{
  958. Usage: mem.Usage,
  959. MaxUsage: mem.MaxUsage,
  960. Stats: cgs.MemoryStats.Stats,
  961. Failcnt: mem.Failcnt,
  962. Limit: mem.Limit,
  963. }
  964. // if the container does not set memory limit, use the machineMemory
  965. if mem.Limit > daemon.statsCollector.machineMemory && daemon.statsCollector.machineMemory > 0 {
  966. s.MemoryStats.Limit = daemon.statsCollector.machineMemory
  967. }
  968. if cgs.PidsStats != nil {
  969. s.PidsStats = types.PidsStats{
  970. Current: cgs.PidsStats.Current,
  971. }
  972. }
  973. }
  974. s.Read = time.Unix(int64(stats.Timestamp), 0)
  975. return s, nil
  976. }
  977. // setDefaultIsolation determines the default isolation mode for the
  978. // daemon to run in. This is only applicable on Windows
  979. func (daemon *Daemon) setDefaultIsolation() error {
  980. return nil
  981. }
  982. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  983. var layers []string
  984. for _, l := range rootfs.DiffIDs {
  985. layers = append(layers, l.String())
  986. }
  987. return types.RootFS{
  988. Type: rootfs.Type,
  989. Layers: layers,
  990. }
  991. }