daemon_unix.go 23 KB

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