daemon_unix.go 22 KB

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