daemon_unix.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465
  1. // +build !windows
  2. package daemon
  3. import (
  4. "fmt"
  5. "net"
  6. "net/http"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "strings"
  11. "syscall"
  12. "github.com/Sirupsen/logrus"
  13. "github.com/docker/docker/autogen/dockerversion"
  14. "github.com/docker/docker/daemon/graphdriver"
  15. "github.com/docker/docker/pkg/archive"
  16. "github.com/docker/docker/pkg/fileutils"
  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/libcontainer/label"
  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. )
  30. const runDir = "/var/run/docker"
  31. const defaultVolumesPathName = "volumes"
  32. func (daemon *Daemon) Changes(container *Container) ([]archive.Change, error) {
  33. initID := fmt.Sprintf("%s-init", container.ID)
  34. return daemon.driver.Changes(container.ID, initID)
  35. }
  36. func (daemon *Daemon) Diff(container *Container) (archive.Archive, error) {
  37. initID := fmt.Sprintf("%s-init", container.ID)
  38. return daemon.driver.Diff(container.ID, initID)
  39. }
  40. func parseSecurityOpt(container *Container, config *runconfig.HostConfig) error {
  41. var (
  42. labelOpts []string
  43. err error
  44. )
  45. for _, opt := range config.SecurityOpt {
  46. con := strings.SplitN(opt, ":", 2)
  47. if len(con) == 1 {
  48. return fmt.Errorf("Invalid --security-opt: %q", opt)
  49. }
  50. switch con[0] {
  51. case "label":
  52. labelOpts = append(labelOpts, con[1])
  53. case "apparmor":
  54. container.AppArmorProfile = con[1]
  55. default:
  56. return fmt.Errorf("Invalid --security-opt: %q", opt)
  57. }
  58. }
  59. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  60. return err
  61. }
  62. func (daemon *Daemon) createRootfs(container *Container) error {
  63. // Step 1: create the container directory.
  64. // This doubles as a barrier to avoid race conditions.
  65. if err := os.Mkdir(container.root, 0700); err != nil {
  66. return err
  67. }
  68. initID := fmt.Sprintf("%s-init", container.ID)
  69. if err := daemon.driver.Create(initID, container.ImageID); err != nil {
  70. return err
  71. }
  72. initPath, err := daemon.driver.Get(initID, "")
  73. if err != nil {
  74. return err
  75. }
  76. defer daemon.driver.Put(initID)
  77. if err := setupInitLayer(initPath); err != nil {
  78. return err
  79. }
  80. if err := daemon.driver.Create(container.ID, initID); err != nil {
  81. return err
  82. }
  83. return nil
  84. }
  85. func checkKernel() error {
  86. // Check for unsupported kernel versions
  87. // FIXME: it would be cleaner to not test for specific versions, but rather
  88. // test for specific functionalities.
  89. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  90. // without actually causing a kernel panic, so we need this workaround until
  91. // the circumstances of pre-3.10 crashes are clearer.
  92. // For details see https://github.com/docker/docker/issues/407
  93. if k, err := kernel.GetKernelVersion(); err != nil {
  94. logrus.Warnf("%s", err)
  95. } else {
  96. if kernel.CompareKernelVersion(k, &kernel.KernelVersionInfo{Kernel: 3, Major: 10, Minor: 0}) < 0 {
  97. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  98. 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())
  99. }
  100. }
  101. }
  102. return nil
  103. }
  104. func (daemon *Daemon) verifyContainerSettings(hostConfig *runconfig.HostConfig, config *runconfig.Config) ([]string, error) {
  105. var warnings []string
  106. if config != nil {
  107. // The check for a valid workdir path is made on the server rather than in the
  108. // client. This is because we don't know the type of path (Linux or Windows)
  109. // to validate on the client.
  110. if config.WorkingDir != "" && !filepath.IsAbs(config.WorkingDir) {
  111. return warnings, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path.", config.WorkingDir)
  112. }
  113. }
  114. if hostConfig == nil {
  115. return warnings, nil
  116. }
  117. if hostConfig.LxcConf.Len() > 0 && !strings.Contains(daemon.ExecutionDriver().Name(), "lxc") {
  118. return warnings, fmt.Errorf("Cannot use --lxc-conf with execdriver: %s", daemon.ExecutionDriver().Name())
  119. }
  120. if hostConfig.Memory != 0 && hostConfig.Memory < 4194304 {
  121. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  122. }
  123. if hostConfig.Memory > 0 && !daemon.SystemConfig().MemoryLimit {
  124. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  125. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  126. hostConfig.Memory = 0
  127. }
  128. if hostConfig.Memory > 0 && hostConfig.MemorySwap != -1 && !daemon.SystemConfig().SwapLimit {
  129. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  130. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  131. hostConfig.MemorySwap = -1
  132. }
  133. if hostConfig.Memory > 0 && hostConfig.MemorySwap > 0 && hostConfig.MemorySwap < hostConfig.Memory {
  134. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage.")
  135. }
  136. if hostConfig.Memory == 0 && hostConfig.MemorySwap > 0 {
  137. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage.")
  138. }
  139. if hostConfig.CpuPeriod > 0 && !daemon.SystemConfig().CpuCfsPeriod {
  140. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  141. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  142. hostConfig.CpuPeriod = 0
  143. }
  144. if hostConfig.CpuQuota > 0 && !daemon.SystemConfig().CpuCfsQuota {
  145. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  146. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  147. hostConfig.CpuQuota = 0
  148. }
  149. if hostConfig.BlkioWeight > 0 && (hostConfig.BlkioWeight < 10 || hostConfig.BlkioWeight > 1000) {
  150. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000.")
  151. }
  152. if hostConfig.OomKillDisable && !daemon.SystemConfig().OomKillDisable {
  153. hostConfig.OomKillDisable = false
  154. return warnings, fmt.Errorf("Your kernel does not support oom kill disable.")
  155. }
  156. if daemon.SystemConfig().IPv4ForwardingDisabled {
  157. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  158. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  159. }
  160. return warnings, nil
  161. }
  162. // checkConfigOptions checks for mutually incompatible config options
  163. func checkConfigOptions(config *Config) error {
  164. // Check for mutually incompatible config options
  165. if config.Bridge.Iface != "" && config.Bridge.IP != "" {
  166. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one.")
  167. }
  168. if !config.Bridge.EnableIPTables && !config.Bridge.InterContainerCommunication {
  169. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC uses iptables to function. Please set --icc or --iptables to true.")
  170. }
  171. if !config.Bridge.EnableIPTables && config.Bridge.EnableIPMasq {
  172. config.Bridge.EnableIPMasq = false
  173. }
  174. return nil
  175. }
  176. // checkSystem validates the system is supported and we have sufficient privileges
  177. func checkSystem() error {
  178. // TODO Windows. Once daemon is running on Windows, move this code back to
  179. // NewDaemon() in daemon.go, and extend the check to support Windows.
  180. if runtime.GOOS != "linux" {
  181. return ErrSystemNotSupported
  182. }
  183. if os.Geteuid() != 0 {
  184. return fmt.Errorf("The Docker daemon needs to be run as root")
  185. }
  186. if err := checkKernel(); err != nil {
  187. return err
  188. }
  189. return nil
  190. }
  191. // configureKernelSecuritySupport configures and validate security support for the kernel
  192. func configureKernelSecuritySupport(config *Config, driverName string) error {
  193. if config.EnableSelinuxSupport {
  194. if selinuxEnabled() {
  195. // As Docker on btrfs and SELinux are incompatible at present, error on both being enabled
  196. if driverName == "btrfs" {
  197. return fmt.Errorf("SELinux is not supported with the BTRFS graph driver")
  198. }
  199. logrus.Debug("SELinux enabled successfully")
  200. } else {
  201. logrus.Warn("Docker could not enable SELinux on the host system")
  202. }
  203. } else {
  204. selinuxSetDisabled()
  205. }
  206. return nil
  207. }
  208. // MigrateIfDownlevel is a wrapper for AUFS migration for downlevel
  209. func migrateIfDownlevel(driver graphdriver.Driver, root string) error {
  210. return migrateIfAufs(driver, root)
  211. }
  212. func configureVolumes(config *Config) error {
  213. volumesDriver, err := local.New(config.Root)
  214. if err != nil {
  215. return err
  216. }
  217. volumedrivers.Register(volumesDriver, volumesDriver.Name())
  218. return nil
  219. }
  220. func configureSysInit(config *Config) (string, error) {
  221. localCopy := filepath.Join(config.Root, "init", fmt.Sprintf("dockerinit-%s", dockerversion.VERSION))
  222. sysInitPath := utils.DockerInitPath(localCopy)
  223. if sysInitPath == "" {
  224. 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.")
  225. }
  226. if sysInitPath != localCopy {
  227. // 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).
  228. if err := os.Mkdir(filepath.Dir(localCopy), 0700); err != nil && !os.IsExist(err) {
  229. return "", err
  230. }
  231. if _, err := fileutils.CopyFile(sysInitPath, localCopy); err != nil {
  232. return "", err
  233. }
  234. if err := os.Chmod(localCopy, 0700); err != nil {
  235. return "", err
  236. }
  237. sysInitPath = localCopy
  238. }
  239. return sysInitPath, nil
  240. }
  241. func isNetworkDisabled(config *Config) bool {
  242. return config.Bridge.Iface == disableNetworkBridge
  243. }
  244. func networkOptions(dconfig *Config) ([]nwconfig.Option, error) {
  245. options := []nwconfig.Option{}
  246. if dconfig == nil {
  247. return options, nil
  248. }
  249. if strings.TrimSpace(dconfig.DefaultNetwork) != "" {
  250. dn := strings.Split(dconfig.DefaultNetwork, ":")
  251. if len(dn) < 2 {
  252. return nil, fmt.Errorf("default network daemon config must be of the form NETWORKDRIVER:NETWORKNAME")
  253. }
  254. options = append(options, nwconfig.OptionDefaultDriver(dn[0]))
  255. options = append(options, nwconfig.OptionDefaultNetwork(strings.Join(dn[1:], ":")))
  256. } else {
  257. dd := runconfig.DefaultDaemonNetworkMode()
  258. dn := runconfig.DefaultDaemonNetworkMode().NetworkName()
  259. options = append(options, nwconfig.OptionDefaultDriver(string(dd)))
  260. options = append(options, nwconfig.OptionDefaultNetwork(dn))
  261. }
  262. if strings.TrimSpace(dconfig.NetworkKVStore) != "" {
  263. kv := strings.Split(dconfig.NetworkKVStore, ":")
  264. if len(kv) < 2 {
  265. return nil, fmt.Errorf("kv store daemon config must be of the form KV-PROVIDER:KV-URL")
  266. }
  267. options = append(options, nwconfig.OptionKVProvider(kv[0]))
  268. options = append(options, nwconfig.OptionKVProviderURL(strings.Join(kv[1:], ":")))
  269. }
  270. options = append(options, nwconfig.OptionLabels(dconfig.Labels))
  271. return options, nil
  272. }
  273. func initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  274. netOptions, err := networkOptions(config)
  275. if err != nil {
  276. return nil, err
  277. }
  278. controller, err := libnetwork.New(netOptions...)
  279. if err != nil {
  280. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  281. }
  282. // Initialize default driver "null"
  283. if err := controller.ConfigureNetworkDriver("null", options.Generic{}); err != nil {
  284. return nil, fmt.Errorf("Error initializing null driver: %v", err)
  285. }
  286. // Initialize default network on "null"
  287. if _, err := controller.NewNetwork("null", "none"); err != nil {
  288. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  289. }
  290. // Initialize default driver "host"
  291. if err := controller.ConfigureNetworkDriver("host", options.Generic{}); err != nil {
  292. return nil, fmt.Errorf("Error initializing host driver: %v", err)
  293. }
  294. // Initialize default network on "host"
  295. if _, err := controller.NewNetwork("host", "host"); err != nil {
  296. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  297. }
  298. // Initialize default driver "bridge"
  299. option := options.Generic{
  300. "EnableIPForwarding": config.Bridge.EnableIPForward}
  301. if err := controller.ConfigureNetworkDriver("bridge", options.Generic{netlabel.GenericData: option}); err != nil {
  302. return nil, fmt.Errorf("Error initializing bridge driver: %v", err)
  303. }
  304. netOption := options.Generic{
  305. "BridgeName": config.Bridge.Iface,
  306. "Mtu": config.Mtu,
  307. "EnableIPTables": config.Bridge.EnableIPTables,
  308. "EnableIPMasquerade": config.Bridge.EnableIPMasq,
  309. "EnableICC": config.Bridge.InterContainerCommunication,
  310. "EnableUserlandProxy": config.Bridge.EnableUserlandProxy,
  311. }
  312. if config.Bridge.IP != "" {
  313. ip, bipNet, err := net.ParseCIDR(config.Bridge.IP)
  314. if err != nil {
  315. return nil, err
  316. }
  317. bipNet.IP = ip
  318. netOption["AddressIPv4"] = bipNet
  319. }
  320. if config.Bridge.FixedCIDR != "" {
  321. _, fCIDR, err := net.ParseCIDR(config.Bridge.FixedCIDR)
  322. if err != nil {
  323. return nil, err
  324. }
  325. netOption["FixedCIDR"] = fCIDR
  326. }
  327. if config.Bridge.FixedCIDRv6 != "" {
  328. _, fCIDRv6, err := net.ParseCIDR(config.Bridge.FixedCIDRv6)
  329. if err != nil {
  330. return nil, err
  331. }
  332. netOption["FixedCIDRv6"] = fCIDRv6
  333. }
  334. if config.Bridge.DefaultGatewayIPv4 != nil {
  335. netOption["DefaultGatewayIPv4"] = config.Bridge.DefaultGatewayIPv4
  336. }
  337. if config.Bridge.DefaultGatewayIPv6 != nil {
  338. netOption["DefaultGatewayIPv6"] = config.Bridge.DefaultGatewayIPv6
  339. }
  340. // --ip processing
  341. if config.Bridge.DefaultIP != nil {
  342. netOption["DefaultBindingIP"] = config.Bridge.DefaultIP
  343. }
  344. // Initialize default network on "bridge" with the same name
  345. _, err = controller.NewNetwork("bridge", "bridge",
  346. libnetwork.NetworkOptionGeneric(options.Generic{
  347. netlabel.GenericData: netOption,
  348. netlabel.EnableIPv6: config.Bridge.EnableIPv6,
  349. }))
  350. if err != nil {
  351. return nil, fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  352. }
  353. return controller, nil
  354. }
  355. // setupInitLayer populates a directory with mountpoints suitable
  356. // for bind-mounting dockerinit into the container. The mountpoint is simply an
  357. // empty file at /.dockerinit
  358. //
  359. // This extra layer is used by all containers as the top-most ro layer. It protects
  360. // the container from unwanted side-effects on the rw layer.
  361. func setupInitLayer(initLayer string) error {
  362. for pth, typ := range map[string]string{
  363. "/dev/pts": "dir",
  364. "/dev/shm": "dir",
  365. "/proc": "dir",
  366. "/sys": "dir",
  367. "/.dockerinit": "file",
  368. "/.dockerenv": "file",
  369. "/etc/resolv.conf": "file",
  370. "/etc/hosts": "file",
  371. "/etc/hostname": "file",
  372. "/dev/console": "file",
  373. "/etc/mtab": "/proc/mounts",
  374. } {
  375. parts := strings.Split(pth, "/")
  376. prev := "/"
  377. for _, p := range parts[1:] {
  378. prev = filepath.Join(prev, p)
  379. syscall.Unlink(filepath.Join(initLayer, prev))
  380. }
  381. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  382. if os.IsNotExist(err) {
  383. if err := system.MkdirAll(filepath.Join(initLayer, filepath.Dir(pth)), 0755); err != nil {
  384. return err
  385. }
  386. switch typ {
  387. case "dir":
  388. if err := system.MkdirAll(filepath.Join(initLayer, pth), 0755); err != nil {
  389. return err
  390. }
  391. case "file":
  392. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  393. if err != nil {
  394. return err
  395. }
  396. f.Close()
  397. default:
  398. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  399. return err
  400. }
  401. }
  402. } else {
  403. return err
  404. }
  405. }
  406. }
  407. // Layer is ready to use, if it wasn't before.
  408. return nil
  409. }
  410. func (daemon *Daemon) NetworkApiRouter() func(w http.ResponseWriter, req *http.Request) {
  411. return nwapi.NewHTTPHandler(daemon.netController)
  412. }