daemon_unix.go 18 KB

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