daemon_unix.go 20 KB

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