daemon_unix.go 20 KB

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