daemon_unix.go 41 KB

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