daemon_unix.go 55 KB

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