daemon_unix.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "net"
  6. "os"
  7. "path/filepath"
  8. "strconv"
  9. "strings"
  10. "syscall"
  11. "github.com/Sirupsen/logrus"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/graphdriver"
  14. derr "github.com/docker/docker/errors"
  15. "github.com/docker/docker/image"
  16. "github.com/docker/docker/layer"
  17. pblkiodev "github.com/docker/docker/pkg/blkiodev"
  18. "github.com/docker/docker/pkg/idtools"
  19. "github.com/docker/docker/pkg/parsers"
  20. "github.com/docker/docker/pkg/parsers/kernel"
  21. "github.com/docker/docker/pkg/sysinfo"
  22. "github.com/docker/docker/runconfig"
  23. "github.com/docker/docker/tag"
  24. "github.com/docker/libnetwork"
  25. nwconfig "github.com/docker/libnetwork/config"
  26. "github.com/docker/libnetwork/drivers/bridge"
  27. "github.com/docker/libnetwork/ipamutils"
  28. "github.com/docker/libnetwork/netlabel"
  29. "github.com/docker/libnetwork/options"
  30. "github.com/docker/libnetwork/types"
  31. blkiodev "github.com/opencontainers/runc/libcontainer/configs"
  32. "github.com/opencontainers/runc/libcontainer/label"
  33. "github.com/vishvananda/netlink"
  34. )
  35. const (
  36. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  37. linuxMinCPUShares = 2
  38. linuxMaxCPUShares = 262144
  39. platformSupported = true
  40. )
  41. func getBlkioWeightDevices(config *runconfig.HostConfig) ([]*blkiodev.WeightDevice, error) {
  42. var stat syscall.Stat_t
  43. var BlkioWeightDevices []*blkiodev.WeightDevice
  44. for _, weightDevice := range config.BlkioWeightDevice {
  45. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  46. return nil, err
  47. }
  48. WeightDevice := blkiodev.NewWeightDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), weightDevice.Weight, 0)
  49. BlkioWeightDevices = append(BlkioWeightDevices, WeightDevice)
  50. }
  51. return BlkioWeightDevices, nil
  52. }
  53. func parseSecurityOpt(container *container.Container, config *runconfig.HostConfig) error {
  54. var (
  55. labelOpts []string
  56. err error
  57. )
  58. for _, opt := range config.SecurityOpt {
  59. con := strings.SplitN(opt, ":", 2)
  60. if len(con) == 1 {
  61. return fmt.Errorf("Invalid --security-opt: %q", opt)
  62. }
  63. switch con[0] {
  64. case "label":
  65. labelOpts = append(labelOpts, con[1])
  66. case "apparmor":
  67. container.AppArmorProfile = con[1]
  68. case "seccomp":
  69. container.SeccompProfile = con[1]
  70. default:
  71. return fmt.Errorf("Invalid --security-opt: %q", opt)
  72. }
  73. }
  74. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  75. return err
  76. }
  77. func getBlkioReadBpsDevices(config *runconfig.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  78. var BlkioReadBpsDevice []*blkiodev.ThrottleDevice
  79. var stat syscall.Stat_t
  80. for _, bpsDevice := range config.BlkioDeviceReadBps {
  81. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  82. return nil, err
  83. }
  84. ReadBpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), bpsDevice.Rate)
  85. BlkioReadBpsDevice = append(BlkioReadBpsDevice, ReadBpsDevice)
  86. }
  87. return BlkioReadBpsDevice, nil
  88. }
  89. func getBlkioWriteBpsDevices(config *runconfig.HostConfig) ([]*blkiodev.ThrottleDevice, error) {
  90. var BlkioWriteBpsDevice []*blkiodev.ThrottleDevice
  91. var stat syscall.Stat_t
  92. for _, bpsDevice := range config.BlkioDeviceWriteBps {
  93. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  94. return nil, err
  95. }
  96. WriteBpsDevice := blkiodev.NewThrottleDevice(int64(stat.Rdev/256), int64(stat.Rdev%256), bpsDevice.Rate)
  97. BlkioWriteBpsDevice = append(BlkioWriteBpsDevice, WriteBpsDevice)
  98. }
  99. return BlkioWriteBpsDevice, nil
  100. }
  101. func checkKernelVersion(k, major, minor int) bool {
  102. if v, err := kernel.GetKernelVersion(); err != nil {
  103. logrus.Warnf("%s", err)
  104. } else {
  105. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  106. return false
  107. }
  108. }
  109. return true
  110. }
  111. func checkKernel() error {
  112. // Check for unsupported kernel versions
  113. // FIXME: it would be cleaner to not test for specific versions, but rather
  114. // test for specific functionalities.
  115. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  116. // without actually causing a kernel panic, so we need this workaround until
  117. // the circumstances of pre-3.10 crashes are clearer.
  118. // For details see https://github.com/docker/docker/issues/407
  119. if !checkKernelVersion(3, 10, 0) {
  120. v, _ := kernel.GetKernelVersion()
  121. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  122. logrus.Warnf("Your Linux kernel version %s can be unstable running docker. Please upgrade your kernel to 3.10.0.", v.String())
  123. }
  124. }
  125. return nil
  126. }
  127. // adaptContainerSettings is called during container creation to modify any
  128. // settings necessary in the HostConfig structure.
  129. func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig, adjustCPUShares bool) error {
  130. if adjustCPUShares && hostConfig.CPUShares > 0 {
  131. // Handle unsupported CPUShares
  132. if hostConfig.CPUShares < linuxMinCPUShares {
  133. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  134. hostConfig.CPUShares = linuxMinCPUShares
  135. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  136. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  137. hostConfig.CPUShares = linuxMaxCPUShares
  138. }
  139. }
  140. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  141. // By default, MemorySwap is set to twice the size of Memory.
  142. hostConfig.MemorySwap = hostConfig.Memory * 2
  143. }
  144. if hostConfig.ShmSize == nil {
  145. shmSize := container.DefaultSHMSize
  146. hostConfig.ShmSize = &shmSize
  147. }
  148. var err error
  149. if hostConfig.SecurityOpt == nil {
  150. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode)
  151. if err != nil {
  152. return err
  153. }
  154. }
  155. if hostConfig.MemorySwappiness == nil {
  156. defaultSwappiness := int64(-1)
  157. hostConfig.MemorySwappiness = &defaultSwappiness
  158. }
  159. return nil
  160. }
  161. // verifyPlatformContainerSettings performs platform-specific validation of the
  162. // hostconfig and config structures.
  163. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  164. warnings := []string{}
  165. sysInfo := sysinfo.New(true)
  166. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  167. if err != nil {
  168. return warnings, err
  169. }
  170. if hostConfig.ShmSize != nil && *hostConfig.ShmSize <= 0 {
  171. return warnings, fmt.Errorf("SHM size must be greater then 0")
  172. }
  173. // memory subsystem checks and adjustments
  174. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  175. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  176. }
  177. if hostConfig.Memory > 0 && !sysInfo.MemoryLimit {
  178. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  179. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  180. hostConfig.Memory = 0
  181. hostConfig.MemorySwap = -1
  182. }
  183. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !sysInfo.SwapLimit {
  184. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  185. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  186. hostConfig.MemorySwap = -1
  187. }
  188. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  189. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  190. }
  191. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  192. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  193. }
  194. if hostConfig.MemorySwappiness != nil && *hostConfig.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  195. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  196. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  197. hostConfig.MemorySwappiness = nil
  198. }
  199. if hostConfig.MemorySwappiness != nil {
  200. swappiness := *hostConfig.MemorySwappiness
  201. if swappiness < -1 || swappiness > 100 {
  202. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
  203. }
  204. }
  205. if hostConfig.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  206. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  207. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  208. hostConfig.MemoryReservation = 0
  209. }
  210. if hostConfig.Memory > 0 && hostConfig.MemoryReservation > 0 && hostConfig.Memory < hostConfig.MemoryReservation {
  211. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage.")
  212. }
  213. if hostConfig.KernelMemory > 0 && !sysInfo.KernelMemory {
  214. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  215. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  216. hostConfig.KernelMemory = 0
  217. }
  218. if hostConfig.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  219. 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.")
  220. 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.")
  221. }
  222. if hostConfig.CPUShares > 0 && !sysInfo.CPUShares {
  223. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  224. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  225. hostConfig.CPUShares = 0
  226. }
  227. if hostConfig.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  228. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  229. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  230. hostConfig.CPUPeriod = 0
  231. }
  232. if hostConfig.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  233. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  234. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  235. hostConfig.CPUQuota = 0
  236. }
  237. if (hostConfig.CpusetCpus != "" || hostConfig.CpusetMems != "") && !sysInfo.Cpuset {
  238. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  239. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  240. hostConfig.CpusetCpus = ""
  241. hostConfig.CpusetMems = ""
  242. }
  243. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(hostConfig.CpusetCpus)
  244. if err != nil {
  245. return warnings, derr.ErrorCodeInvalidCpusetCpus.WithArgs(hostConfig.CpusetCpus)
  246. }
  247. if !cpusAvailable {
  248. return warnings, derr.ErrorCodeNotAvailableCpusetCpus.WithArgs(hostConfig.CpusetCpus, sysInfo.Cpus)
  249. }
  250. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(hostConfig.CpusetMems)
  251. if err != nil {
  252. return warnings, derr.ErrorCodeInvalidCpusetMems.WithArgs(hostConfig.CpusetMems)
  253. }
  254. if !memsAvailable {
  255. return warnings, derr.ErrorCodeNotAvailableCpusetMems.WithArgs(hostConfig.CpusetMems, sysInfo.Mems)
  256. }
  257. if hostConfig.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  258. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  259. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  260. hostConfig.BlkioWeight = 0
  261. }
  262. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  263. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  264. }
  265. if len(hostConfig.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  266. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  267. logrus.Warnf("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  268. hostConfig.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  269. }
  270. if len(hostConfig.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  271. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  272. logrus.Warnf("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  273. hostConfig.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  274. }
  275. if len(hostConfig.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  276. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  277. logrus.Warnf("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  278. hostConfig.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  279. }
  280. if hostConfig.OomKillDisable && !sysInfo.OomKillDisable {
  281. hostConfig.OomKillDisable = false
  282. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  283. }
  284. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  285. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000].", hostConfig.OomScoreAdj)
  286. }
  287. if sysInfo.IPv4ForwardingDisabled {
  288. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  289. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  290. }
  291. return warnings, nil
  292. }
  293. // checkConfigOptions checks for mutually incompatible config options
  294. func checkConfigOptions(config *Config) error {
  295. // Check for mutually incompatible config options
  296. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  297. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  298. }
  299. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  300. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true.")
  301. }
  302. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  303. config.Bridge.EnableIPMasq = false
  304. }
  305. return nil
  306. }
  307. // checkSystem validates platform-specific requirements
  308. func checkSystem() error {
  309. if os.Geteuid() != 0 {
  310. return fmt.Errorf("The Docker daemon needs to be run as root")
  311. }
  312. return checkKernel()
  313. }
  314. // configureKernelSecuritySupport configures and validate security support for the kernel
  315. func configureKernelSecuritySupport(config *Config, driverName string) error {
  316. if config.EnableSelinuxSupport {
  317. if selinuxEnabled() {
  318. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  319. if driverName == "overlay" {
  320. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  321. }
  322. logrus.Debug("SELinux enabled successfully")
  323. } else {
  324. logrus.Warn("Docker could not enable SELinux on the host system")
  325. }
  326. } else {
  327. selinuxSetDisabled()
  328. }
  329. return nil
  330. }
  331. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  332. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  333. return migrateIfAufs(driver, root)
  334. }
  335. func isBridgeNetworkDisabled(config *Config) bool {
  336. return config.Bridge.Iface == disableNetworkBridge
  337. }
  338. func (daemon *Daemon) networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  339. options := []nwconfig.Option{}
  340. if dconfig == nil {
  341. return options, nil
  342. }
  343. options = append(options, nwconfig.OptionDataDir(dconfig.Root))
  344. dd := runconfig.DefaultDaemonNetworkMode()
  345. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  346. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  347. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  348. if strings.TrimSpace(dconfig.ClusterStore) != "" {
  349. kv := strings.Split(dconfig.ClusterStore, "://")
  350. if len(kv) != 2 {
  351. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER://KV-URL")
  352. }
  353. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  354. options = append(options, nwconfig.OptionKVProviderURL(kv[1]))
  355. }
  356. if len(dconfig.ClusterOpts) > 0 {
  357. options = append(options, nwconfig.OptionKVOpts(dconfig.ClusterOpts))
  358. }
  359. if daemon.discoveryWatcher != nil {
  360. options = append(options, nwconfig.OptionDiscoveryWatcher(daemon.discoveryWatcher))
  361. }
  362. if dconfig.ClusterAdvertise != "" {
  363. options = append(options, nwconfig.OptionDiscoveryAddress(dconfig.ClusterAdvertise))
  364. }
  365. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  366. options = append(options, driverOptions(dconfig)...)
  367. return options, nil
  368. }
  369. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  370. netOptions, err := daemon.networkOptions(config)
  371. if err != nil {
  372. return nil, err
  373. }
  374. controller, err := libnetwork.New(netOptions...)
  375. if err != nil {
  376. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  377. }
  378. // Initialize default network on "null"
  379. if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
  380. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  381. }
  382. // Initialize default network on "host"
  383. if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
  384. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  385. }
  386. if !config.DisableBridge {
  387. // Initialize default driver "bridge"
  388. if err := initBridgeDriver(controller, config); err != nil {
  389. return nil, err
  390. }
  391. }
  392. return controller, nil
  393. }
  394. func driverOptions(config *Config) []nwconfig.Option {
  395. bridgeConfig := options.Generic{
  396. "EnableIPForwarding": config.Bridge.EnableIPForward,
  397. "EnableIPTables": config.Bridge.EnableIPTables,
  398. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy}
  399. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  400. dOptions := []nwconfig.Option{}
  401. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  402. return dOptions
  403. }
  404. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  405. if n, err := controller.NetworkByName("bridge"); err == nil {
  406. if err = n.Delete(); err != nil {
  407. return fmt.Errorf("could not delete the default bridge network: %v", err)
  408. }
  409. }
  410. bridgeName := bridge.DefaultBridgeName
  411. if config.Bridge.Iface != "" {
  412. bridgeName = config.Bridge.Iface
  413. }
  414. netOption := map[string]string{
  415. bridge.BridgeName: bridgeName,
  416. bridge.DefaultBridge: strconv.FormatBool(true),
  417. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  418. bridge.EnableIPMasquerade: strconv.FormatBool(config.Bridge.EnableIPMasq),
  419. bridge.EnableICC: strconv.FormatBool(config.Bridge.InterContainerCommunication),
  420. }
  421. // --ip processing
  422. if config.Bridge.DefaultIP != nil {
  423. netOption[bridge.DefaultBindingIP] = config.Bridge.DefaultIP.String()
  424. }
  425. ipamV4Conf := libnetwork.IpamConf{}
  426. ipamV4Conf.AuxAddresses = make(map[string]string)
  427. if nw, _, err := ipamutils.ElectInterfaceAddresses(bridgeName); err == nil {
  428. ipamV4Conf.PreferredPool = nw.String()
  429. hip, _ := types.GetHostPartIP(nw.IP, nw.Mask)
  430. if hip.IsGlobalUnicast() {
  431. ipamV4Conf.Gateway = nw.IP.String()
  432. }
  433. }
  434. if config.Bridge.IP != "" {
  435. ipamV4Conf.PreferredPool = config.Bridge.IP
  436. ip, _, err := net.ParseCIDR(config.Bridge.IP)
  437. if err != nil {
  438. return err
  439. }
  440. ipamV4Conf.Gateway = ip.String()
  441. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  442. 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)
  443. }
  444. if config.Bridge.FixedCIDR != "" {
  445. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  446. if err != nil {
  447. return err
  448. }
  449. ipamV4Conf.SubPool = fCIDR.String()
  450. }
  451. if config.Bridge.DefaultGatewayIPv4 != nil {
  452. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4.String()
  453. }
  454. var (
  455. ipamV6Conf *libnetwork.IpamConf
  456. deferIPv6Alloc bool
  457. )
  458. if config.Bridge.FixedCIDRv6 != "" {
  459. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  460. if err != nil {
  461. return err
  462. }
  463. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  464. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  465. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  466. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  467. // on this network until after the driver has created the endpoint and returned the
  468. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  469. ones, _ := fCIDRv6.Mask.Size()
  470. deferIPv6Alloc = ones <= 80
  471. if ipamV6Conf == nil {
  472. ipamV6Conf = &libnetwork.IpamConf{}
  473. }
  474. ipamV6Conf.PreferredPool = fCIDRv6.String()
  475. }
  476. if config.Bridge.DefaultGatewayIPv6 != nil {
  477. if ipamV6Conf == nil {
  478. ipamV6Conf = &libnetwork.IpamConf{}
  479. }
  480. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6.String()
  481. }
  482. v4Conf := []*libnetwork.IpamConf{&ipamV4Conf}
  483. v6Conf := []*libnetwork.IpamConf{}
  484. if ipamV6Conf != nil {
  485. v6Conf = append(v6Conf, ipamV6Conf)
  486. }
  487. // Initialize default network on "bridge" with the same name
  488. _, err := controller.NewNetwork("bridge", "bridge",
  489. libnetwork.NetworkOptionGeneric(options.Generic{
  490. netlabel.GenericData: netOption,
  491. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  492. }),
  493. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf),
  494. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  495. if err != nil {
  496. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  497. }
  498. return nil
  499. }
  500. // setupInitLayer populates a directory with mountpoints suitable
  501. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  502. // empty file at /.dockerinit
  503. //
  504. // This extra layer is used by all containers as the top-most ro layer. It protects
  505. // the container from unwanted side-effects on the rw layer.
  506. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  507. for pth, typ := range map[string]string{
  508. "/dev/pts": "dir",
  509. "/dev/shm": "dir",
  510. "/proc": "dir",
  511. "/sys": "dir",
  512. "/.dockerinit": "file",
  513. "/.dockerenv": "file",
  514. "/etc/resolv.conf": "file",
  515. "/etc/hosts": "file",
  516. "/etc/hostname": "file",
  517. "/dev/console": "file",
  518. "/etc/mtab": "/proc/mounts",
  519. } {
  520. parts := strings.Split(pth, "/")
  521. prev := "/"
  522. for _, p := range parts[1:] {
  523. prev = filepath.Join(prev, p)
  524. syscall.Unlink(filepath.Join(initLayer, prev))
  525. }
  526. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  527. if os.IsNotExist(err) {
  528. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  529. return err
  530. }
  531. switch typ {
  532. case "dir":
  533. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  534. return err
  535. }
  536. case "file":
  537. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  538. if err != nil {
  539. return err
  540. }
  541. f.Chown(rootUID, rootGID)
  542. f.Close()
  543. default:
  544. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  545. return err
  546. }
  547. }
  548. } else {
  549. return err
  550. }
  551. }
  552. }
  553. // Layer is ready to use, if it wasn't before.
  554. return nil
  555. }
  556. // registerLinks writes the links to a file.
  557. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *runconfig.HostConfig) error {
  558. if hostConfig == nil || hostConfig.Links == nil {
  559. return nil
  560. }
  561. for _, l := range hostConfig.Links {
  562. name, alias, err := parsers.ParseLink(l)
  563. if err != nil {
  564. return err
  565. }
  566. child, err := daemon.Get(name)
  567. if err != nil {
  568. //An error from daemon.Get() means this name could not be found
  569. return fmt.Errorf("Could not get container for %s", name)
  570. }
  571. for child.HostConfig.NetworkMode.IsContainer() {
  572. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  573. child, err = daemon.Get(parts[1])
  574. if err != nil {
  575. return fmt.Errorf("Could not get container for %s", parts[1])
  576. }
  577. }
  578. if child.HostConfig.NetworkMode.IsHost() {
  579. return runconfig.ErrConflictHostNetworkAndLinks
  580. }
  581. if err := daemon.registerLink(container, child, alias); err != nil {
  582. return err
  583. }
  584. }
  585. // After we load all the links into the daemon
  586. // set them to nil on the hostconfig
  587. hostConfig.Links = nil
  588. if err := container.WriteHostConfig(); err != nil {
  589. return err
  590. }
  591. return nil
  592. }
  593. // conditionalMountOnStart is a platform specific helper function during the
  594. // container start to call mount.
  595. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  596. return daemon.Mount(container)
  597. }
  598. // conditionalUnmountOnCleanup is a platform specific helper function called
  599. // during the cleanup of a container to unmount.
  600. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) {
  601. daemon.Unmount(container)
  602. }
  603. // getDefaultRouteMtu returns the MTU for the default route's interface.
  604. func getDefaultRouteMtu() (int, error) {
  605. routes, err := netlink.RouteList(nil, 0)
  606. if err != nil {
  607. return 0, err
  608. }
  609. for _, r := range routes {
  610. // a nil Dst means that this is the default route.
  611. if r.Dst == nil {
  612. i, err := net.InterfaceByIndex(r.LinkIndex)
  613. if err != nil {
  614. continue
  615. }
  616. return i.MTU, nil
  617. }
  618. }
  619. return 0, errNoDefaultRoute
  620. }
  621. func restoreCustomImage(driver graphdriver.Driver, is image.Store, ls layer.Store, ts tag.Store) error {
  622. // Unix has no custom images to register
  623. return nil
  624. }