daemon_unix.go 42 KB

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