daemon_unix.go 14 KB

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