daemon_unix.go 22 KB

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