daemon_unix.go 54 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "bufio"
  5. "context"
  6. "fmt"
  7. "io/ioutil"
  8. "net"
  9. "os"
  10. "path/filepath"
  11. "runtime"
  12. "runtime/debug"
  13. "strconv"
  14. "strings"
  15. "time"
  16. containerd_cgroups "github.com/containerd/cgroups"
  17. "github.com/docker/docker/api/types"
  18. "github.com/docker/docker/api/types/blkiodev"
  19. pblkiodev "github.com/docker/docker/api/types/blkiodev"
  20. containertypes "github.com/docker/docker/api/types/container"
  21. "github.com/docker/docker/container"
  22. "github.com/docker/docker/daemon/config"
  23. "github.com/docker/docker/image"
  24. "github.com/docker/docker/opts"
  25. "github.com/docker/docker/pkg/containerfs"
  26. "github.com/docker/docker/pkg/idtools"
  27. "github.com/docker/docker/pkg/ioutils"
  28. "github.com/docker/docker/pkg/mount"
  29. "github.com/docker/docker/pkg/parsers"
  30. "github.com/docker/docker/pkg/parsers/kernel"
  31. "github.com/docker/docker/pkg/sysinfo"
  32. "github.com/docker/docker/runconfig"
  33. "github.com/docker/docker/volume"
  34. "github.com/docker/libnetwork"
  35. nwconfig "github.com/docker/libnetwork/config"
  36. "github.com/docker/libnetwork/drivers/bridge"
  37. "github.com/docker/libnetwork/netlabel"
  38. "github.com/docker/libnetwork/netutils"
  39. "github.com/docker/libnetwork/options"
  40. lntypes "github.com/docker/libnetwork/types"
  41. "github.com/opencontainers/runc/libcontainer/cgroups"
  42. rsystem "github.com/opencontainers/runc/libcontainer/system"
  43. specs "github.com/opencontainers/runtime-spec/specs-go"
  44. "github.com/opencontainers/selinux/go-selinux/label"
  45. "github.com/pkg/errors"
  46. "github.com/sirupsen/logrus"
  47. "github.com/vishvananda/netlink"
  48. "golang.org/x/sys/unix"
  49. )
  50. const (
  51. // DefaultShimBinary is the default shim to be used by containerd if none
  52. // is specified
  53. DefaultShimBinary = "docker-containerd-shim"
  54. // DefaultRuntimeBinary is the default runtime to be used by
  55. // containerd if none is specified
  56. DefaultRuntimeBinary = "docker-runc"
  57. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  58. linuxMinCPUShares = 2
  59. linuxMaxCPUShares = 262144
  60. platformSupported = true
  61. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  62. linuxMinMemory = 4194304
  63. // constants for remapped root settings
  64. defaultIDSpecifier string = "default"
  65. defaultRemappedID string = "dockremap"
  66. // constant for cgroup drivers
  67. cgroupFsDriver = "cgroupfs"
  68. cgroupSystemdDriver = "systemd"
  69. // DefaultRuntimeName is the default runtime to be used by
  70. // containerd if none is specified
  71. DefaultRuntimeName = "docker-runc"
  72. )
  73. type containerGetter interface {
  74. GetContainer(string) (*container.Container, error)
  75. }
  76. func getMemoryResources(config containertypes.Resources) *specs.LinuxMemory {
  77. memory := specs.LinuxMemory{}
  78. if config.Memory > 0 {
  79. memory.Limit = &config.Memory
  80. }
  81. if config.MemoryReservation > 0 {
  82. memory.Reservation = &config.MemoryReservation
  83. }
  84. if config.MemorySwap > 0 {
  85. memory.Swap = &config.MemorySwap
  86. }
  87. if config.MemorySwappiness != nil {
  88. swappiness := uint64(*config.MemorySwappiness)
  89. memory.Swappiness = &swappiness
  90. }
  91. if config.KernelMemory != 0 {
  92. memory.Kernel = &config.KernelMemory
  93. }
  94. return &memory
  95. }
  96. func getCPUResources(config containertypes.Resources) (*specs.LinuxCPU, error) {
  97. cpu := specs.LinuxCPU{}
  98. if config.CPUShares < 0 {
  99. return nil, fmt.Errorf("shares: invalid argument")
  100. }
  101. if config.CPUShares >= 0 {
  102. shares := uint64(config.CPUShares)
  103. cpu.Shares = &shares
  104. }
  105. if config.CpusetCpus != "" {
  106. cpu.Cpus = config.CpusetCpus
  107. }
  108. if config.CpusetMems != "" {
  109. cpu.Mems = config.CpusetMems
  110. }
  111. if config.NanoCPUs > 0 {
  112. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  113. period := uint64(100 * time.Millisecond / time.Microsecond)
  114. quota := config.NanoCPUs * int64(period) / 1e9
  115. cpu.Period = &period
  116. cpu.Quota = &quota
  117. }
  118. if config.CPUPeriod != 0 {
  119. period := uint64(config.CPUPeriod)
  120. cpu.Period = &period
  121. }
  122. if config.CPUQuota != 0 {
  123. q := config.CPUQuota
  124. cpu.Quota = &q
  125. }
  126. if config.CPURealtimePeriod != 0 {
  127. period := uint64(config.CPURealtimePeriod)
  128. cpu.RealtimePeriod = &period
  129. }
  130. if config.CPURealtimeRuntime != 0 {
  131. c := config.CPURealtimeRuntime
  132. cpu.RealtimeRuntime = &c
  133. }
  134. return &cpu, nil
  135. }
  136. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.LinuxWeightDevice, error) {
  137. var stat unix.Stat_t
  138. var blkioWeightDevices []specs.LinuxWeightDevice
  139. for _, weightDevice := range config.BlkioWeightDevice {
  140. if err := unix.Stat(weightDevice.Path, &stat); err != nil {
  141. return nil, err
  142. }
  143. weight := weightDevice.Weight
  144. d := specs.LinuxWeightDevice{Weight: &weight}
  145. d.Major = int64(stat.Rdev / 256)
  146. d.Minor = int64(stat.Rdev % 256)
  147. blkioWeightDevices = append(blkioWeightDevices, d)
  148. }
  149. return blkioWeightDevices, nil
  150. }
  151. func (daemon *Daemon) parseSecurityOpt(container *container.Container, hostConfig *containertypes.HostConfig) error {
  152. container.NoNewPrivileges = daemon.configStore.NoNewPrivileges
  153. return parseSecurityOpt(container, hostConfig)
  154. }
  155. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  156. var (
  157. labelOpts []string
  158. err error
  159. )
  160. for _, opt := range config.SecurityOpt {
  161. if opt == "no-new-privileges" {
  162. container.NoNewPrivileges = true
  163. continue
  164. }
  165. if opt == "disable" {
  166. labelOpts = append(labelOpts, "disable")
  167. continue
  168. }
  169. var con []string
  170. if strings.Contains(opt, "=") {
  171. con = strings.SplitN(opt, "=", 2)
  172. } else if strings.Contains(opt, ":") {
  173. con = strings.SplitN(opt, ":", 2)
  174. logrus.Warn("Security options with `:` as a separator are deprecated and will be completely unsupported in 17.04, use `=` instead.")
  175. }
  176. if len(con) != 2 {
  177. return fmt.Errorf("invalid --security-opt 1: %q", opt)
  178. }
  179. switch con[0] {
  180. case "label":
  181. labelOpts = append(labelOpts, con[1])
  182. case "apparmor":
  183. container.AppArmorProfile = con[1]
  184. case "seccomp":
  185. container.SeccompProfile = con[1]
  186. case "no-new-privileges":
  187. noNewPrivileges, err := strconv.ParseBool(con[1])
  188. if err != nil {
  189. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  190. }
  191. container.NoNewPrivileges = noNewPrivileges
  192. default:
  193. return fmt.Errorf("invalid --security-opt 2: %q", opt)
  194. }
  195. }
  196. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  197. return err
  198. }
  199. func getBlkioThrottleDevices(devs []*blkiodev.ThrottleDevice) ([]specs.LinuxThrottleDevice, error) {
  200. var throttleDevices []specs.LinuxThrottleDevice
  201. var stat unix.Stat_t
  202. for _, d := range devs {
  203. if err := unix.Stat(d.Path, &stat); err != nil {
  204. return nil, err
  205. }
  206. d := specs.LinuxThrottleDevice{Rate: d.Rate}
  207. d.Major = int64(stat.Rdev / 256)
  208. d.Minor = int64(stat.Rdev % 256)
  209. throttleDevices = append(throttleDevices, d)
  210. }
  211. return throttleDevices, nil
  212. }
  213. func checkKernel() error {
  214. // Check for unsupported kernel versions
  215. // FIXME: it would be cleaner to not test for specific versions, but rather
  216. // test for specific functionalities.
  217. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  218. // without actually causing a kernel panic, so we need this workaround until
  219. // the circumstances of pre-3.10 crashes are clearer.
  220. // For details see https://github.com/docker/docker/issues/407
  221. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  222. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  223. if !kernel.CheckKernelVersion(3, 10, 0) {
  224. v, _ := kernel.GetKernelVersion()
  225. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  226. logrus.Fatalf("Your Linux kernel version %s is not supported for running docker. Please upgrade your kernel to 3.10.0 or newer.", v.String())
  227. }
  228. }
  229. return nil
  230. }
  231. // adaptContainerSettings is called during container creation to modify any
  232. // settings necessary in the HostConfig structure.
  233. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  234. if adjustCPUShares && hostConfig.CPUShares > 0 {
  235. // Handle unsupported CPUShares
  236. if hostConfig.CPUShares < linuxMinCPUShares {
  237. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  238. hostConfig.CPUShares = linuxMinCPUShares
  239. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  240. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  241. hostConfig.CPUShares = linuxMaxCPUShares
  242. }
  243. }
  244. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  245. // By default, MemorySwap is set to twice the size of Memory.
  246. hostConfig.MemorySwap = hostConfig.Memory * 2
  247. }
  248. if hostConfig.ShmSize == 0 {
  249. hostConfig.ShmSize = config.DefaultShmSize
  250. if daemon.configStore != nil {
  251. hostConfig.ShmSize = int64(daemon.configStore.ShmSize)
  252. }
  253. }
  254. // Set default IPC mode, if unset for container
  255. if hostConfig.IpcMode.IsEmpty() {
  256. m := config.DefaultIpcMode
  257. if daemon.configStore != nil {
  258. m = daemon.configStore.IpcMode
  259. }
  260. hostConfig.IpcMode = containertypes.IpcMode(m)
  261. }
  262. adaptSharedNamespaceContainer(daemon, hostConfig)
  263. var err error
  264. opts, err := daemon.generateSecurityOpt(hostConfig)
  265. if err != nil {
  266. return err
  267. }
  268. hostConfig.SecurityOpt = append(hostConfig.SecurityOpt, opts...)
  269. if hostConfig.OomKillDisable == nil {
  270. defaultOomKillDisable := false
  271. hostConfig.OomKillDisable = &defaultOomKillDisable
  272. }
  273. return nil
  274. }
  275. // adaptSharedNamespaceContainer replaces container name with its ID in hostConfig.
  276. // To be more precisely, it modifies `container:name` to `container:ID` of PidMode, IpcMode
  277. // and NetworkMode.
  278. //
  279. // When a container shares its namespace with another container, use ID can keep the namespace
  280. // sharing connection between the two containers even the another container is renamed.
  281. func adaptSharedNamespaceContainer(daemon containerGetter, hostConfig *containertypes.HostConfig) {
  282. containerPrefix := "container:"
  283. if hostConfig.PidMode.IsContainer() {
  284. pidContainer := hostConfig.PidMode.Container()
  285. // if there is any error returned here, we just ignore it and leave it to be
  286. // handled in the following logic
  287. if c, err := daemon.GetContainer(pidContainer); err == nil {
  288. hostConfig.PidMode = containertypes.PidMode(containerPrefix + c.ID)
  289. }
  290. }
  291. if hostConfig.IpcMode.IsContainer() {
  292. ipcContainer := hostConfig.IpcMode.Container()
  293. if c, err := daemon.GetContainer(ipcContainer); err == nil {
  294. hostConfig.IpcMode = containertypes.IpcMode(containerPrefix + c.ID)
  295. }
  296. }
  297. if hostConfig.NetworkMode.IsContainer() {
  298. netContainer := hostConfig.NetworkMode.ConnectedContainer()
  299. if c, err := daemon.GetContainer(netContainer); err == nil {
  300. hostConfig.NetworkMode = containertypes.NetworkMode(containerPrefix + c.ID)
  301. }
  302. }
  303. }
  304. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  305. warnings := []string{}
  306. fixMemorySwappiness(resources)
  307. // memory subsystem checks and adjustments
  308. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  309. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  310. }
  311. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  312. warnings = append(warnings, "Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  313. logrus.Warn("Your kernel does not support memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  314. resources.Memory = 0
  315. resources.MemorySwap = -1
  316. }
  317. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  318. warnings = append(warnings, "Your kernel does not support swap limit capabilities or the cgroup is not mounted. Memory limited without swap.")
  319. logrus.Warn("Your kernel does not support swap limit capabilities,or the cgroup is not mounted. Memory limited without swap.")
  320. resources.MemorySwap = -1
  321. }
  322. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  323. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  324. }
  325. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  326. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  327. }
  328. if resources.MemorySwappiness != nil && !sysInfo.MemorySwappiness {
  329. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities or the cgroup is not mounted. Memory swappiness discarded.")
  330. logrus.Warn("Your kernel does not support memory swappiness capabilities, or the cgroup is not mounted. Memory swappiness discarded.")
  331. resources.MemorySwappiness = nil
  332. }
  333. if resources.MemorySwappiness != nil {
  334. swappiness := *resources.MemorySwappiness
  335. if swappiness < 0 || swappiness > 100 {
  336. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  337. }
  338. }
  339. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  340. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  341. logrus.Warn("Your kernel does not support memory soft limit capabilities or the cgroup is not mounted. Limitation discarded.")
  342. resources.MemoryReservation = 0
  343. }
  344. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  345. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  346. }
  347. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  348. return warnings, fmt.Errorf("Minimum memory limit can not be less than memory reservation limit, see usage")
  349. }
  350. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  351. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  352. logrus.Warn("Your kernel does not support kernel memory limit capabilities or the cgroup is not mounted. Limitation discarded.")
  353. resources.KernelMemory = 0
  354. }
  355. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  356. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  357. }
  358. if resources.KernelMemory > 0 && !kernel.CheckKernelVersion(4, 0, 0) {
  359. warnings = append(warnings, "You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  360. logrus.Warn("You specified a kernel memory limit on a kernel older than 4.0. Kernel memory limits are experimental on older kernels, it won't work as expected and can cause your system to be unstable.")
  361. }
  362. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  363. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  364. // warning the caller if they already wanted the feature to be off
  365. if *resources.OomKillDisable {
  366. warnings = append(warnings, "Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  367. logrus.Warn("Your kernel does not support OomKillDisable. OomKillDisable discarded.")
  368. }
  369. resources.OomKillDisable = nil
  370. }
  371. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  372. warnings = append(warnings, "Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  373. logrus.Warn("Your kernel does not support pids limit capabilities or the cgroup is not mounted. PIDs limit discarded.")
  374. resources.PidsLimit = 0
  375. }
  376. // cpu subsystem checks and adjustments
  377. if resources.NanoCPUs > 0 && resources.CPUPeriod > 0 {
  378. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Period cannot both be set")
  379. }
  380. if resources.NanoCPUs > 0 && resources.CPUQuota > 0 {
  381. return warnings, fmt.Errorf("Conflicting options: Nano CPUs and CPU Quota cannot both be set")
  382. }
  383. if resources.NanoCPUs > 0 && (!sysInfo.CPUCfsPeriod || !sysInfo.CPUCfsQuota) {
  384. return warnings, fmt.Errorf("NanoCPUs can not be set, as your kernel does not support CPU cfs period/quota or the cgroup is not mounted")
  385. }
  386. // The highest precision we could get on Linux is 0.001, by setting
  387. // cpu.cfs_period_us=1000ms
  388. // cpu.cfs_quota=1ms
  389. // See the following link for details:
  390. // https://www.kernel.org/doc/Documentation/scheduler/sched-bwc.txt
  391. // Here we don't set the lower limit and it is up to the underlying platform (e.g., Linux) to return an error.
  392. // The error message is 0.01 so that this is consistent with Windows
  393. if resources.NanoCPUs < 0 || resources.NanoCPUs > int64(sysinfo.NumCPU())*1e9 {
  394. return warnings, fmt.Errorf("Range of CPUs is from 0.01 to %d.00, as there are only %d CPUs available", sysinfo.NumCPU(), sysinfo.NumCPU())
  395. }
  396. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  397. warnings = append(warnings, "Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  398. logrus.Warn("Your kernel does not support CPU shares or the cgroup is not mounted. Shares discarded.")
  399. resources.CPUShares = 0
  400. }
  401. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  402. warnings = append(warnings, "Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  403. logrus.Warn("Your kernel does not support CPU cfs period or the cgroup is not mounted. Period discarded.")
  404. resources.CPUPeriod = 0
  405. }
  406. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  407. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  408. }
  409. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  410. warnings = append(warnings, "Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  411. logrus.Warn("Your kernel does not support CPU cfs quota or the cgroup is not mounted. Quota discarded.")
  412. resources.CPUQuota = 0
  413. }
  414. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  415. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  416. }
  417. if resources.CPUPercent > 0 {
  418. warnings = append(warnings, fmt.Sprintf("%s does not support CPU percent. Percent discarded.", runtime.GOOS))
  419. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  420. resources.CPUPercent = 0
  421. }
  422. // cpuset subsystem checks and adjustments
  423. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  424. warnings = append(warnings, "Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  425. logrus.Warn("Your kernel does not support cpuset or the cgroup is not mounted. Cpuset discarded.")
  426. resources.CpusetCpus = ""
  427. resources.CpusetMems = ""
  428. }
  429. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  430. if err != nil {
  431. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  432. }
  433. if !cpusAvailable {
  434. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  435. }
  436. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  437. if err != nil {
  438. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  439. }
  440. if !memsAvailable {
  441. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  442. }
  443. // blkio subsystem checks and adjustments
  444. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  445. warnings = append(warnings, "Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  446. logrus.Warn("Your kernel does not support Block I/O weight or the cgroup is not mounted. Weight discarded.")
  447. resources.BlkioWeight = 0
  448. }
  449. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  450. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  451. }
  452. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  453. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  454. }
  455. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  456. warnings = append(warnings, "Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  457. logrus.Warn("Your kernel does not support Block I/O weight_device or the cgroup is not mounted. Weight-device discarded.")
  458. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  459. }
  460. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  461. warnings = append(warnings, "Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded.")
  462. logrus.Warn("Your kernel does not support BPS Block I/O read limit or the cgroup is not mounted. Block I/O BPS read limit discarded")
  463. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  464. }
  465. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  466. warnings = append(warnings, "Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  467. logrus.Warn("Your kernel does not support BPS Block I/O write limit or the cgroup is not mounted. Block I/O BPS write limit discarded.")
  468. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  469. }
  470. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  471. warnings = append(warnings, "Your kernel does not support IOPS Block read limit or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  472. logrus.Warn("Your kernel does not support IOPS Block I/O read limit in IO or the cgroup is not mounted. Block I/O IOPS read limit discarded.")
  473. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  474. }
  475. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  476. warnings = append(warnings, "Your kernel does not support IOPS Block write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  477. logrus.Warn("Your kernel does not support IOPS Block I/O write limit or the cgroup is not mounted. Block I/O IOPS write limit discarded.")
  478. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  479. }
  480. return warnings, nil
  481. }
  482. func (daemon *Daemon) getCgroupDriver() string {
  483. cgroupDriver := cgroupFsDriver
  484. if UsingSystemd(daemon.configStore) {
  485. cgroupDriver = cgroupSystemdDriver
  486. }
  487. return cgroupDriver
  488. }
  489. // getCD gets the raw value of the native.cgroupdriver option, if set.
  490. func getCD(config *config.Config) string {
  491. for _, option := range config.ExecOptions {
  492. key, val, err := parsers.ParseKeyValueOpt(option)
  493. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  494. continue
  495. }
  496. return val
  497. }
  498. return ""
  499. }
  500. // VerifyCgroupDriver validates native.cgroupdriver
  501. func VerifyCgroupDriver(config *config.Config) error {
  502. cd := getCD(config)
  503. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  504. return nil
  505. }
  506. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  507. }
  508. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  509. func UsingSystemd(config *config.Config) bool {
  510. return getCD(config) == cgroupSystemdDriver
  511. }
  512. // verifyPlatformContainerSettings performs platform-specific validation of the
  513. // hostconfig and config structures.
  514. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  515. var warnings []string
  516. sysInfo := sysinfo.New(true)
  517. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  518. // no matter err is nil or not, w could have data in itself.
  519. warnings = append(warnings, w...)
  520. if err != nil {
  521. return warnings, err
  522. }
  523. if hostConfig.ShmSize < 0 {
  524. return warnings, fmt.Errorf("SHM size can not be less than 0")
  525. }
  526. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  527. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  528. }
  529. // ip-forwarding does not affect container with '--net=host' (or '--net=none')
  530. if sysInfo.IPv4ForwardingDisabled && !(hostConfig.NetworkMode.IsHost() || hostConfig.NetworkMode.IsNone()) {
  531. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  532. logrus.Warn("IPv4 forwarding is disabled. Networking will not work")
  533. }
  534. // check for various conflicting options with user namespaces
  535. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  536. if hostConfig.Privileged {
  537. return warnings, fmt.Errorf("privileged mode is incompatible with user namespaces. You must run the container in the host namespace when running privileged mode")
  538. }
  539. if hostConfig.NetworkMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  540. return warnings, fmt.Errorf("cannot share the host's network namespace when user namespaces are enabled")
  541. }
  542. if hostConfig.PidMode.IsHost() && !hostConfig.UsernsMode.IsHost() {
  543. return warnings, fmt.Errorf("cannot share the host PID namespace when user namespaces are enabled")
  544. }
  545. }
  546. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  547. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  548. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  549. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  550. }
  551. }
  552. if hostConfig.Runtime == "" {
  553. hostConfig.Runtime = daemon.configStore.GetDefaultRuntimeName()
  554. }
  555. if rt := daemon.configStore.GetRuntime(hostConfig.Runtime); rt == nil {
  556. return warnings, fmt.Errorf("Unknown runtime specified %s", hostConfig.Runtime)
  557. }
  558. parser := volume.NewParser(runtime.GOOS)
  559. for dest := range hostConfig.Tmpfs {
  560. if err := parser.ValidateTmpfsMountDestination(dest); err != nil {
  561. return warnings, err
  562. }
  563. }
  564. return warnings, nil
  565. }
  566. func (daemon *Daemon) loadRuntimes() error {
  567. return daemon.initRuntimes(daemon.configStore.Runtimes)
  568. }
  569. func (daemon *Daemon) initRuntimes(runtimes map[string]types.Runtime) (err error) {
  570. runtimeDir := filepath.Join(daemon.configStore.Root, "runtimes")
  571. // Remove old temp directory if any
  572. os.RemoveAll(runtimeDir + "-old")
  573. tmpDir, err := ioutils.TempDir(daemon.configStore.Root, "gen-runtimes")
  574. if err != nil {
  575. return errors.Wrapf(err, "failed to get temp dir to generate runtime scripts")
  576. }
  577. defer func() {
  578. if err != nil {
  579. if err1 := os.RemoveAll(tmpDir); err1 != nil {
  580. logrus.WithError(err1).WithField("dir", tmpDir).
  581. Warnf("failed to remove tmp dir")
  582. }
  583. return
  584. }
  585. if err = os.Rename(runtimeDir, runtimeDir+"-old"); err != nil {
  586. return
  587. }
  588. if err = os.Rename(tmpDir, runtimeDir); err != nil {
  589. err = errors.Wrapf(err, "failed to setup runtimes dir, new containers may not start")
  590. return
  591. }
  592. if err = os.RemoveAll(runtimeDir + "-old"); err != nil {
  593. logrus.WithError(err).WithField("dir", tmpDir).
  594. Warnf("failed to remove old runtimes dir")
  595. }
  596. }()
  597. for name, rt := range runtimes {
  598. if len(rt.Args) == 0 {
  599. continue
  600. }
  601. script := filepath.Join(tmpDir, name)
  602. content := fmt.Sprintf("#!/bin/sh\n%s %s $@\n", rt.Path, strings.Join(rt.Args, " "))
  603. if err := ioutil.WriteFile(script, []byte(content), 0700); err != nil {
  604. return err
  605. }
  606. }
  607. return nil
  608. }
  609. // verifyDaemonSettings performs validation of daemon config struct
  610. func verifyDaemonSettings(conf *config.Config) error {
  611. // Check for mutually incompatible config options
  612. if conf.BridgeConfig.Iface != "" && conf.BridgeConfig.IP != "" {
  613. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  614. }
  615. if !conf.BridgeConfig.EnableIPTables && !conf.BridgeConfig.InterContainerCommunication {
  616. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  617. }
  618. if !conf.BridgeConfig.EnableIPTables && conf.BridgeConfig.EnableIPMasq {
  619. conf.BridgeConfig.EnableIPMasq = false
  620. }
  621. if err := VerifyCgroupDriver(conf); err != nil {
  622. return err
  623. }
  624. if conf.CgroupParent != "" && UsingSystemd(conf) {
  625. if len(conf.CgroupParent) <= 6 || !strings.HasSuffix(conf.CgroupParent, ".slice") {
  626. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  627. }
  628. }
  629. if conf.DefaultRuntime == "" {
  630. conf.DefaultRuntime = config.StockRuntimeName
  631. }
  632. if conf.Runtimes == nil {
  633. conf.Runtimes = make(map[string]types.Runtime)
  634. }
  635. conf.Runtimes[config.StockRuntimeName] = types.Runtime{Path: DefaultRuntimeName}
  636. return nil
  637. }
  638. // checkSystem validates platform-specific requirements
  639. func checkSystem() error {
  640. if os.Geteuid() != 0 {
  641. return fmt.Errorf("The Docker daemon needs to be run as root")
  642. }
  643. return checkKernel()
  644. }
  645. // configureMaxThreads sets the Go runtime max threads threshold
  646. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  647. func configureMaxThreads(config *config.Config) error {
  648. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  649. if err != nil {
  650. return err
  651. }
  652. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  653. if err != nil {
  654. return err
  655. }
  656. maxThreads := (mtint / 100) * 90
  657. debug.SetMaxThreads(maxThreads)
  658. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  659. return nil
  660. }
  661. func overlaySupportsSelinux() (bool, error) {
  662. f, err := os.Open("/proc/kallsyms")
  663. if err != nil {
  664. if os.IsNotExist(err) {
  665. return false, nil
  666. }
  667. return false, err
  668. }
  669. defer f.Close()
  670. var symAddr, symType, symName, text string
  671. s := bufio.NewScanner(f)
  672. for s.Scan() {
  673. if err := s.Err(); err != nil {
  674. return false, err
  675. }
  676. text = s.Text()
  677. if _, err := fmt.Sscanf(text, "%s %s %s", &symAddr, &symType, &symName); err != nil {
  678. return false, fmt.Errorf("Scanning '%s' failed: %s", text, err)
  679. }
  680. // Check for presence of symbol security_inode_copy_up.
  681. if symName == "security_inode_copy_up" {
  682. return true, nil
  683. }
  684. }
  685. return false, nil
  686. }
  687. // configureKernelSecuritySupport configures and validates security support for the kernel
  688. func configureKernelSecuritySupport(config *config.Config, driverName string) error {
  689. if config.EnableSelinuxSupport {
  690. if !selinuxEnabled() {
  691. logrus.Warn("Docker could not enable SELinux on the host system")
  692. return nil
  693. }
  694. if driverName == "overlay" || driverName == "overlay2" {
  695. // If driver is overlay or overlay2, make sure kernel
  696. // supports selinux with overlay.
  697. supported, err := overlaySupportsSelinux()
  698. if err != nil {
  699. return err
  700. }
  701. if !supported {
  702. logrus.Warnf("SELinux is not supported with the %v graph driver on this kernel", driverName)
  703. }
  704. }
  705. } else {
  706. selinuxSetDisabled()
  707. }
  708. return nil
  709. }
  710. func (daemon *Daemon) initNetworkController(config *config.Config, activeSandboxes map[string]interface{}) (libnetwork.NetworkController, error) {
  711. netOptions, err := daemon.networkOptions(config, daemon.PluginStore, activeSandboxes)
  712. if err != nil {
  713. return nil, err
  714. }
  715. controller, err := libnetwork.New(netOptions...)
  716. if err != nil {
  717. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  718. }
  719. if len(activeSandboxes) > 0 {
  720. logrus.Info("There are old running containers, the network config will not take affect")
  721. return controller, nil
  722. }
  723. // Initialize default network on "null"
  724. if n, _ := controller.NetworkByName("none"); n == nil {
  725. if _, err := controller.NewNetwork("null", "none", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  726. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  727. }
  728. }
  729. // Initialize default network on "host"
  730. if n, _ := controller.NetworkByName("host"); n == nil {
  731. if _, err := controller.NewNetwork("host", "host", "", libnetwork.NetworkOptionPersist(true)); err != nil {
  732. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  733. }
  734. }
  735. // Clear stale bridge network
  736. if n, err := controller.NetworkByName("bridge"); err == nil {
  737. if err = n.Delete(); err != nil {
  738. return nil, fmt.Errorf("could not delete the default bridge network: %v", err)
  739. }
  740. }
  741. if !config.DisableBridge {
  742. // Initialize default driver "bridge"
  743. if err := initBridgeDriver(controller, config); err != nil {
  744. return nil, err
  745. }
  746. } else {
  747. removeDefaultBridgeInterface()
  748. }
  749. return controller, nil
  750. }
  751. func driverOptions(config *config.Config) []nwconfig.Option {
  752. bridgeConfig := options.Generic{
  753. "EnableIPForwarding": config.BridgeConfig.EnableIPForward,
  754. "EnableIPTables": config.BridgeConfig.EnableIPTables,
  755. "EnableUserlandProxy": config.BridgeConfig.EnableUserlandProxy,
  756. "UserlandProxyPath": config.BridgeConfig.UserlandProxyPath}
  757. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  758. dOptions := []nwconfig.Option{}
  759. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  760. return dOptions
  761. }
  762. func initBridgeDriver(controller libnetwork.NetworkController, config *config.Config) error {
  763. bridgeName := bridge.DefaultBridgeName
  764. if config.BridgeConfig.Iface != "" {
  765. bridgeName = config.BridgeConfig.Iface
  766. }
  767. netOption := map[string]string{
  768. bridge.BridgeName: bridgeName,
  769. bridge.DefaultBridge: strconv.FormatBool(true),
  770. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  771. bridge.EnableIPMasquerade: strconv.FormatBool(config.BridgeConfig.EnableIPMasq),
  772. bridge.EnableICC: strconv.FormatBool(config.BridgeConfig.InterContainerCommunication),
  773. }
  774. // --ip processing
  775. if config.BridgeConfig.DefaultIP != nil {
  776. netOption[bridge.DefaultBindingIP] = config.BridgeConfig.DefaultIP.String()
  777. }
  778. var (
  779. ipamV4Conf *libnetwork.IpamConf
  780. ipamV6Conf *libnetwork.IpamConf
  781. )
  782. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  783. nwList, nw6List, err := netutils.ElectInterfaceAddresses(bridgeName)
  784. if err != nil {
  785. return errors.Wrap(err, "list bridge addresses failed")
  786. }
  787. nw := nwList[0]
  788. if len(nwList) > 1 && config.BridgeConfig.FixedCIDR != "" {
  789. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  790. if err != nil {
  791. return errors.Wrap(err, "parse CIDR failed")
  792. }
  793. // Iterate through in case there are multiple addresses for the bridge
  794. for _, entry := range nwList {
  795. if fCIDR.Contains(entry.IP) {
  796. nw = entry
  797. break
  798. }
  799. }
  800. }
  801. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  802. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  803. if hip.IsGlobalUnicast() {
  804. ipamV4Conf.Gateway = nw.IP.String()
  805. }
  806. if config.BridgeConfig.IP != "" {
  807. ipamV4Conf.PreferredPool = config.BridgeConfig.IP
  808. ip, _, err := net.ParseCIDR(config.BridgeConfig.IP)
  809. if err != nil {
  810. return err
  811. }
  812. ipamV4Conf.Gateway = ip.String()
  813. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  814. logrus.Infof("Default bridge (%s) is assigned with an IP address %s. Daemon option --bip can be used to set a preferred IP address", bridgeName, ipamV4Conf.PreferredPool)
  815. }
  816. if config.BridgeConfig.FixedCIDR != "" {
  817. _, fCIDR, err := net.ParseCIDR(config.BridgeConfig.FixedCIDR)
  818. if err != nil {
  819. return err
  820. }
  821. ipamV4Conf.SubPool = fCIDR.String()
  822. }
  823. if config.BridgeConfig.DefaultGatewayIPv4 != nil {
  824. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.BridgeConfig.DefaultGatewayIPv4.String()
  825. }
  826. var deferIPv6Alloc bool
  827. if config.BridgeConfig.FixedCIDRv6 != "" {
  828. _, fCIDRv6, err := net.ParseCIDR(config.BridgeConfig.FixedCIDRv6)
  829. if err != nil {
  830. return err
  831. }
  832. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  833. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  834. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  835. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  836. // on this network until after the driver has created the endpoint and returned the
  837. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  838. ones, _ := fCIDRv6.Mask.Size()
  839. deferIPv6Alloc = ones <= 80
  840. if ipamV6Conf == nil {
  841. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  842. }
  843. ipamV6Conf.PreferredPool = fCIDRv6.String()
  844. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  845. // address belongs to the same network, we need to inform libnetwork about it, so
  846. // that it can be reserved with IPAM and it will not be given away to somebody else
  847. for _, nw6 := range nw6List {
  848. if fCIDRv6.Contains(nw6.IP) {
  849. ipamV6Conf.Gateway = nw6.IP.String()
  850. break
  851. }
  852. }
  853. }
  854. if config.BridgeConfig.DefaultGatewayIPv6 != nil {
  855. if ipamV6Conf == nil {
  856. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  857. }
  858. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.BridgeConfig.DefaultGatewayIPv6.String()
  859. }
  860. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  861. v6Conf := []*libnetwork.IpamConf{}
  862. if ipamV6Conf != nil {
  863. v6Conf = append(v6Conf, ipamV6Conf)
  864. }
  865. // Initialize default network on "bridge" with the same name
  866. _, err = controller.NewNetwork("bridge", "bridge", "",
  867. libnetwork.NetworkOptionEnableIPv6(config.BridgeConfig.EnableIPv6),
  868. libnetwork.NetworkOptionDriverOpts(netOption),
  869. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  870. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  871. if err != nil {
  872. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  873. }
  874. return nil
  875. }
  876. // Remove default bridge interface if present (--bridge=none use case)
  877. func removeDefaultBridgeInterface() {
  878. if lnk, err := netlink.LinkByName(bridge.DefaultBridgeName); err == nil {
  879. if err := netlink.LinkDel(lnk); err != nil {
  880. logrus.Warnf("Failed to remove bridge interface (%s): %v", bridge.DefaultBridgeName, err)
  881. }
  882. }
  883. }
  884. func (daemon *Daemon) getLayerInit() func(containerfs.ContainerFS) error {
  885. return daemon.setupInitLayer
  886. }
  887. // Parse the remapped root (user namespace) option, which can be one of:
  888. // username - valid username from /etc/passwd
  889. // username:groupname - valid username; valid groupname from /etc/group
  890. // uid - 32-bit unsigned int valid Linux UID value
  891. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  892. //
  893. // If no groupname is specified, and a username is specified, an attempt
  894. // will be made to lookup a gid for that username as a groupname
  895. //
  896. // If names are used, they are verified to exist in passwd/group
  897. func parseRemappedRoot(usergrp string) (string, string, error) {
  898. var (
  899. userID, groupID int
  900. username, groupname string
  901. )
  902. idparts := strings.Split(usergrp, ":")
  903. if len(idparts) > 2 {
  904. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  905. }
  906. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  907. // must be a uid; take it as valid
  908. userID = int(uid)
  909. luser, err := idtools.LookupUID(userID)
  910. if err != nil {
  911. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  912. }
  913. username = luser.Name
  914. if len(idparts) == 1 {
  915. // if the uid was numeric and no gid was specified, take the uid as the gid
  916. groupID = userID
  917. lgrp, err := idtools.LookupGID(groupID)
  918. if err != nil {
  919. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  920. }
  921. groupname = lgrp.Name
  922. }
  923. } else {
  924. lookupName := idparts[0]
  925. // special case: if the user specified "default", they want Docker to create or
  926. // use (after creation) the "dockremap" user/group for root remapping
  927. if lookupName == defaultIDSpecifier {
  928. lookupName = defaultRemappedID
  929. }
  930. luser, err := idtools.LookupUser(lookupName)
  931. if err != nil && idparts[0] != defaultIDSpecifier {
  932. // error if the name requested isn't the special "dockremap" ID
  933. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  934. } else if err != nil {
  935. // special case-- if the username == "default", then we have been asked
  936. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  937. // ranges will be used for the user and group mappings in user namespaced containers
  938. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  939. if err == nil {
  940. return defaultRemappedID, defaultRemappedID, nil
  941. }
  942. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  943. }
  944. username = luser.Name
  945. if len(idparts) == 1 {
  946. // we only have a string username, and no group specified; look up gid from username as group
  947. group, err := idtools.LookupGroup(lookupName)
  948. if err != nil {
  949. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  950. }
  951. groupname = group.Name
  952. }
  953. }
  954. if len(idparts) == 2 {
  955. // groupname or gid is separately specified and must be resolved
  956. // to an unsigned 32-bit gid
  957. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  958. // must be a gid, take it as valid
  959. groupID = int(gid)
  960. lgrp, err := idtools.LookupGID(groupID)
  961. if err != nil {
  962. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  963. }
  964. groupname = lgrp.Name
  965. } else {
  966. // not a number; attempt a lookup
  967. if _, err := idtools.LookupGroup(idparts[1]); err != nil {
  968. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  969. }
  970. groupname = idparts[1]
  971. }
  972. }
  973. return username, groupname, nil
  974. }
  975. func setupRemappedRoot(config *config.Config) (*idtools.IDMappings, error) {
  976. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  977. return nil, fmt.Errorf("User namespaces are only supported on Linux")
  978. }
  979. // if the daemon was started with remapped root option, parse
  980. // the config option to the int uid,gid values
  981. if config.RemappedRoot != "" {
  982. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  983. if err != nil {
  984. return nil, err
  985. }
  986. if username == "root" {
  987. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  988. // effectively
  989. logrus.Warn("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  990. return &idtools.IDMappings{}, nil
  991. }
  992. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  993. // update remapped root setting now that we have resolved them to actual names
  994. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  995. mappings, err := idtools.NewIDMappings(username, groupname)
  996. if err != nil {
  997. return nil, errors.Wrapf(err, "Can't create ID mappings: %v")
  998. }
  999. return mappings, nil
  1000. }
  1001. return &idtools.IDMappings{}, nil
  1002. }
  1003. func setupDaemonRoot(config *config.Config, rootDir string, rootIDs idtools.IDPair) error {
  1004. config.Root = rootDir
  1005. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  1006. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  1007. // (e.g. mounted layers of a container) can traverse this path.
  1008. // The user namespace support will create subdirectories for the remapped root host uid:gid
  1009. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  1010. // layer content subtrees.
  1011. if _, err := os.Stat(rootDir); err == nil {
  1012. // root current exists; verify the access bits are correct by setting them
  1013. if err = os.Chmod(rootDir, 0711); err != nil {
  1014. return err
  1015. }
  1016. } else if os.IsNotExist(err) {
  1017. // no root exists yet, create it 0711 with root:root ownership
  1018. if err := os.MkdirAll(rootDir, 0711); err != nil {
  1019. return err
  1020. }
  1021. }
  1022. // if user namespaces are enabled we will create a subtree underneath the specified root
  1023. // with any/all specified remapped root uid/gid options on the daemon creating
  1024. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  1025. // `chdir()` to work for containers namespaced to that uid/gid)
  1026. if config.RemappedRoot != "" {
  1027. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootIDs.UID, rootIDs.GID))
  1028. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  1029. // Create the root directory if it doesn't exist
  1030. if err := idtools.MkdirAllAndChown(config.Root, 0700, rootIDs); err != nil {
  1031. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  1032. }
  1033. // we also need to verify that any pre-existing directories in the path to
  1034. // the graphroot won't block access to remapped root--if any pre-existing directory
  1035. // has strict permissions that don't allow "x", container start will fail, so
  1036. // better to warn and fail now
  1037. dirPath := config.Root
  1038. for {
  1039. dirPath = filepath.Dir(dirPath)
  1040. if dirPath == "/" {
  1041. break
  1042. }
  1043. if !idtools.CanAccess(dirPath, rootIDs) {
  1044. return fmt.Errorf("a subdirectory in your graphroot path (%s) restricts access to the remapped root uid/gid; please fix by allowing 'o+x' permissions on existing directories", config.Root)
  1045. }
  1046. }
  1047. }
  1048. if err := ensureSharedOrSlave(config.Root); err != nil {
  1049. if err := mount.MakeShared(config.Root); err != nil {
  1050. logrus.WithError(err).WithField("dir", config.Root).Warn("Could not set daemon root propagation to shared, this is not generally critical but may cause some functionality to not work or fallback to less desirable behavior")
  1051. }
  1052. }
  1053. return nil
  1054. }
  1055. // registerLinks writes the links to a file.
  1056. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  1057. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  1058. return nil
  1059. }
  1060. for _, l := range hostConfig.Links {
  1061. name, alias, err := opts.ParseLink(l)
  1062. if err != nil {
  1063. return err
  1064. }
  1065. child, err := daemon.GetContainer(name)
  1066. if err != nil {
  1067. return errors.Wrapf(err, "could not get container for %s", name)
  1068. }
  1069. for child.HostConfig.NetworkMode.IsContainer() {
  1070. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  1071. child, err = daemon.GetContainer(parts[1])
  1072. if err != nil {
  1073. return errors.Wrapf(err, "Could not get container for %s", parts[1])
  1074. }
  1075. }
  1076. if child.HostConfig.NetworkMode.IsHost() {
  1077. return runconfig.ErrConflictHostNetworkAndLinks
  1078. }
  1079. if err := daemon.registerLink(container, child, alias); err != nil {
  1080. return err
  1081. }
  1082. }
  1083. // After we load all the links into the daemon
  1084. // set them to nil on the hostconfig
  1085. _, err := container.WriteHostConfig()
  1086. return err
  1087. }
  1088. // conditionalMountOnStart is a platform specific helper function during the
  1089. // container start to call mount.
  1090. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  1091. return daemon.Mount(container)
  1092. }
  1093. // conditionalUnmountOnCleanup is a platform specific helper function called
  1094. // during the cleanup of a container to unmount.
  1095. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  1096. return daemon.Unmount(container)
  1097. }
  1098. func copyBlkioEntry(entries []*containerd_cgroups.BlkIOEntry) []types.BlkioStatEntry {
  1099. out := make([]types.BlkioStatEntry, len(entries))
  1100. for i, re := range entries {
  1101. out[i] = types.BlkioStatEntry{
  1102. Major: re.Major,
  1103. Minor: re.Minor,
  1104. Op: re.Op,
  1105. Value: re.Value,
  1106. }
  1107. }
  1108. return out
  1109. }
  1110. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  1111. if !c.IsRunning() {
  1112. return nil, errNotRunning(c.ID)
  1113. }
  1114. cs, err := daemon.containerd.Stats(context.Background(), c.ID)
  1115. if err != nil {
  1116. if strings.Contains(err.Error(), "container not found") {
  1117. return nil, containerNotFound(c.ID)
  1118. }
  1119. return nil, err
  1120. }
  1121. s := &types.StatsJSON{}
  1122. s.Read = cs.Read
  1123. stats := cs.Metrics
  1124. if stats.Blkio != nil {
  1125. s.BlkioStats = types.BlkioStats{
  1126. IoServiceBytesRecursive: copyBlkioEntry(stats.Blkio.IoServiceBytesRecursive),
  1127. IoServicedRecursive: copyBlkioEntry(stats.Blkio.IoServicedRecursive),
  1128. IoQueuedRecursive: copyBlkioEntry(stats.Blkio.IoQueuedRecursive),
  1129. IoServiceTimeRecursive: copyBlkioEntry(stats.Blkio.IoServiceTimeRecursive),
  1130. IoWaitTimeRecursive: copyBlkioEntry(stats.Blkio.IoWaitTimeRecursive),
  1131. IoMergedRecursive: copyBlkioEntry(stats.Blkio.IoMergedRecursive),
  1132. IoTimeRecursive: copyBlkioEntry(stats.Blkio.IoTimeRecursive),
  1133. SectorsRecursive: copyBlkioEntry(stats.Blkio.SectorsRecursive),
  1134. }
  1135. }
  1136. if stats.CPU != nil {
  1137. s.CPUStats = types.CPUStats{
  1138. CPUUsage: types.CPUUsage{
  1139. TotalUsage: stats.CPU.Usage.Total,
  1140. PercpuUsage: stats.CPU.Usage.PerCPU,
  1141. UsageInKernelmode: stats.CPU.Usage.Kernel,
  1142. UsageInUsermode: stats.CPU.Usage.User,
  1143. },
  1144. ThrottlingData: types.ThrottlingData{
  1145. Periods: stats.CPU.Throttling.Periods,
  1146. ThrottledPeriods: stats.CPU.Throttling.ThrottledPeriods,
  1147. ThrottledTime: stats.CPU.Throttling.ThrottledTime,
  1148. },
  1149. }
  1150. }
  1151. if stats.Memory != nil {
  1152. raw := make(map[string]uint64)
  1153. raw["cache"] = stats.Memory.Cache
  1154. raw["rss"] = stats.Memory.RSS
  1155. raw["rss_huge"] = stats.Memory.RSSHuge
  1156. raw["mapped_file"] = stats.Memory.MappedFile
  1157. raw["dirty"] = stats.Memory.Dirty
  1158. raw["writeback"] = stats.Memory.Writeback
  1159. raw["pgpgin"] = stats.Memory.PgPgIn
  1160. raw["pgpgout"] = stats.Memory.PgPgOut
  1161. raw["pgfault"] = stats.Memory.PgFault
  1162. raw["pgmajfault"] = stats.Memory.PgMajFault
  1163. raw["inactive_anon"] = stats.Memory.InactiveAnon
  1164. raw["active_anon"] = stats.Memory.ActiveAnon
  1165. raw["inactive_file"] = stats.Memory.InactiveFile
  1166. raw["active_file"] = stats.Memory.ActiveFile
  1167. raw["unevictable"] = stats.Memory.Unevictable
  1168. raw["hierarchical_memory_limit"] = stats.Memory.HierarchicalMemoryLimit
  1169. raw["hierarchical_memsw_limit"] = stats.Memory.HierarchicalSwapLimit
  1170. raw["total_cache"] = stats.Memory.TotalCache
  1171. raw["total_rss"] = stats.Memory.TotalRSS
  1172. raw["total_rss_huge"] = stats.Memory.TotalRSSHuge
  1173. raw["total_mapped_file"] = stats.Memory.TotalMappedFile
  1174. raw["total_dirty"] = stats.Memory.TotalDirty
  1175. raw["total_writeback"] = stats.Memory.TotalWriteback
  1176. raw["total_pgpgin"] = stats.Memory.TotalPgPgIn
  1177. raw["total_pgpgout"] = stats.Memory.TotalPgPgOut
  1178. raw["total_pgfault"] = stats.Memory.TotalPgFault
  1179. raw["total_pgmajfault"] = stats.Memory.TotalPgMajFault
  1180. raw["total_inactive_anon"] = stats.Memory.TotalInactiveAnon
  1181. raw["total_active_anon"] = stats.Memory.TotalActiveAnon
  1182. raw["total_inactive_file"] = stats.Memory.TotalInactiveFile
  1183. raw["total_active_file"] = stats.Memory.TotalActiveFile
  1184. raw["total_unevictable"] = stats.Memory.TotalUnevictable
  1185. if stats.Memory.Usage != nil {
  1186. s.MemoryStats = types.MemoryStats{
  1187. Stats: raw,
  1188. Usage: stats.Memory.Usage.Usage,
  1189. MaxUsage: stats.Memory.Usage.Max,
  1190. Limit: stats.Memory.Usage.Limit,
  1191. Failcnt: stats.Memory.Usage.Failcnt,
  1192. }
  1193. } else {
  1194. s.MemoryStats = types.MemoryStats{
  1195. Stats: raw,
  1196. }
  1197. }
  1198. // if the container does not set memory limit, use the machineMemory
  1199. if s.MemoryStats.Limit > daemon.machineMemory && daemon.machineMemory > 0 {
  1200. s.MemoryStats.Limit = daemon.machineMemory
  1201. }
  1202. }
  1203. if stats.Pids != nil {
  1204. s.PidsStats = types.PidsStats{
  1205. Current: stats.Pids.Current,
  1206. Limit: stats.Pids.Limit,
  1207. }
  1208. }
  1209. return s, nil
  1210. }
  1211. // setDefaultIsolation determines the default isolation mode for the
  1212. // daemon to run in. This is only applicable on Windows
  1213. func (daemon *Daemon) setDefaultIsolation() error {
  1214. return nil
  1215. }
  1216. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  1217. var layers []string
  1218. for _, l := range rootfs.DiffIDs {
  1219. layers = append(layers, l.String())
  1220. }
  1221. return types.RootFS{
  1222. Type: rootfs.Type,
  1223. Layers: layers,
  1224. }
  1225. }
  1226. // setupDaemonProcess sets various settings for the daemon's process
  1227. func setupDaemonProcess(config *config.Config) error {
  1228. // setup the daemons oom_score_adj
  1229. if err := setupOOMScoreAdj(config.OOMScoreAdjust); err != nil {
  1230. return err
  1231. }
  1232. if err := setMayDetachMounts(); err != nil {
  1233. logrus.WithError(err).Warn("Could not set may_detach_mounts kernel parameter")
  1234. }
  1235. return nil
  1236. }
  1237. // This is used to allow removal of mountpoints that may be mounted in other
  1238. // namespaces on RHEL based kernels starting from RHEL 7.4.
  1239. // Without this setting, removals on these RHEL based kernels may fail with
  1240. // "device or resource busy".
  1241. // This setting is not available in upstream kernels as it is not configurable,
  1242. // but has been in the upstream kernels since 3.15.
  1243. func setMayDetachMounts() error {
  1244. f, err := os.OpenFile("/proc/sys/fs/may_detach_mounts", os.O_WRONLY, 0)
  1245. if err != nil {
  1246. if os.IsNotExist(err) {
  1247. return nil
  1248. }
  1249. return errors.Wrap(err, "error opening may_detach_mounts kernel config file")
  1250. }
  1251. defer f.Close()
  1252. _, err = f.WriteString("1")
  1253. if os.IsPermission(err) {
  1254. // Setting may_detach_mounts does not work in an
  1255. // unprivileged container. Ignore the error, but log
  1256. // it if we appear not to be in that situation.
  1257. if !rsystem.RunningInUserNS() {
  1258. logrus.Debugf("Permission denied writing %q to /proc/sys/fs/may_detach_mounts", "1")
  1259. }
  1260. return nil
  1261. }
  1262. return err
  1263. }
  1264. func setupOOMScoreAdj(score int) error {
  1265. f, err := os.OpenFile("/proc/self/oom_score_adj", os.O_WRONLY, 0)
  1266. if err != nil {
  1267. return err
  1268. }
  1269. defer f.Close()
  1270. stringScore := strconv.Itoa(score)
  1271. _, err = f.WriteString(stringScore)
  1272. if os.IsPermission(err) {
  1273. // Setting oom_score_adj does not work in an
  1274. // unprivileged container. Ignore the error, but log
  1275. // it if we appear not to be in that situation.
  1276. if !rsystem.RunningInUserNS() {
  1277. logrus.Debugf("Permission denied writing %q to /proc/self/oom_score_adj", stringScore)
  1278. }
  1279. return nil
  1280. }
  1281. return err
  1282. }
  1283. func (daemon *Daemon) initCgroupsPath(path string) error {
  1284. if path == "/" || path == "." {
  1285. return nil
  1286. }
  1287. if daemon.configStore.CPURealtimePeriod == 0 && daemon.configStore.CPURealtimeRuntime == 0 {
  1288. return nil
  1289. }
  1290. // Recursively create cgroup to ensure that the system and all parent cgroups have values set
  1291. // for the period and runtime as this limits what the children can be set to.
  1292. daemon.initCgroupsPath(filepath.Dir(path))
  1293. mnt, root, err := cgroups.FindCgroupMountpointAndRoot("cpu")
  1294. if err != nil {
  1295. return err
  1296. }
  1297. // When docker is run inside docker, the root is based of the host cgroup.
  1298. // Should this be handled in runc/libcontainer/cgroups ?
  1299. if strings.HasPrefix(root, "/docker/") {
  1300. root = "/"
  1301. }
  1302. path = filepath.Join(mnt, root, path)
  1303. sysinfo := sysinfo.New(true)
  1304. if err := maybeCreateCPURealTimeFile(sysinfo.CPURealtimePeriod, daemon.configStore.CPURealtimePeriod, "cpu.rt_period_us", path); err != nil {
  1305. return err
  1306. }
  1307. return maybeCreateCPURealTimeFile(sysinfo.CPURealtimeRuntime, daemon.configStore.CPURealtimeRuntime, "cpu.rt_runtime_us", path)
  1308. }
  1309. func maybeCreateCPURealTimeFile(sysinfoPresent bool, configValue int64, file string, path string) error {
  1310. if sysinfoPresent && configValue != 0 {
  1311. if err := os.MkdirAll(path, 0755); err != nil {
  1312. return err
  1313. }
  1314. if err := ioutil.WriteFile(filepath.Join(path, file), []byte(strconv.FormatInt(configValue, 10)), 0700); err != nil {
  1315. return err
  1316. }
  1317. }
  1318. return nil
  1319. }
  1320. func (daemon *Daemon) setupSeccompProfile() error {
  1321. if daemon.configStore.SeccompProfile != "" {
  1322. daemon.seccompProfilePath = daemon.configStore.SeccompProfile
  1323. b, err := ioutil.ReadFile(daemon.configStore.SeccompProfile)
  1324. if err != nil {
  1325. return fmt.Errorf("opening seccomp profile (%s) failed: %v", daemon.configStore.SeccompProfile, err)
  1326. }
  1327. daemon.seccompProfile = b
  1328. }
  1329. return nil
  1330. }