daemon_unix.go 43 KB

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