daemon_unix.go 55 KB

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