daemon_unix.go 37 KB

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