daemon_unix.go 15 KB

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