daemon_unix.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  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/nat"
  17. "github.com/docker/docker/pkg/parsers"
  18. "github.com/docker/docker/pkg/parsers/kernel"
  19. "github.com/docker/docker/pkg/system"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/docker/utils"
  22. volumedrivers "github.com/docker/docker/volume/drivers"
  23. "github.com/docker/docker/volume/local"
  24. "github.com/docker/libnetwork"
  25. nwapi "github.com/docker/libnetwork/api"
  26. nwconfig "github.com/docker/libnetwork/config"
  27. "github.com/docker/libnetwork/netlabel"
  28. "github.com/docker/libnetwork/options"
  29. "github.com/opencontainers/runc/libcontainer/label"
  30. )
  31. func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  32. initID := fmt.Sprintf("%s-init", container.ID)
  33. return daemon.driver.Changes(container.ID, initID)
  34. }
  35. func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  36. initID := fmt.Sprintf("%s-init", container.ID)
  37. return daemon.driver.Diff(container.ID, initID)
  38. }
  39. func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error {
  40. var (
  41. labelOpts []string
  42. err error
  43. )
  44. for _, opt := range config.SecurityOpt {
  45. con := strings.SplitN(opt, ":", 2)
  46. if len(con) == 1 {
  47. return fmt.Errorf("Invalid --security-opt: %q", opt)
  48. }
  49. switch con[0] {
  50. case "label":
  51. labelOpts = append(labelOpts, con[1])
  52. case "apparmor":
  53. container.AppArmorProfile = con[1]
  54. default:
  55. return fmt.Errorf("Invalid --security-opt: %q", opt)
  56. }
  57. }
  58. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  59. return err
  60. }
  61. func (daemon *Daemon) createRootfs(container *Container) error {
  62. // Step 1: create the container directory.
  63. // This doubles as a barrier to avoid race conditions.
  64. if err := os.Mkdir(container.root, 0700); err != nil {
  65. return err
  66. }
  67. initID := fmt.Sprintf("%s-init", container.ID)
  68. if err := daemon.driver.Create(initID, container.ImageID); err != nil {
  69. return err
  70. }
  71. initPath, err := daemon.driver.Get(initID, "")
  72. if err != nil {
  73. return err
  74. }
  75. if err := setupInitLayer(initPath); err != nil {
  76. daemon.driver.Put(initID)
  77. return err
  78. }
  79. // We want to unmount init layer before we take snapshot of it
  80. // for the actual container.
  81. daemon.driver.Put(initID)
  82. if err := daemon.driver.Create(container.ID, initID); err != nil {
  83. return err
  84. }
  85. return nil
  86. }
  87. func checkKernel() error {
  88. // Check for unsupported kernel versions
  89. // FIXME: it would be cleaner to not test for specific versions, but rather
  90. // test for specific functionalities.
  91. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  92. // without actually causing a kernel panic, so we need this workaround until
  93. // the circumstances of pre-3.10 crashes are clearer.
  94. // For details see https://github.com/docker/docker/issues/407
  95. if k, err := kernel.GetKernelVersion(); err != nil {
  96. logrus.Warnf("%s", err)
  97. } else {
  98. if kernel.CompareKernelVersion(*k, kernel.VersionInfo{Kernel: 3, Major: 10, Minor: 0}) < 0 {
  99. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  100. 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())
  101. }
  102. }
  103. }
  104. return nil
  105. }
  106. func (daemon *Daemon) adaptContainerSettings(hostConfig *runconfig.HostConfig) {
  107. if hostConfig == nil {
  108. return
  109. }
  110. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  111. // By default, MemorySwap is set to twice the size of Memory.
  112. hostConfig.MemorySwap = hostConfig.Memory * 2
  113. }
  114. }
  115. func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  116. var warnings []string
  117. if config != nil {
  118. // The check for a valid workdir path is made on the server rather than in the
  119. // client. This is because we don't know the type of path (Linux or Windows)
  120. // to validate on the client.
  121. if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) {
  122. return warnings, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir)
  123. }
  124. }
  125. if hostConfig == nil {
  126. return warnings, nil
  127. }
  128. for port := range hostConfig.PortBindings {
  129. _, portStr := nat.SplitProtoPort(string(port))
  130. if _, err := nat.ParsePort(portStr); err != nil {
  131. return warnings, fmt.Errorf("Invalid port specification: %q", portStr)
  132. }
  133. for _, pb := range hostConfig.PortBindings[port] {
  134. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  135. if err != nil {
  136. return warnings, fmt.Errorf("Invalid port specification: %q", pb.HostPort)
  137. }
  138. }
  139. }
  140. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  141. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  142. }
  143. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  144. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  145. }
  146. if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  147. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  148. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  149. hostConfig.Memory = 0
  150. }
  151. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  152. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  153. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  154. hostConfig.MemorySwap = -1
  155. }
  156. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  157. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  158. }
  159. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  160. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  161. }
  162. if hostConfig.MemorySwappiness != nil && !daemon.SystemConfig().MemorySwappiness {
  163. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  164. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  165. hostConfig.MemorySwappiness = nil
  166. }
  167. if hostConfig.MemorySwappiness != nil {
  168. swappiness := *hostConfig.MemorySwappiness
  169. if swappiness < -1 || swappiness > 100 {
  170. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100.", swappiness)
  171. }
  172. }
  173. if hostConfig.CPUPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod {
  174. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  175. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  176. hostConfig.CPUPeriod = 0
  177. }
  178. if hostConfig.CPUQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  179. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  180. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  181. hostConfig.CPUQuota = 0
  182. }
  183. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  184. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  185. }
  186. if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable {
  187. hostConfig.OomKillDisable = false
  188. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  189. }
  190. if daemon.SystemConfig().IPv4ForwardingDisabled {
  191. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  192. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  193. }
  194. return warnings, nil
  195. }
  196. // checkConfigOptions checks for mutually incompatible config options
  197. func checkConfigOptions(config *Config) error {
  198. // Check for mutually incompatible config options
  199. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  200. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  201. }
  202. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  203. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  204. }
  205. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  206. config.Bridge.EnableIPMasq = false
  207. }
  208. return nil
  209. }
  210. // checkSystem validates platform-specific requirements
  211. func checkSystem() error {
  212. if os.Geteuid() != 0 {
  213. return fmt.Errorf("The Docker daemon needs to be run as root")
  214. }
  215. if err := checkKernel(); err != nil {
  216. return err
  217. }
  218. return nil
  219. }
  220. // configureKernelSecuritySupport configures and validate security support for the kernel
  221. func configureKernelSecuritySupport(config *Config, driverName string) error {
  222. if config.EnableSelinuxSupport {
  223. if selinuxEnabled() {
  224. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  225. if driverName == "btrfs" {
  226. return fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
  227. }
  228. logrus.Debug("SELinux enabled successfully")
  229. } else {
  230. logrus.Warn("Docker could not enable SELinux on the host system")
  231. }
  232. } else {
  233. selinuxSetDisabled()
  234. }
  235. return nil
  236. }
  237. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  238. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  239. return migrateIfAufs(driver, root)
  240. }
  241. func configureVolumes(config *Config) error {
  242. volumesDriver, err := local.New(config.Root)
  243. if err != nil {
  244. return err
  245. }
  246. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  247. return nil
  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. if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil {
  339. return fmt.Errorf("Error initializing bridge driver: %v", err)
  340. }
  341. netOption := options.Generic{
  342. "BridgeName": config.Bridge.Iface,
  343. "Mtu": config.Mtu,
  344. "EnableIPTables": config.Bridge.EnableIPTables,
  345. "EnableIPMasquerade": config.Bridge.EnableIPMasq,
  346. "EnableICC": config.Bridge.InterContainerCommunication,
  347. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy,
  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. func (daemon *Daemon) NetworkApiRouter() func(w http.ResponseWriter, req *http.Request) {
  448. return nwapi.NewHTTPHandler(daemon.netController)
  449. }
  450. func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
  451. if hostConfig == nil || hostConfig.Links == nil {
  452. return nil
  453. }
  454. for _, l := range hostConfig.Links {
  455. name, alias, err := parsers.ParseLink(l)
  456. if err != nil {
  457. return err
  458. }
  459. child, err := daemon.Get(name)
  460. if err != nil {
  461. //An error from daemon.Get() means this name could not be found
  462. return fmt.Errorf("Could not get container for %s", name)
  463. }
  464. for child.hostConfig.NetworkMode.IsContainer() {
  465. parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2)
  466. child, err = daemon.Get(parts[1])
  467. if err != nil {
  468. return fmt.Errorf("Could not get container for %s", parts[1])
  469. }
  470. }
  471. if child.hostConfig.NetworkMode.IsHost() {
  472. return runconfig.ErrConflictHostNetworkAndLinks
  473. }
  474. if err := daemon.RegisterLink(container, child, alias); err != nil {
  475. return err
  476. }
  477. }
  478. // After we load all the links into the daemon
  479. // set them to nil on the hostconfig
  480. hostConfig.Links = nil
  481. if err := container.WriteHostConfig(); err != nil {
  482. return err
  483. }
  484. return nil
  485. }
  486. func (daemon *Daemon) newBaseContainer(id string) Container {
  487. return Container{
  488. CommonContainer: CommonContainer{
  489. ID: id,
  490. State: NewState(),
  491. execCommands: newExecStore(),
  492. root: daemon.containerRoot(id),
  493. },
  494. MountPoints: make(map[string]*mountPoint),
  495. Volumes: make(map[string]string),
  496. VolumesRW: make(map[string]bool),
  497. }
  498. }