daemon_unix.go 40 KB

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