daemon_unix.go 41 KB

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