daemon_unix.go 35 KB

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