daemon_unix.go 36 KB

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