daemon_unix.go 41 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145
  1. // +build linux freebsd
  2. package daemon
  3. import (
  4. "fmt"
  5. "io/ioutil"
  6. "net"
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. "runtime/debug"
  11. "strconv"
  12. "strings"
  13. "syscall"
  14. "time"
  15. "github.com/Sirupsen/logrus"
  16. "github.com/docker/docker/container"
  17. "github.com/docker/docker/image"
  18. "github.com/docker/docker/layer"
  19. "github.com/docker/docker/pkg/idtools"
  20. "github.com/docker/docker/pkg/parsers"
  21. "github.com/docker/docker/pkg/parsers/kernel"
  22. "github.com/docker/docker/pkg/sysinfo"
  23. "github.com/docker/docker/reference"
  24. "github.com/docker/docker/runconfig"
  25. runconfigopts "github.com/docker/docker/runconfig/opts"
  26. "github.com/docker/engine-api/types"
  27. pblkiodev "github.com/docker/engine-api/types/blkiodev"
  28. containertypes "github.com/docker/engine-api/types/container"
  29. "github.com/docker/libnetwork"
  30. nwconfig "github.com/docker/libnetwork/config"
  31. "github.com/docker/libnetwork/drivers/bridge"
  32. "github.com/docker/libnetwork/ipamutils"
  33. "github.com/docker/libnetwork/netlabel"
  34. "github.com/docker/libnetwork/options"
  35. lntypes "github.com/docker/libnetwork/types"
  36. "github.com/opencontainers/runc/libcontainer/label"
  37. "github.com/opencontainers/runc/libcontainer/user"
  38. "github.com/opencontainers/specs/specs-go"
  39. )
  40. const (
  41. // See https://git.kernel.org/cgit/linux/kernel/git/tip/tip.git/tree/kernel/sched/sched.h?id=8cd9234c64c584432f6992fe944ca9e46ca8ea76#n269
  42. linuxMinCPUShares = 2
  43. linuxMaxCPUShares = 262144
  44. platformSupported = true
  45. // It's not kernel limit, we want this 4M limit to supply a reasonable functional container
  46. linuxMinMemory = 4194304
  47. // constants for remapped root settings
  48. defaultIDSpecifier string = "default"
  49. defaultRemappedID string = "dockremap"
  50. // constant for cgroup drivers
  51. cgroupFsDriver = "cgroupfs"
  52. cgroupSystemdDriver = "systemd"
  53. )
  54. func getMemoryResources(config containertypes.Resources) *specs.Memory {
  55. memory := specs.Memory{}
  56. if config.Memory > 0 {
  57. limit := uint64(config.Memory)
  58. memory.Limit = &limit
  59. }
  60. if config.MemoryReservation > 0 {
  61. reservation := uint64(config.MemoryReservation)
  62. memory.Reservation = &reservation
  63. }
  64. if config.MemorySwap != 0 {
  65. swap := uint64(config.MemorySwap)
  66. memory.Swap = &swap
  67. }
  68. if config.MemorySwappiness != nil {
  69. swappiness := uint64(*config.MemorySwappiness)
  70. memory.Swappiness = &swappiness
  71. }
  72. if config.KernelMemory != 0 {
  73. kernelMemory := uint64(config.KernelMemory)
  74. memory.Kernel = &kernelMemory
  75. }
  76. return &memory
  77. }
  78. func getCPUResources(config containertypes.Resources) *specs.CPU {
  79. cpu := specs.CPU{}
  80. if config.CPUShares != 0 {
  81. shares := uint64(config.CPUShares)
  82. cpu.Shares = &shares
  83. }
  84. if config.CpusetCpus != "" {
  85. cpuset := config.CpusetCpus
  86. cpu.Cpus = &cpuset
  87. }
  88. if config.CpusetMems != "" {
  89. cpuset := config.CpusetMems
  90. cpu.Mems = &cpuset
  91. }
  92. if config.CPUPeriod != 0 {
  93. period := uint64(config.CPUPeriod)
  94. cpu.Period = &period
  95. }
  96. if config.CPUQuota != 0 {
  97. quota := uint64(config.CPUQuota)
  98. cpu.Quota = &quota
  99. }
  100. return &cpu
  101. }
  102. func getBlkioWeightDevices(config containertypes.Resources) ([]specs.WeightDevice, error) {
  103. var stat syscall.Stat_t
  104. var blkioWeightDevices []specs.WeightDevice
  105. for _, weightDevice := range config.BlkioWeightDevice {
  106. if err := syscall.Stat(weightDevice.Path, &stat); err != nil {
  107. return nil, err
  108. }
  109. weight := weightDevice.Weight
  110. d := specs.WeightDevice{Weight: &weight}
  111. d.Major = int64(stat.Rdev / 256)
  112. d.Minor = int64(stat.Rdev % 256)
  113. blkioWeightDevices = append(blkioWeightDevices, d)
  114. }
  115. return blkioWeightDevices, nil
  116. }
  117. func parseSecurityOpt(container *container.Container, config *containertypes.HostConfig) error {
  118. var (
  119. labelOpts []string
  120. err error
  121. )
  122. for _, opt := range config.SecurityOpt {
  123. if opt == "no-new-privileges" {
  124. container.NoNewPrivileges = true
  125. } else {
  126. var con []string
  127. if strings.Contains(opt, "=") {
  128. con = strings.SplitN(opt, "=", 2)
  129. } else if strings.Contains(opt, ":") {
  130. con = strings.SplitN(opt, ":", 2)
  131. logrus.Warnf("Security options with `:` as a separator are deprecated and will be completely unsupported in 1.13, use `=` instead.")
  132. }
  133. if len(con) != 2 {
  134. return fmt.Errorf("Invalid --security-opt 1: %q", opt)
  135. }
  136. switch con[0] {
  137. case "label":
  138. labelOpts = append(labelOpts, con[1])
  139. case "apparmor":
  140. container.AppArmorProfile = con[1]
  141. case "seccomp":
  142. container.SeccompProfile = con[1]
  143. default:
  144. return fmt.Errorf("Invalid --security-opt 2: %q", opt)
  145. }
  146. }
  147. }
  148. container.ProcessLabel, container.MountLabel, err = label.InitLabels(labelOpts)
  149. return err
  150. }
  151. func getBlkioReadIOpsDevices(config containertypes.Resources) ([]specs.ThrottleDevice, error) {
  152. var blkioReadIOpsDevice []specs.ThrottleDevice
  153. var stat syscall.Stat_t
  154. for _, iopsDevice := range config.BlkioDeviceReadIOps {
  155. if err := syscall.Stat(iopsDevice.Path, &stat); err != nil {
  156. return nil, err
  157. }
  158. rate := iopsDevice.Rate
  159. d := specs.ThrottleDevice{Rate: &rate}
  160. d.Major = int64(stat.Rdev / 256)
  161. d.Minor = int64(stat.Rdev % 256)
  162. blkioReadIOpsDevice = append(blkioReadIOpsDevice, d)
  163. }
  164. return blkioReadIOpsDevice, nil
  165. }
  166. func getBlkioWriteIOpsDevices(config containertypes.Resources) ([]specs.ThrottleDevice, error) {
  167. var blkioWriteIOpsDevice []specs.ThrottleDevice
  168. var stat syscall.Stat_t
  169. for _, iopsDevice := range config.BlkioDeviceWriteIOps {
  170. if err := syscall.Stat(iopsDevice.Path, &stat); err != nil {
  171. return nil, err
  172. }
  173. rate := iopsDevice.Rate
  174. d := specs.ThrottleDevice{Rate: &rate}
  175. d.Major = int64(stat.Rdev / 256)
  176. d.Minor = int64(stat.Rdev % 256)
  177. blkioWriteIOpsDevice = append(blkioWriteIOpsDevice, d)
  178. }
  179. return blkioWriteIOpsDevice, nil
  180. }
  181. func getBlkioReadBpsDevices(config containertypes.Resources) ([]specs.ThrottleDevice, error) {
  182. var blkioReadBpsDevice []specs.ThrottleDevice
  183. var stat syscall.Stat_t
  184. for _, bpsDevice := range config.BlkioDeviceReadBps {
  185. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  186. return nil, err
  187. }
  188. rate := bpsDevice.Rate
  189. d := specs.ThrottleDevice{Rate: &rate}
  190. d.Major = int64(stat.Rdev / 256)
  191. d.Minor = int64(stat.Rdev % 256)
  192. blkioReadBpsDevice = append(blkioReadBpsDevice, d)
  193. }
  194. return blkioReadBpsDevice, nil
  195. }
  196. func getBlkioWriteBpsDevices(config containertypes.Resources) ([]specs.ThrottleDevice, error) {
  197. var blkioWriteBpsDevice []specs.ThrottleDevice
  198. var stat syscall.Stat_t
  199. for _, bpsDevice := range config.BlkioDeviceWriteBps {
  200. if err := syscall.Stat(bpsDevice.Path, &stat); err != nil {
  201. return nil, err
  202. }
  203. rate := bpsDevice.Rate
  204. d := specs.ThrottleDevice{Rate: &rate}
  205. d.Major = int64(stat.Rdev / 256)
  206. d.Minor = int64(stat.Rdev % 256)
  207. blkioWriteBpsDevice = append(blkioWriteBpsDevice, d)
  208. }
  209. return blkioWriteBpsDevice, nil
  210. }
  211. func checkKernelVersion(k, major, minor int) bool {
  212. if v, err := kernel.GetKernelVersion(); err != nil {
  213. logrus.Warnf("%s", err)
  214. } else {
  215. if kernel.CompareKernelVersion(*v, kernel.VersionInfo{Kernel: k, Major: major, Minor: minor}) < 0 {
  216. return false
  217. }
  218. }
  219. return true
  220. }
  221. func checkKernel() error {
  222. // Check for unsupported kernel versions
  223. // FIXME: it would be cleaner to not test for specific versions, but rather
  224. // test for specific functionalities.
  225. // Unfortunately we can't test for the feature "does not cause a kernel panic"
  226. // without actually causing a kernel panic, so we need this workaround until
  227. // the circumstances of pre-3.10 crashes are clearer.
  228. // For details see https://github.com/docker/docker/issues/407
  229. // Docker 1.11 and above doesn't actually run on kernels older than 3.4,
  230. // due to containerd-shim usage of PR_SET_CHILD_SUBREAPER (introduced in 3.4).
  231. if !checkKernelVersion(3, 10, 0) {
  232. v, _ := kernel.GetKernelVersion()
  233. if os.Getenv("DOCKER_NOWARN_KERNEL_VERSION") == "" {
  234. 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())
  235. }
  236. }
  237. return nil
  238. }
  239. // adaptContainerSettings is called during container creation to modify any
  240. // settings necessary in the HostConfig structure.
  241. func (daemon *Daemon) adaptContainerSettings(hostConfig *containertypes.HostConfig, adjustCPUShares bool) error {
  242. if adjustCPUShares && hostConfig.CPUShares > 0 {
  243. // Handle unsupported CPUShares
  244. if hostConfig.CPUShares < linuxMinCPUShares {
  245. logrus.Warnf("Changing requested CPUShares of %d to minimum allowed of %d", hostConfig.CPUShares, linuxMinCPUShares)
  246. hostConfig.CPUShares = linuxMinCPUShares
  247. } else if hostConfig.CPUShares > linuxMaxCPUShares {
  248. logrus.Warnf("Changing requested CPUShares of %d to maximum allowed of %d", hostConfig.CPUShares, linuxMaxCPUShares)
  249. hostConfig.CPUShares = linuxMaxCPUShares
  250. }
  251. }
  252. if hostConfig.Memory > 0 && hostConfig.MemorySwap == 0 {
  253. // By default, MemorySwap is set to twice the size of Memory.
  254. hostConfig.MemorySwap = hostConfig.Memory * 2
  255. }
  256. if hostConfig.ShmSize == 0 {
  257. hostConfig.ShmSize = container.DefaultSHMSize
  258. }
  259. var err error
  260. if hostConfig.SecurityOpt == nil {
  261. hostConfig.SecurityOpt, err = daemon.generateSecurityOpt(hostConfig.IpcMode, hostConfig.PidMode)
  262. if err != nil {
  263. return err
  264. }
  265. }
  266. if hostConfig.MemorySwappiness == nil {
  267. defaultSwappiness := int64(-1)
  268. hostConfig.MemorySwappiness = &defaultSwappiness
  269. }
  270. if hostConfig.OomKillDisable == nil {
  271. defaultOomKillDisable := false
  272. hostConfig.OomKillDisable = &defaultOomKillDisable
  273. }
  274. return nil
  275. }
  276. func verifyContainerResources(resources *containertypes.Resources, sysInfo *sysinfo.SysInfo, update bool) ([]string, error) {
  277. warnings := []string{}
  278. // memory subsystem checks and adjustments
  279. if resources.Memory != 0 && resources.Memory < linuxMinMemory {
  280. return warnings, fmt.Errorf("Minimum memory limit allowed is 4MB")
  281. }
  282. if resources.Memory > 0 && !sysInfo.MemoryLimit {
  283. warnings = append(warnings, "Your kernel does not support memory limit capabilities. Limitation discarded.")
  284. logrus.Warnf("Your kernel does not support memory limit capabilities. Limitation discarded.")
  285. resources.Memory = 0
  286. resources.MemorySwap = -1
  287. }
  288. if resources.Memory > 0 && resources.MemorySwap != -1 && !sysInfo.SwapLimit {
  289. warnings = append(warnings, "Your kernel does not support swap limit capabilities, memory limited without swap.")
  290. logrus.Warnf("Your kernel does not support swap limit capabilities, memory limited without swap.")
  291. resources.MemorySwap = -1
  292. }
  293. if resources.Memory > 0 && resources.MemorySwap > 0 && resources.MemorySwap < resources.Memory {
  294. return warnings, fmt.Errorf("Minimum memoryswap limit should be larger than memory limit, see usage")
  295. }
  296. if resources.Memory == 0 && resources.MemorySwap > 0 && !update {
  297. return warnings, fmt.Errorf("You should always set the Memory limit when using Memoryswap limit, see usage")
  298. }
  299. if resources.MemorySwappiness != nil && *resources.MemorySwappiness != -1 && !sysInfo.MemorySwappiness {
  300. warnings = append(warnings, "Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  301. logrus.Warnf("Your kernel does not support memory swappiness capabilities, memory swappiness discarded.")
  302. resources.MemorySwappiness = nil
  303. }
  304. if resources.MemorySwappiness != nil {
  305. swappiness := *resources.MemorySwappiness
  306. if swappiness < -1 || swappiness > 100 {
  307. return warnings, fmt.Errorf("Invalid value: %v, valid memory swappiness range is 0-100", swappiness)
  308. }
  309. }
  310. if resources.MemoryReservation > 0 && !sysInfo.MemoryReservation {
  311. warnings = append(warnings, "Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  312. logrus.Warnf("Your kernel does not support memory soft limit capabilities. Limitation discarded.")
  313. resources.MemoryReservation = 0
  314. }
  315. if resources.MemoryReservation > 0 && resources.MemoryReservation < linuxMinMemory {
  316. return warnings, fmt.Errorf("Minimum memory reservation allowed is 4MB")
  317. }
  318. if resources.Memory > 0 && resources.MemoryReservation > 0 && resources.Memory < resources.MemoryReservation {
  319. return warnings, fmt.Errorf("Minimum memory limit should be larger than memory reservation limit, see usage")
  320. }
  321. if resources.KernelMemory > 0 && !sysInfo.KernelMemory {
  322. warnings = append(warnings, "Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  323. logrus.Warnf("Your kernel does not support kernel memory limit capabilities. Limitation discarded.")
  324. resources.KernelMemory = 0
  325. }
  326. if resources.KernelMemory > 0 && resources.KernelMemory < linuxMinMemory {
  327. return warnings, fmt.Errorf("Minimum kernel memory limit allowed is 4MB")
  328. }
  329. if resources.KernelMemory > 0 && !checkKernelVersion(4, 0, 0) {
  330. 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.")
  331. logrus.Warnf("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.")
  332. }
  333. if resources.OomKillDisable != nil && !sysInfo.OomKillDisable {
  334. // only produce warnings if the setting wasn't to *disable* the OOM Kill; no point
  335. // warning the caller if they already wanted the feature to be off
  336. if *resources.OomKillDisable {
  337. warnings = append(warnings, "Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  338. logrus.Warnf("Your kernel does not support OomKillDisable, OomKillDisable discarded.")
  339. }
  340. resources.OomKillDisable = nil
  341. }
  342. if resources.PidsLimit != 0 && !sysInfo.PidsLimit {
  343. warnings = append(warnings, "Your kernel does not support pids limit capabilities, pids limit discarded.")
  344. logrus.Warnf("Your kernel does not support pids limit capabilities, pids limit discarded.")
  345. resources.PidsLimit = 0
  346. }
  347. // cpu subsystem checks and adjustments
  348. if resources.CPUShares > 0 && !sysInfo.CPUShares {
  349. warnings = append(warnings, "Your kernel does not support CPU shares. Shares discarded.")
  350. logrus.Warnf("Your kernel does not support CPU shares. Shares discarded.")
  351. resources.CPUShares = 0
  352. }
  353. if resources.CPUPeriod > 0 && !sysInfo.CPUCfsPeriod {
  354. warnings = append(warnings, "Your kernel does not support CPU cfs period. Period discarded.")
  355. logrus.Warnf("Your kernel does not support CPU cfs period. Period discarded.")
  356. resources.CPUPeriod = 0
  357. }
  358. if resources.CPUPeriod != 0 && (resources.CPUPeriod < 1000 || resources.CPUPeriod > 1000000) {
  359. return warnings, fmt.Errorf("CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)")
  360. }
  361. if resources.CPUQuota > 0 && !sysInfo.CPUCfsQuota {
  362. warnings = append(warnings, "Your kernel does not support CPU cfs quota. Quota discarded.")
  363. logrus.Warnf("Your kernel does not support CPU cfs quota. Quota discarded.")
  364. resources.CPUQuota = 0
  365. }
  366. if resources.CPUQuota > 0 && resources.CPUQuota < 1000 {
  367. return warnings, fmt.Errorf("CPU cfs quota can not be less than 1ms (i.e. 1000)")
  368. }
  369. if resources.CPUPercent > 0 {
  370. warnings = append(warnings, "%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  371. logrus.Warnf("%s does not support CPU percent. Percent discarded.", runtime.GOOS)
  372. resources.CPUPercent = 0
  373. }
  374. // cpuset subsystem checks and adjustments
  375. if (resources.CpusetCpus != "" || resources.CpusetMems != "") && !sysInfo.Cpuset {
  376. warnings = append(warnings, "Your kernel does not support cpuset. Cpuset discarded.")
  377. logrus.Warnf("Your kernel does not support cpuset. Cpuset discarded.")
  378. resources.CpusetCpus = ""
  379. resources.CpusetMems = ""
  380. }
  381. cpusAvailable, err := sysInfo.IsCpusetCpusAvailable(resources.CpusetCpus)
  382. if err != nil {
  383. return warnings, fmt.Errorf("Invalid value %s for cpuset cpus", resources.CpusetCpus)
  384. }
  385. if !cpusAvailable {
  386. return warnings, fmt.Errorf("Requested CPUs are not available - requested %s, available: %s", resources.CpusetCpus, sysInfo.Cpus)
  387. }
  388. memsAvailable, err := sysInfo.IsCpusetMemsAvailable(resources.CpusetMems)
  389. if err != nil {
  390. return warnings, fmt.Errorf("Invalid value %s for cpuset mems", resources.CpusetMems)
  391. }
  392. if !memsAvailable {
  393. return warnings, fmt.Errorf("Requested memory nodes are not available - requested %s, available: %s", resources.CpusetMems, sysInfo.Mems)
  394. }
  395. // blkio subsystem checks and adjustments
  396. if resources.BlkioWeight > 0 && !sysInfo.BlkioWeight {
  397. warnings = append(warnings, "Your kernel does not support Block I/O weight. Weight discarded.")
  398. logrus.Warnf("Your kernel does not support Block I/O weight. Weight discarded.")
  399. resources.BlkioWeight = 0
  400. }
  401. if resources.BlkioWeight > 0 && (resources.BlkioWeight < 10 || resources.BlkioWeight > 1000) {
  402. return warnings, fmt.Errorf("Range of blkio weight is from 10 to 1000")
  403. }
  404. if resources.IOMaximumBandwidth != 0 || resources.IOMaximumIOps != 0 {
  405. return warnings, fmt.Errorf("Invalid QoS settings: %s does not support Maximum IO Bandwidth or Maximum IO IOps", runtime.GOOS)
  406. }
  407. if len(resources.BlkioWeightDevice) > 0 && !sysInfo.BlkioWeightDevice {
  408. warnings = append(warnings, "Your kernel does not support Block I/O weight_device.")
  409. logrus.Warnf("Your kernel does not support Block I/O weight_device. Weight-device discarded.")
  410. resources.BlkioWeightDevice = []*pblkiodev.WeightDevice{}
  411. }
  412. if len(resources.BlkioDeviceReadBps) > 0 && !sysInfo.BlkioReadBpsDevice {
  413. warnings = append(warnings, "Your kernel does not support Block read limit in bytes per second.")
  414. logrus.Warnf("Your kernel does not support Block I/O read limit in bytes per second. --device-read-bps discarded.")
  415. resources.BlkioDeviceReadBps = []*pblkiodev.ThrottleDevice{}
  416. }
  417. if len(resources.BlkioDeviceWriteBps) > 0 && !sysInfo.BlkioWriteBpsDevice {
  418. warnings = append(warnings, "Your kernel does not support Block write limit in bytes per second.")
  419. logrus.Warnf("Your kernel does not support Block I/O write limit in bytes per second. --device-write-bps discarded.")
  420. resources.BlkioDeviceWriteBps = []*pblkiodev.ThrottleDevice{}
  421. }
  422. if len(resources.BlkioDeviceReadIOps) > 0 && !sysInfo.BlkioReadIOpsDevice {
  423. warnings = append(warnings, "Your kernel does not support Block read limit in IO per second.")
  424. logrus.Warnf("Your kernel does not support Block I/O read limit in IO per second. -device-read-iops discarded.")
  425. resources.BlkioDeviceReadIOps = []*pblkiodev.ThrottleDevice{}
  426. }
  427. if len(resources.BlkioDeviceWriteIOps) > 0 && !sysInfo.BlkioWriteIOpsDevice {
  428. warnings = append(warnings, "Your kernel does not support Block write limit in IO per second.")
  429. logrus.Warnf("Your kernel does not support Block I/O write limit in IO per second. --device-write-iops discarded.")
  430. resources.BlkioDeviceWriteIOps = []*pblkiodev.ThrottleDevice{}
  431. }
  432. return warnings, nil
  433. }
  434. func (daemon *Daemon) getCgroupDriver() string {
  435. cgroupDriver := cgroupFsDriver
  436. if UsingSystemd(daemon.configStore) {
  437. cgroupDriver = cgroupSystemdDriver
  438. }
  439. return cgroupDriver
  440. }
  441. // getCD gets the raw value of the native.cgroupdriver option, if set.
  442. func getCD(config *Config) string {
  443. for _, option := range config.ExecOptions {
  444. key, val, err := parsers.ParseKeyValueOpt(option)
  445. if err != nil || !strings.EqualFold(key, "native.cgroupdriver") {
  446. continue
  447. }
  448. return val
  449. }
  450. return ""
  451. }
  452. // VerifyCgroupDriver validates native.cgroupdriver
  453. func VerifyCgroupDriver(config *Config) error {
  454. cd := getCD(config)
  455. if cd == "" || cd == cgroupFsDriver || cd == cgroupSystemdDriver {
  456. return nil
  457. }
  458. return fmt.Errorf("native.cgroupdriver option %s not supported", cd)
  459. }
  460. // UsingSystemd returns true if cli option includes native.cgroupdriver=systemd
  461. func UsingSystemd(config *Config) bool {
  462. return getCD(config) == cgroupSystemdDriver
  463. }
  464. // verifyPlatformContainerSettings performs platform-specific validation of the
  465. // hostconfig and config structures.
  466. func verifyPlatformContainerSettings(daemon *Daemon, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  467. warnings := []string{}
  468. sysInfo := sysinfo.New(true)
  469. warnings, err := daemon.verifyExperimentalContainerSettings(hostConfig, config)
  470. if err != nil {
  471. return warnings, err
  472. }
  473. w, err := verifyContainerResources(&hostConfig.Resources, sysInfo, update)
  474. if err != nil {
  475. return warnings, err
  476. }
  477. warnings = append(warnings, w...)
  478. if hostConfig.ShmSize < 0 {
  479. return warnings, fmt.Errorf("SHM size must be greater than 0")
  480. }
  481. if hostConfig.OomScoreAdj < -1000 || hostConfig.OomScoreAdj > 1000 {
  482. return warnings, fmt.Errorf("Invalid value %d, range for oom score adj is [-1000, 1000]", hostConfig.OomScoreAdj)
  483. }
  484. if sysInfo.IPv4ForwardingDisabled {
  485. warnings = append(warnings, "IPv4 forwarding is disabled. Networking will not work.")
  486. logrus.Warnf("IPv4 forwarding is disabled. Networking will not work")
  487. }
  488. // check for various conflicting options with user namespaces
  489. if daemon.configStore.RemappedRoot != "" && hostConfig.UsernsMode.IsPrivate() {
  490. if hostConfig.Privileged {
  491. return warnings, fmt.Errorf("Privileged mode is incompatible with user namespaces")
  492. }
  493. if hostConfig.NetworkMode.IsHost() {
  494. return warnings, fmt.Errorf("Cannot share the host's network namespace when user namespaces are enabled")
  495. }
  496. if hostConfig.PidMode.IsHost() {
  497. return warnings, fmt.Errorf("Cannot share the host PID namespace when user namespaces are enabled")
  498. }
  499. if hostConfig.ReadonlyRootfs {
  500. return warnings, fmt.Errorf("Cannot use the --read-only option when user namespaces are enabled")
  501. }
  502. }
  503. if hostConfig.CgroupParent != "" && UsingSystemd(daemon.configStore) {
  504. // CgroupParent for systemd cgroup should be named as "xxx.slice"
  505. if len(hostConfig.CgroupParent) <= 6 || !strings.HasSuffix(hostConfig.CgroupParent, ".slice") {
  506. return warnings, fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  507. }
  508. }
  509. return warnings, nil
  510. }
  511. // verifyDaemonSettings performs validation of daemon config struct
  512. func verifyDaemonSettings(config *Config) error {
  513. // Check for mutually incompatible config options
  514. if config.bridgeConfig.Iface != "" && config.bridgeConfig.IP != "" {
  515. return fmt.Errorf("You specified -b & --bip, mutually exclusive options. Please specify only one")
  516. }
  517. if !config.bridgeConfig.EnableIPTables && !config.bridgeConfig.InterContainerCommunication {
  518. return fmt.Errorf("You specified --iptables=false with --icc=false. ICC=false uses iptables to function. Please set --icc or --iptables to true")
  519. }
  520. if !config.bridgeConfig.EnableIPTables && config.bridgeConfig.EnableIPMasq {
  521. config.bridgeConfig.EnableIPMasq = false
  522. }
  523. if err := VerifyCgroupDriver(config); err != nil {
  524. return err
  525. }
  526. if config.CgroupParent != "" && UsingSystemd(config) {
  527. if len(config.CgroupParent) <= 6 || !strings.HasSuffix(config.CgroupParent, ".slice") {
  528. return fmt.Errorf("cgroup-parent for systemd cgroup should be a valid slice named as \"xxx.slice\"")
  529. }
  530. }
  531. return nil
  532. }
  533. // checkSystem validates platform-specific requirements
  534. func checkSystem() error {
  535. if os.Geteuid() != 0 {
  536. return fmt.Errorf("The Docker daemon needs to be run as root")
  537. }
  538. return checkKernel()
  539. }
  540. // configureMaxThreads sets the Go runtime max threads threshold
  541. // which is 90% of the kernel setting from /proc/sys/kernel/threads-max
  542. func configureMaxThreads(config *Config) error {
  543. mt, err := ioutil.ReadFile("/proc/sys/kernel/threads-max")
  544. if err != nil {
  545. return err
  546. }
  547. mtint, err := strconv.Atoi(strings.TrimSpace(string(mt)))
  548. if err != nil {
  549. return err
  550. }
  551. maxThreads := (mtint / 100) * 90
  552. debug.SetMaxThreads(maxThreads)
  553. logrus.Debugf("Golang's threads limit set to %d", maxThreads)
  554. return nil
  555. }
  556. // configureKernelSecuritySupport configures and validates security support for the kernel
  557. func configureKernelSecuritySupport(config *Config, driverName string) error {
  558. if config.EnableSelinuxSupport {
  559. if selinuxEnabled() {
  560. // As Docker on overlayFS and SELinux are incompatible at present, error on overlayfs being enabled
  561. if driverName == "overlay" {
  562. return fmt.Errorf("SELinux is not supported with the %s graph driver", driverName)
  563. }
  564. logrus.Debug("SELinux enabled successfully")
  565. } else {
  566. logrus.Warn("Docker could not enable SELinux on the host system")
  567. }
  568. } else {
  569. selinuxSetDisabled()
  570. }
  571. return nil
  572. }
  573. func (daemon *Daemon) initNetworkController(config *Config) (libnetwork.NetworkController, error) {
  574. netOptions, err := daemon.networkOptions(config)
  575. if err != nil {
  576. return nil, err
  577. }
  578. controller, err := libnetwork.New(netOptions...)
  579. if err != nil {
  580. return nil, fmt.Errorf("error obtaining controller instance: %v", err)
  581. }
  582. // Initialize default network on "null"
  583. if _, err := controller.NewNetwork("null", "none", libnetwork.NetworkOptionPersist(false)); err != nil {
  584. return nil, fmt.Errorf("Error creating default \"null\" network: %v", err)
  585. }
  586. // Initialize default network on "host"
  587. if _, err := controller.NewNetwork("host", "host", libnetwork.NetworkOptionPersist(false)); err != nil {
  588. return nil, fmt.Errorf("Error creating default \"host\" network: %v", err)
  589. }
  590. if !config.DisableBridge {
  591. // Initialize default driver "bridge"
  592. if err := initBridgeDriver(controller, config); err != nil {
  593. return nil, err
  594. }
  595. }
  596. return controller, nil
  597. }
  598. func driverOptions(config *Config) []nwconfig.Option {
  599. bridgeConfig := options.Generic{
  600. "EnableIPForwarding": config.bridgeConfig.EnableIPForward,
  601. "EnableIPTables": config.bridgeConfig.EnableIPTables,
  602. "EnableUserlandProxy": config.bridgeConfig.EnableUserlandProxy}
  603. bridgeOption := options.Generic{netlabel.GenericData: bridgeConfig}
  604. dOptions := []nwconfig.Option{}
  605. dOptions = append(dOptions, nwconfig.OptionDriverConfig("bridge", bridgeOption))
  606. return dOptions
  607. }
  608. func initBridgeDriver(controller libnetwork.NetworkController, config *Config) error {
  609. if n, err := controller.NetworkByName("bridge"); err == nil {
  610. if err = n.Delete(); err != nil {
  611. return fmt.Errorf("could not delete the default bridge network: %v", err)
  612. }
  613. }
  614. bridgeName := bridge.DefaultBridgeName
  615. if config.bridgeConfig.Iface != "" {
  616. bridgeName = config.bridgeConfig.Iface
  617. }
  618. netOption := map[string]string{
  619. bridge.BridgeName: bridgeName,
  620. bridge.DefaultBridge: strconv.FormatBool(true),
  621. netlabel.DriverMTU: strconv.Itoa(config.Mtu),
  622. bridge.EnableIPMasquerade: strconv.FormatBool(config.bridgeConfig.EnableIPMasq),
  623. bridge.EnableICC: strconv.FormatBool(config.bridgeConfig.InterContainerCommunication),
  624. }
  625. // --ip processing
  626. if config.bridgeConfig.DefaultIP != nil {
  627. netOption[bridge.DefaultBindingIP] = config.bridgeConfig.DefaultIP.String()
  628. }
  629. var (
  630. ipamV4Conf *libnetwork.IpamConf
  631. ipamV6Conf *libnetwork.IpamConf
  632. )
  633. ipamV4Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  634. nw, nw6List, err := ipamutils.ElectInterfaceAddresses(bridgeName)
  635. if err == nil {
  636. ipamV4Conf.PreferredPool = lntypes.GetIPNetCanonical(nw).String()
  637. hip, _ := lntypes.GetHostPartIP(nw.IP, nw.Mask)
  638. if hip.IsGlobalUnicast() {
  639. ipamV4Conf.Gateway = nw.IP.String()
  640. }
  641. }
  642. if config.bridgeConfig.IP != "" {
  643. ipamV4Conf.PreferredPool = config.bridgeConfig.IP
  644. ip, _, err := net.ParseCIDR(config.bridgeConfig.IP)
  645. if err != nil {
  646. return err
  647. }
  648. ipamV4Conf.Gateway = ip.String()
  649. } else if bridgeName == bridge.DefaultBridgeName && ipamV4Conf.PreferredPool != "" {
  650. 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)
  651. }
  652. if config.bridgeConfig.FixedCIDR != "" {
  653. _, fCIDR, err := net.ParseCIDR(config.bridgeConfig.FixedCIDR)
  654. if err != nil {
  655. return err
  656. }
  657. ipamV4Conf.SubPool = fCIDR.String()
  658. }
  659. if config.bridgeConfig.DefaultGatewayIPv4 != nil {
  660. ipamV4Conf.AuxAddresses["DefaultGatewayIPv4"] = config.bridgeConfig.DefaultGatewayIPv4.String()
  661. }
  662. var deferIPv6Alloc bool
  663. if config.bridgeConfig.FixedCIDRv6 != "" {
  664. _, fCIDRv6, err := net.ParseCIDR(config.bridgeConfig.FixedCIDRv6)
  665. if err != nil {
  666. return err
  667. }
  668. // In case user has specified the daemon flag --fixed-cidr-v6 and the passed network has
  669. // at least 48 host bits, we need to guarantee the current behavior where the containers'
  670. // IPv6 addresses will be constructed based on the containers' interface MAC address.
  671. // We do so by telling libnetwork to defer the IPv6 address allocation for the endpoints
  672. // on this network until after the driver has created the endpoint and returned the
  673. // constructed address. Libnetwork will then reserve this address with the ipam driver.
  674. ones, _ := fCIDRv6.Mask.Size()
  675. deferIPv6Alloc = ones <= 80
  676. if ipamV6Conf == nil {
  677. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  678. }
  679. ipamV6Conf.PreferredPool = fCIDRv6.String()
  680. // In case the --fixed-cidr-v6 is specified and the current docker0 bridge IPv6
  681. // address belongs to the same network, we need to inform libnetwork about it, so
  682. // that it can be reserved with IPAM and it will not be given away to somebody else
  683. for _, nw6 := range nw6List {
  684. if fCIDRv6.Contains(nw6.IP) {
  685. ipamV6Conf.Gateway = nw6.IP.String()
  686. break
  687. }
  688. }
  689. }
  690. if config.bridgeConfig.DefaultGatewayIPv6 != nil {
  691. if ipamV6Conf == nil {
  692. ipamV6Conf = &libnetwork.IpamConf{AuxAddresses: make(map[string]string)}
  693. }
  694. ipamV6Conf.AuxAddresses["DefaultGatewayIPv6"] = config.bridgeConfig.DefaultGatewayIPv6.String()
  695. }
  696. v4Conf := []*libnetwork.IpamConf{ipamV4Conf}
  697. v6Conf := []*libnetwork.IpamConf{}
  698. if ipamV6Conf != nil {
  699. v6Conf = append(v6Conf, ipamV6Conf)
  700. }
  701. // Initialize default network on "bridge" with the same name
  702. _, err = controller.NewNetwork("bridge", "bridge",
  703. libnetwork.NetworkOptionEnableIPv6(config.bridgeConfig.EnableIPv6),
  704. libnetwork.NetworkOptionDriverOpts(netOption),
  705. libnetwork.NetworkOptionIpam("default", "", v4Conf, v6Conf, nil),
  706. libnetwork.NetworkOptionDeferIPv6Alloc(deferIPv6Alloc))
  707. if err != nil {
  708. return fmt.Errorf("Error creating default \"bridge\" network: %v", err)
  709. }
  710. return nil
  711. }
  712. // setupInitLayer populates a directory with mountpoints suitable
  713. // for bind-mounting things into the container.
  714. //
  715. // This extra layer is used by all containers as the top-most ro layer. It protects
  716. // the container from unwanted side-effects on the rw layer.
  717. func setupInitLayer(initLayer string, rootUID, rootGID int) error {
  718. for pth, typ := range map[string]string{
  719. "/dev/pts": "dir",
  720. "/dev/shm": "dir",
  721. "/proc": "dir",
  722. "/sys": "dir",
  723. "/.dockerenv": "file",
  724. "/etc/resolv.conf": "file",
  725. "/etc/hosts": "file",
  726. "/etc/hostname": "file",
  727. "/dev/console": "file",
  728. "/etc/mtab": "/proc/mounts",
  729. } {
  730. parts := strings.Split(pth, "/")
  731. prev := "/"
  732. for _, p := range parts[1:] {
  733. prev = filepath.Join(prev, p)
  734. syscall.Unlink(filepath.Join(initLayer, prev))
  735. }
  736. if _, err := os.Stat(filepath.Join(initLayer, pth)); err != nil {
  737. if os.IsNotExist(err) {
  738. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, filepath.Dir(pth)), 0755, rootUID, rootGID); err != nil {
  739. return err
  740. }
  741. switch typ {
  742. case "dir":
  743. if err := idtools.MkdirAllNewAs(filepath.Join(initLayer, pth), 0755, rootUID, rootGID); err != nil {
  744. return err
  745. }
  746. case "file":
  747. f, err := os.OpenFile(filepath.Join(initLayer, pth), os.O_CREATE, 0755)
  748. if err != nil {
  749. return err
  750. }
  751. f.Chown(rootUID, rootGID)
  752. f.Close()
  753. default:
  754. if err := os.Symlink(typ, filepath.Join(initLayer, pth)); err != nil {
  755. return err
  756. }
  757. }
  758. } else {
  759. return err
  760. }
  761. }
  762. }
  763. // Layer is ready to use, if it wasn't before.
  764. return nil
  765. }
  766. // Parse the remapped root (user namespace) option, which can be one of:
  767. // username - valid username from /etc/passwd
  768. // username:groupname - valid username; valid groupname from /etc/group
  769. // uid - 32-bit unsigned int valid Linux UID value
  770. // uid:gid - uid value; 32-bit unsigned int Linux GID value
  771. //
  772. // If no groupname is specified, and a username is specified, an attempt
  773. // will be made to lookup a gid for that username as a groupname
  774. //
  775. // If names are used, they are verified to exist in passwd/group
  776. func parseRemappedRoot(usergrp string) (string, string, error) {
  777. var (
  778. userID, groupID int
  779. username, groupname string
  780. )
  781. idparts := strings.Split(usergrp, ":")
  782. if len(idparts) > 2 {
  783. return "", "", fmt.Errorf("Invalid user/group specification in --userns-remap: %q", usergrp)
  784. }
  785. if uid, err := strconv.ParseInt(idparts[0], 10, 32); err == nil {
  786. // must be a uid; take it as valid
  787. userID = int(uid)
  788. luser, err := user.LookupUid(userID)
  789. if err != nil {
  790. return "", "", fmt.Errorf("Uid %d has no entry in /etc/passwd: %v", userID, err)
  791. }
  792. username = luser.Name
  793. if len(idparts) == 1 {
  794. // if the uid was numeric and no gid was specified, take the uid as the gid
  795. groupID = userID
  796. lgrp, err := user.LookupGid(groupID)
  797. if err != nil {
  798. return "", "", fmt.Errorf("Gid %d has no entry in /etc/group: %v", groupID, err)
  799. }
  800. groupname = lgrp.Name
  801. }
  802. } else {
  803. lookupName := idparts[0]
  804. // special case: if the user specified "default", they want Docker to create or
  805. // use (after creation) the "dockremap" user/group for root remapping
  806. if lookupName == defaultIDSpecifier {
  807. lookupName = defaultRemappedID
  808. }
  809. luser, err := user.LookupUser(lookupName)
  810. if err != nil && idparts[0] != defaultIDSpecifier {
  811. // error if the name requested isn't the special "dockremap" ID
  812. return "", "", fmt.Errorf("Error during uid lookup for %q: %v", lookupName, err)
  813. } else if err != nil {
  814. // special case-- if the username == "default", then we have been asked
  815. // to create a new entry pair in /etc/{passwd,group} for which the /etc/sub{uid,gid}
  816. // ranges will be used for the user and group mappings in user namespaced containers
  817. _, _, err := idtools.AddNamespaceRangesUser(defaultRemappedID)
  818. if err == nil {
  819. return defaultRemappedID, defaultRemappedID, nil
  820. }
  821. return "", "", fmt.Errorf("Error during %q user creation: %v", defaultRemappedID, err)
  822. }
  823. username = luser.Name
  824. if len(idparts) == 1 {
  825. // we only have a string username, and no group specified; look up gid from username as group
  826. group, err := user.LookupGroup(lookupName)
  827. if err != nil {
  828. return "", "", fmt.Errorf("Error during gid lookup for %q: %v", lookupName, err)
  829. }
  830. groupID = group.Gid
  831. groupname = group.Name
  832. }
  833. }
  834. if len(idparts) == 2 {
  835. // groupname or gid is separately specified and must be resolved
  836. // to an unsigned 32-bit gid
  837. if gid, err := strconv.ParseInt(idparts[1], 10, 32); err == nil {
  838. // must be a gid, take it as valid
  839. groupID = int(gid)
  840. lgrp, err := user.LookupGid(groupID)
  841. if err != nil {
  842. return "", "", fmt.Errorf("Gid %d has no entry in /etc/passwd: %v", groupID, err)
  843. }
  844. groupname = lgrp.Name
  845. } else {
  846. // not a number; attempt a lookup
  847. if _, err := user.LookupGroup(idparts[1]); err != nil {
  848. return "", "", fmt.Errorf("Error during groupname lookup for %q: %v", idparts[1], err)
  849. }
  850. groupname = idparts[1]
  851. }
  852. }
  853. return username, groupname, nil
  854. }
  855. func setupRemappedRoot(config *Config) ([]idtools.IDMap, []idtools.IDMap, error) {
  856. if runtime.GOOS != "linux" && config.RemappedRoot != "" {
  857. return nil, nil, fmt.Errorf("User namespaces are only supported on Linux")
  858. }
  859. // if the daemon was started with remapped root option, parse
  860. // the config option to the int uid,gid values
  861. var (
  862. uidMaps, gidMaps []idtools.IDMap
  863. )
  864. if config.RemappedRoot != "" {
  865. username, groupname, err := parseRemappedRoot(config.RemappedRoot)
  866. if err != nil {
  867. return nil, nil, err
  868. }
  869. if username == "root" {
  870. // Cannot setup user namespaces with a 1-to-1 mapping; "--root=0:0" is a no-op
  871. // effectively
  872. logrus.Warnf("User namespaces: root cannot be remapped with itself; user namespaces are OFF")
  873. return uidMaps, gidMaps, nil
  874. }
  875. logrus.Infof("User namespaces: ID ranges will be mapped to subuid/subgid ranges of: %s:%s", username, groupname)
  876. // update remapped root setting now that we have resolved them to actual names
  877. config.RemappedRoot = fmt.Sprintf("%s:%s", username, groupname)
  878. uidMaps, gidMaps, err = idtools.CreateIDMappings(username, groupname)
  879. if err != nil {
  880. return nil, nil, fmt.Errorf("Can't create ID mappings: %v", err)
  881. }
  882. }
  883. return uidMaps, gidMaps, nil
  884. }
  885. func setupDaemonRoot(config *Config, rootDir string, rootUID, rootGID int) error {
  886. config.Root = rootDir
  887. // the docker root metadata directory needs to have execute permissions for all users (g+x,o+x)
  888. // so that syscalls executing as non-root, operating on subdirectories of the graph root
  889. // (e.g. mounted layers of a container) can traverse this path.
  890. // The user namespace support will create subdirectories for the remapped root host uid:gid
  891. // pair owned by that same uid:gid pair for proper write access to those needed metadata and
  892. // layer content subtrees.
  893. if _, err := os.Stat(rootDir); err == nil {
  894. // root current exists; verify the access bits are correct by setting them
  895. if err = os.Chmod(rootDir, 0711); err != nil {
  896. return err
  897. }
  898. } else if os.IsNotExist(err) {
  899. // no root exists yet, create it 0711 with root:root ownership
  900. if err := os.MkdirAll(rootDir, 0711); err != nil {
  901. return err
  902. }
  903. }
  904. // if user namespaces are enabled we will create a subtree underneath the specified root
  905. // with any/all specified remapped root uid/gid options on the daemon creating
  906. // a new subdirectory with ownership set to the remapped uid/gid (so as to allow
  907. // `chdir()` to work for containers namespaced to that uid/gid)
  908. if config.RemappedRoot != "" {
  909. config.Root = filepath.Join(rootDir, fmt.Sprintf("%d.%d", rootUID, rootGID))
  910. logrus.Debugf("Creating user namespaced daemon root: %s", config.Root)
  911. // Create the root directory if it doesn't exist
  912. if err := idtools.MkdirAllAs(config.Root, 0700, rootUID, rootGID); err != nil {
  913. return fmt.Errorf("Cannot create daemon root: %s: %v", config.Root, err)
  914. }
  915. }
  916. return nil
  917. }
  918. // registerLinks writes the links to a file.
  919. func (daemon *Daemon) registerLinks(container *container.Container, hostConfig *containertypes.HostConfig) error {
  920. if hostConfig == nil || hostConfig.NetworkMode.IsUserDefined() {
  921. return nil
  922. }
  923. for _, l := range hostConfig.Links {
  924. name, alias, err := runconfigopts.ParseLink(l)
  925. if err != nil {
  926. return err
  927. }
  928. child, err := daemon.GetContainer(name)
  929. if err != nil {
  930. //An error from daemon.GetContainer() means this name could not be found
  931. return fmt.Errorf("Could not get container for %s", name)
  932. }
  933. for child.HostConfig.NetworkMode.IsContainer() {
  934. parts := strings.SplitN(string(child.HostConfig.NetworkMode), ":", 2)
  935. child, err = daemon.GetContainer(parts[1])
  936. if err != nil {
  937. return fmt.Errorf("Could not get container for %s", parts[1])
  938. }
  939. }
  940. if child.HostConfig.NetworkMode.IsHost() {
  941. return runconfig.ErrConflictHostNetworkAndLinks
  942. }
  943. if err := daemon.registerLink(container, child, alias); err != nil {
  944. return err
  945. }
  946. }
  947. // After we load all the links into the daemon
  948. // set them to nil on the hostconfig
  949. return container.WriteHostConfig()
  950. }
  951. // conditionalMountOnStart is a platform specific helper function during the
  952. // container start to call mount.
  953. func (daemon *Daemon) conditionalMountOnStart(container *container.Container) error {
  954. return daemon.Mount(container)
  955. }
  956. // conditionalUnmountOnCleanup is a platform specific helper function called
  957. // during the cleanup of a container to unmount.
  958. func (daemon *Daemon) conditionalUnmountOnCleanup(container *container.Container) error {
  959. return daemon.Unmount(container)
  960. }
  961. func restoreCustomImage(is image.Store, ls layer.Store, rs reference.Store) error {
  962. // Unix has no custom images to register
  963. return nil
  964. }
  965. func (daemon *Daemon) stats(c *container.Container) (*types.StatsJSON, error) {
  966. if !c.IsRunning() {
  967. return nil, errNotRunning{c.ID}
  968. }
  969. stats, err := daemon.containerd.Stats(c.ID)
  970. if err != nil {
  971. return nil, err
  972. }
  973. s := &types.StatsJSON{}
  974. cgs := stats.CgroupStats
  975. if cgs != nil {
  976. s.BlkioStats = types.BlkioStats{
  977. IoServiceBytesRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceBytesRecursive),
  978. IoServicedRecursive: copyBlkioEntry(cgs.BlkioStats.IoServicedRecursive),
  979. IoQueuedRecursive: copyBlkioEntry(cgs.BlkioStats.IoQueuedRecursive),
  980. IoServiceTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoServiceTimeRecursive),
  981. IoWaitTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoWaitTimeRecursive),
  982. IoMergedRecursive: copyBlkioEntry(cgs.BlkioStats.IoMergedRecursive),
  983. IoTimeRecursive: copyBlkioEntry(cgs.BlkioStats.IoTimeRecursive),
  984. SectorsRecursive: copyBlkioEntry(cgs.BlkioStats.SectorsRecursive),
  985. }
  986. cpu := cgs.CpuStats
  987. s.CPUStats = types.CPUStats{
  988. CPUUsage: types.CPUUsage{
  989. TotalUsage: cpu.CpuUsage.TotalUsage,
  990. PercpuUsage: cpu.CpuUsage.PercpuUsage,
  991. UsageInKernelmode: cpu.CpuUsage.UsageInKernelmode,
  992. UsageInUsermode: cpu.CpuUsage.UsageInUsermode,
  993. },
  994. ThrottlingData: types.ThrottlingData{
  995. Periods: cpu.ThrottlingData.Periods,
  996. ThrottledPeriods: cpu.ThrottlingData.ThrottledPeriods,
  997. ThrottledTime: cpu.ThrottlingData.ThrottledTime,
  998. },
  999. }
  1000. mem := cgs.MemoryStats.Usage
  1001. s.MemoryStats = types.MemoryStats{
  1002. Usage: mem.Usage,
  1003. MaxUsage: mem.MaxUsage,
  1004. Stats: cgs.MemoryStats.Stats,
  1005. Failcnt: mem.Failcnt,
  1006. Limit: mem.Limit,
  1007. }
  1008. // if the container does not set memory limit, use the machineMemory
  1009. if mem.Limit > daemon.statsCollector.machineMemory && daemon.statsCollector.machineMemory > 0 {
  1010. s.MemoryStats.Limit = daemon.statsCollector.machineMemory
  1011. }
  1012. if cgs.PidsStats != nil {
  1013. s.PidsStats = types.PidsStats{
  1014. Current: cgs.PidsStats.Current,
  1015. }
  1016. }
  1017. }
  1018. s.Read = time.Unix(int64(stats.Timestamp), 0)
  1019. return s, nil
  1020. }
  1021. // setDefaultIsolation determines the default isolation mode for the
  1022. // daemon to run in. This is only applicable on Windows
  1023. func (daemon *Daemon) setDefaultIsolation() error {
  1024. return nil
  1025. }
  1026. func rootFSToAPIType(rootfs *image.RootFS) types.RootFS {
  1027. var layers []string
  1028. for _, l := range rootfs.DiffIDs {
  1029. layers = append(layers, l.String())
  1030. }
  1031. return types.RootFS{
  1032. Type: rootfs.Type,
  1033. Layers: layers,
  1034. }
  1035. }