daemon_unix.go 19 KB

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