daemon_unix.go 23 KB

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