daemon_unix.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531
  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.KernelVersionInfo{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) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  107. var warnings []string
  108. if config != nil {
  109. // The check for a valid workdir path is made on the server rather than in the
  110. // client. This is because we don't know the type of path (Linux or Windows)
  111. // to validate on the client.
  112. if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) {
  113. return warnings, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir)
  114. }
  115. }
  116. if hostConfig == nil {
  117. return warnings, nil
  118. }
  119. for port := range hostConfig.PortBindings {
  120. _, portStr := nat.SplitProtoPort(string(port))
  121. if _, err := nat.ParsePort(portStr); err != nil {
  122. return warnings, fmt.Errorf("Invalid port specification: %q", portStr)
  123. }
  124. for _, pb := range hostConfig.PortBindings[port] {
  125. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  126. if err != nil {
  127. return warnings, fmt.Errorf("Invalid port specification: %q", pb.HostPort)
  128. }
  129. }
  130. }
  131. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  132. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  133. }
  134. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  135. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  136. }
  137. if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  138. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  139. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  140. hostConfig.Memory = 0
  141. }
  142. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  143. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  144. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  145. hostConfig.MemorySwap = -1
  146. }
  147. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  148. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  149. }
  150. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  151. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  152. }
  153. if hostConfig.MemorySwappiness != -1 && !daemon.SystemConfig().MemorySwappiness {
  154. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  155. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  156. hostConfig.MemorySwappiness = -1
  157. }
  158. if hostConfig.MemorySwappiness != -1 && (hostConfig.MemorySwappiness < 0 || hostConfig.MemorySwappiness > 100) {
  159. return warnings, fmt.Errorf("Invalid value: %d, valid memory swappiness range is 0-100.", hostConfig.MemorySwappiness)
  160. }
  161. if hostConfig.CpuPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod {
  162. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  163. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  164. hostConfig.CpuPeriod = 0
  165. }
  166. if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  167. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  168. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  169. hostConfig.CpuQuota = 0
  170. }
  171. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  172. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  173. }
  174. if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable {
  175. hostConfig.OomKillDisable = false
  176. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  177. }
  178. if daemon.SystemConfig().IPv4ForwardingDisabled {
  179. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  180. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  181. }
  182. return warnings, nil
  183. }
  184. // checkConfigOptions checks for mutually incompatible config options
  185. func checkConfigOptions(config *Config) error {
  186. // Check for mutually incompatible config options
  187. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  188. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  189. }
  190. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  191. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  192. }
  193. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  194. config.Bridge.EnableIPMasq = false
  195. }
  196. return nil
  197. }
  198. // checkSystem validates platform-specific requirements
  199. func checkSystem() error {
  200. if os.Geteuid() != 0 {
  201. return fmt.Errorf("The Docker daemon needs to be run as root")
  202. }
  203. if err := checkKernel(); err != nil {
  204. return err
  205. }
  206. return nil
  207. }
  208. // configureKernelSecuritySupport configures and validate security support for the kernel
  209. func configureKernelSecuritySupport(config *Config, driverName string) error {
  210. if config.EnableSelinuxSupport {
  211. if selinuxEnabled() {
  212. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  213. if driverName == "btrfs" {
  214. return fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
  215. }
  216. logrus.Debug("SELinux enabled successfully")
  217. } else {
  218. logrus.Warn("Docker could not enable SELinux on the host system")
  219. }
  220. } else {
  221. selinuxSetDisabled()
  222. }
  223. return nil
  224. }
  225. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  226. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  227. return migrateIfAufs(driver, root)
  228. }
  229. func configureVolumes(config *Config) error {
  230. volumesDriver, err := local.New(config.Root)
  231. if err != nil {
  232. return err
  233. }
  234. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  235. return nil
  236. }
  237. func configureSysInit(config *Config) (string, error) {
  238. localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  239. sysInitPath := utils.DockerInitPath(localCopy)
  240. if sysInitPath == "" {
  241. 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.")
  242. }
  243. if sysInitPath != localCopy {
  244. // 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).
  245. if err := os.Mkdir(filepath.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  246. return "", err
  247. }
  248. if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
  249. return "", err
  250. }
  251. if err := os.Chmod(localCopy, 0700); err != nil {
  252. return "", err
  253. }
  254. sysInitPath = localCopy
  255. }
  256. return sysInitPath, nil
  257. }
  258. func isBridgeNetworkDisabled(config *Config) bool {
  259. return config.Bridge.Iface == disableNetworkBridge
  260. }
  261. func networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  262. options := []nwconfig.Option{}
  263. if dconfig == nil {
  264. return options, nil
  265. }
  266. if strings.TrimSpace(dconfig.DefaultNetwork) != "" {
  267. dn := strings.Split(dconfig.DefaultNetwork, ":")
  268. if len(dn) < 2 {
  269. return nil, fmt.Errorf("default network daemon config must be of the form NETWORKDRIVER:NETWORKNAME")
  270. }
  271. options = append(options, nwconfig.OptionDefaultDriver(dn[0]))
  272. options = append(options, nwconfig.OptionDefaultNetwork(strings.Join(dn[1:], ":")))
  273. } else {
  274. dd := runconfig.DefaultDaemonNetworkMode()
  275. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  276. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  277. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  278. }
  279. if strings.TrimSpace(dconfig.NetworkKVStore) != "" {
  280. kv := strings.Split(dconfig.NetworkKVStore, ":")
  281. if len(kv) < 2 {
  282. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER:KV-URL")
  283. }
  284. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  285. options = append(options, nwconfig.OptionKVProviderURL(strings.Join(kv[1:], ":")))
  286. }
  287. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  288. return options, nil
  289. }
  290. func initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  291. netOptions, err := networkOptions(config)
  292. if err != nil {
  293. return nil, err
  294. }
  295. controller, err := libnetwork.New(netOptions...)
  296. if err != nil {
  297. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  298. }
  299. // Initialize default driver "null"
  300. if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil {
  301. return nil, fmt.Errorf("Error initializing null driver: %v", err)
  302. }
  303. // Initialize default network on "null"
  304. if _, err := controller.NewNetwork("null", "none"); err != nil {
  305. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  306. }
  307. // Initialize default driver "host"
  308. if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil {
  309. return nil, fmt.Errorf("Error initializing host driver: %v", err)
  310. }
  311. // Initialize default network on "host"
  312. if _, err := controller.NewNetwork("host", "host"); err != nil {
  313. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  314. }
  315. if !config.DisableBridge {
  316. // Initialize default driver "bridge"
  317. if err := initBridgeDriver(controller, config); err != nil {
  318. return nil, err
  319. }
  320. }
  321. return controller, nil
  322. }
  323. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  324. option := options.Generic{
  325. "EnableIPForwarding": config.Bridge.EnableIPForward}
  326. if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil {
  327. return fmt.Errorf("Error initializing bridge driver: %v", err)
  328. }
  329. netOption := options.Generic{
  330. "BridgeName": config.Bridge.Iface,
  331. "Mtu": config.Mtu,
  332. "EnableIPTables": config.Bridge.EnableIPTables,
  333. "EnableIPMasquerade": config.Bridge.EnableIPMasq,
  334. "EnableICC": config.Bridge.InterContainerCommunication,
  335. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy,
  336. }
  337. if config.Bridge.IP != "" {
  338. ip, bipNet, err := net.ParseCIDR(config.Bridge.IP)
  339. if err != nil {
  340. return err
  341. }
  342. bipNet.IP = ip
  343. netOption["AddressIPv4"] = bipNet
  344. }
  345. if config.Bridge.FixedCIDR != "" {
  346. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  347. if err != nil {
  348. return err
  349. }
  350. netOption["FixedCIDR"] = fCIDR
  351. }
  352. if config.Bridge.FixedCIDRv6 != "" {
  353. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  354. if err != nil {
  355. return err
  356. }
  357. netOption["FixedCIDRv6"] = fCIDRv6
  358. }
  359. if config.Bridge.DefaultGatewayIPv4 != nil {
  360. netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4
  361. }
  362. if config.Bridge.DefaultGatewayIPv6 != nil {
  363. netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6
  364. }
  365. // --ip processing
  366. if config.Bridge.DefaultIP != nil {
  367. netOption["DefaultBindingIP"] = config.Bridge.DefaultIP
  368. }
  369. // Initialize default network on "bridge" with the same name
  370. _, err := controller.NewNetwork("bridge", "bridge",
  371. libnetwork.NetworkOptionGeneric(options.Generic{
  372. netlabel.GenericData: netOption,
  373. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  374. }))
  375. if err != nil {
  376. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  377. }
  378. return nil
  379. }
  380. // setupInitLayer populates a directory with mountpoints suitable
  381. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  382. // empty file at /.dockerinit
  383. //
  384. // This extra layer is used by all containers as the top-most ro layer. It protects
  385. // the container from unwanted side-effects on the rw layer.
  386. func setupInitLayer(initLayer string) error {
  387. for pth, typ := range map[string]string{
  388. "/dev/pts": "dir",
  389. "/dev/shm": "dir",
  390. "/proc": "dir",
  391. "/sys": "dir",
  392. "/.dockerinit": "file",
  393. "/.dockerenv": "file",
  394. "/etc/resolv.conf": "file",
  395. "/etc/hosts": "file",
  396. "/etc/hostname": "file",
  397. "/dev/console": "file",
  398. "/etc/mtab": "/proc/mounts",
  399. } {
  400. parts := strings.Split(pth, "/")
  401. prev := "/"
  402. for _, p := range parts[1:] {
  403. prev = filepath.Join(prev, p)
  404. syscall.Unlink(filepath.Join(initLayer, prev))
  405. }
  406. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  407. if os.IsNotExist(err) {
  408. if err := system.MkdirAll(filepath.Join(initLayer, filepath.Dir(pth)), 0755); err != nil {
  409. return err
  410. }
  411. switch typ {
  412. case "dir":
  413. if err := system.MkdirAll(filepath.Join(initLayer, pth), 0755); err != nil {
  414. return err
  415. }
  416. case "file":
  417. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  418. if err != nil {
  419. return err
  420. }
  421. f.Close()
  422. default:
  423. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  424. return err
  425. }
  426. }
  427. } else {
  428. return err
  429. }
  430. }
  431. }
  432. // Layer is ready to use, if it wasn't before.
  433. return nil
  434. }
  435. func (daemon *Daemon) NetworkApiRouter() func(w http.ResponseWriter, req *http.Request) {
  436. return nwapi.NewHTTPHandler(daemon.netController)
  437. }
  438. func (daemon *Daemon) RegisterLinks(container *Container, hostConfig *runconfig.HostConfig) error {
  439. if hostConfig == nil || hostConfig.Links == nil {
  440. return nil
  441. }
  442. for _, l := range hostConfig.Links {
  443. name, alias, err := parsers.ParseLink(l)
  444. if err != nil {
  445. return err
  446. }
  447. child, err := daemon.Get(name)
  448. if err != nil {
  449. //An error from daemon.Get() means this name could not be found
  450. return fmt.Errorf("Could not get container for %s", name)
  451. }
  452. for child.hostConfig.NetworkMode.IsContainer() {
  453. parts := strings.SplitN(string(child.hostConfig.NetworkMode), ":", 2)
  454. child, err = daemon.Get(parts[1])
  455. if err != nil {
  456. return fmt.Errorf("Could not get container for %s", parts[1])
  457. }
  458. }
  459. if child.hostConfig.NetworkMode.IsHost() {
  460. return runconfig.ErrConflictHostNetworkAndLinks
  461. }
  462. if err := daemon.RegisterLink(container, child, alias); err != nil {
  463. return err
  464. }
  465. }
  466. // After we load all the links into the daemon
  467. // set them to nil on the hostconfig
  468. hostConfig.Links = nil
  469. if err := container.WriteHostConfig(); err != nil {
  470. return err
  471. }
  472. return nil
  473. }