hostconfig.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. package container // import "github.com/docker/docker/api/types/container"
  2. import (
  3. "fmt"
  4. "strings"
  5. "github.com/docker/docker/api/types/blkiodev"
  6. "github.com/docker/docker/api/types/mount"
  7. "github.com/docker/docker/api/types/network"
  8. "github.com/docker/docker/api/types/strslice"
  9. "github.com/docker/go-connections/nat"
  10. units "github.com/docker/go-units"
  11. )
  12. // CgroupnsMode represents the cgroup namespace mode of the container
  13. type CgroupnsMode string
  14. // cgroup namespace modes for containers
  15. const (
  16. CgroupnsModeEmpty CgroupnsMode = ""
  17. CgroupnsModePrivate CgroupnsMode = "private"
  18. CgroupnsModeHost CgroupnsMode = "host"
  19. )
  20. // IsPrivate indicates whether the container uses its own private cgroup namespace
  21. func (c CgroupnsMode) IsPrivate() bool {
  22. return c == CgroupnsModePrivate
  23. }
  24. // IsHost indicates whether the container shares the host's cgroup namespace
  25. func (c CgroupnsMode) IsHost() bool {
  26. return c == CgroupnsModeHost
  27. }
  28. // IsEmpty indicates whether the container cgroup namespace mode is unset
  29. func (c CgroupnsMode) IsEmpty() bool {
  30. return c == CgroupnsModeEmpty
  31. }
  32. // Valid indicates whether the cgroup namespace mode is valid
  33. func (c CgroupnsMode) Valid() bool {
  34. return c.IsEmpty() || c.IsPrivate() || c.IsHost()
  35. }
  36. // Isolation represents the isolation technology of a container. The supported
  37. // values are platform specific
  38. type Isolation string
  39. // Isolation modes for containers
  40. const (
  41. IsolationEmpty Isolation = "" // IsolationEmpty is unspecified (same behavior as default)
  42. IsolationDefault Isolation = "default" // IsolationDefault is the default isolation mode on current daemon
  43. IsolationProcess Isolation = "process" // IsolationProcess is process isolation mode
  44. IsolationHyperV Isolation = "hyperv" // IsolationHyperV is HyperV isolation mode
  45. )
  46. // IsDefault indicates the default isolation technology of a container. On Linux this
  47. // is the native driver. On Windows, this is a Windows Server Container.
  48. func (i Isolation) IsDefault() bool {
  49. // TODO consider making isolation-mode strict (case-sensitive)
  50. v := Isolation(strings.ToLower(string(i)))
  51. return v == IsolationDefault || v == IsolationEmpty
  52. }
  53. // IsHyperV indicates the use of a Hyper-V partition for isolation
  54. func (i Isolation) IsHyperV() bool {
  55. // TODO consider making isolation-mode strict (case-sensitive)
  56. return Isolation(strings.ToLower(string(i))) == IsolationHyperV
  57. }
  58. // IsProcess indicates the use of process isolation
  59. func (i Isolation) IsProcess() bool {
  60. // TODO consider making isolation-mode strict (case-sensitive)
  61. return Isolation(strings.ToLower(string(i))) == IsolationProcess
  62. }
  63. // IpcMode represents the container ipc stack.
  64. type IpcMode string
  65. // IpcMode constants
  66. const (
  67. IPCModeNone IpcMode = "none"
  68. IPCModeHost IpcMode = "host"
  69. IPCModeContainer IpcMode = "container"
  70. IPCModePrivate IpcMode = "private"
  71. IPCModeShareable IpcMode = "shareable"
  72. )
  73. // IsPrivate indicates whether the container uses its own private ipc namespace which can not be shared.
  74. func (n IpcMode) IsPrivate() bool {
  75. return n == IPCModePrivate
  76. }
  77. // IsHost indicates whether the container shares the host's ipc namespace.
  78. func (n IpcMode) IsHost() bool {
  79. return n == IPCModeHost
  80. }
  81. // IsShareable indicates whether the container's ipc namespace can be shared with another container.
  82. func (n IpcMode) IsShareable() bool {
  83. return n == IPCModeShareable
  84. }
  85. // IsContainer indicates whether the container uses another container's ipc namespace.
  86. func (n IpcMode) IsContainer() bool {
  87. _, ok := containerID(string(n))
  88. return ok
  89. }
  90. // IsNone indicates whether container IpcMode is set to "none".
  91. func (n IpcMode) IsNone() bool {
  92. return n == IPCModeNone
  93. }
  94. // IsEmpty indicates whether container IpcMode is empty
  95. func (n IpcMode) IsEmpty() bool {
  96. return n == ""
  97. }
  98. // Valid indicates whether the ipc mode is valid.
  99. func (n IpcMode) Valid() bool {
  100. // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid.
  101. return n.IsEmpty() || n.IsNone() || n.IsPrivate() || n.IsHost() || n.IsShareable() || n.IsContainer()
  102. }
  103. // Container returns the name of the container ipc stack is going to be used.
  104. func (n IpcMode) Container() (idOrName string) {
  105. idOrName, _ = containerID(string(n))
  106. return idOrName
  107. }
  108. // NetworkMode represents the container network stack.
  109. type NetworkMode string
  110. // IsNone indicates whether container isn't using a network stack.
  111. func (n NetworkMode) IsNone() bool {
  112. return n == network.NetworkNone
  113. }
  114. // IsDefault indicates whether container uses the default network stack.
  115. func (n NetworkMode) IsDefault() bool {
  116. return n == network.NetworkDefault
  117. }
  118. // IsPrivate indicates whether container uses its private network stack.
  119. func (n NetworkMode) IsPrivate() bool {
  120. return !(n.IsHost() || n.IsContainer())
  121. }
  122. // IsContainer indicates whether container uses a container network stack.
  123. func (n NetworkMode) IsContainer() bool {
  124. _, ok := containerID(string(n))
  125. return ok
  126. }
  127. // ConnectedContainer is the id of the container which network this container is connected to.
  128. func (n NetworkMode) ConnectedContainer() (idOrName string) {
  129. idOrName, _ = containerID(string(n))
  130. return idOrName
  131. }
  132. // UserDefined indicates user-created network
  133. func (n NetworkMode) UserDefined() string {
  134. if n.IsUserDefined() {
  135. return string(n)
  136. }
  137. return ""
  138. }
  139. // UsernsMode represents userns mode in the container.
  140. type UsernsMode string
  141. // IsHost indicates whether the container uses the host's userns.
  142. func (n UsernsMode) IsHost() bool {
  143. return n == "host"
  144. }
  145. // IsPrivate indicates whether the container uses the a private userns.
  146. func (n UsernsMode) IsPrivate() bool {
  147. return !n.IsHost()
  148. }
  149. // Valid indicates whether the userns is valid.
  150. func (n UsernsMode) Valid() bool {
  151. return n == "" || n.IsHost()
  152. }
  153. // CgroupSpec represents the cgroup to use for the container.
  154. type CgroupSpec string
  155. // IsContainer indicates whether the container is using another container cgroup
  156. func (c CgroupSpec) IsContainer() bool {
  157. _, ok := containerID(string(c))
  158. return ok
  159. }
  160. // Valid indicates whether the cgroup spec is valid.
  161. func (c CgroupSpec) Valid() bool {
  162. // TODO(thaJeztah): align with PidMode, and consider container-mode without a container name/ID to be invalid.
  163. return c == "" || c.IsContainer()
  164. }
  165. // Container returns the ID or name of the container whose cgroup will be used.
  166. func (c CgroupSpec) Container() (idOrName string) {
  167. idOrName, _ = containerID(string(c))
  168. return idOrName
  169. }
  170. // UTSMode represents the UTS namespace of the container.
  171. type UTSMode string
  172. // IsPrivate indicates whether the container uses its private UTS namespace.
  173. func (n UTSMode) IsPrivate() bool {
  174. return !n.IsHost()
  175. }
  176. // IsHost indicates whether the container uses the host's UTS namespace.
  177. func (n UTSMode) IsHost() bool {
  178. return n == "host"
  179. }
  180. // Valid indicates whether the UTS namespace is valid.
  181. func (n UTSMode) Valid() bool {
  182. return n == "" || n.IsHost()
  183. }
  184. // PidMode represents the pid namespace of the container.
  185. type PidMode string
  186. // IsPrivate indicates whether the container uses its own new pid namespace.
  187. func (n PidMode) IsPrivate() bool {
  188. return !(n.IsHost() || n.IsContainer())
  189. }
  190. // IsHost indicates whether the container uses the host's pid namespace.
  191. func (n PidMode) IsHost() bool {
  192. return n == "host"
  193. }
  194. // IsContainer indicates whether the container uses a container's pid namespace.
  195. func (n PidMode) IsContainer() bool {
  196. _, ok := containerID(string(n))
  197. return ok
  198. }
  199. // Valid indicates whether the pid namespace is valid.
  200. func (n PidMode) Valid() bool {
  201. return n == "" || n.IsHost() || validContainer(string(n))
  202. }
  203. // Container returns the name of the container whose pid namespace is going to be used.
  204. func (n PidMode) Container() (idOrName string) {
  205. idOrName, _ = containerID(string(n))
  206. return idOrName
  207. }
  208. // DeviceRequest represents a request for devices from a device driver.
  209. // Used by GPU device drivers.
  210. type DeviceRequest struct {
  211. Driver string // Name of device driver
  212. Count int // Number of devices to request (-1 = All)
  213. DeviceIDs []string // List of device IDs as recognizable by the device driver
  214. Capabilities [][]string // An OR list of AND lists of device capabilities (e.g. "gpu")
  215. Options map[string]string // Options to pass onto the device driver
  216. }
  217. // DeviceMapping represents the device mapping between the host and the container.
  218. type DeviceMapping struct {
  219. PathOnHost string
  220. PathInContainer string
  221. CgroupPermissions string
  222. }
  223. // RestartPolicy represents the restart policies of the container.
  224. type RestartPolicy struct {
  225. Name RestartPolicyMode
  226. MaximumRetryCount int
  227. }
  228. type RestartPolicyMode string
  229. const (
  230. RestartPolicyDisabled RestartPolicyMode = "no"
  231. RestartPolicyAlways RestartPolicyMode = "always"
  232. RestartPolicyOnFailure RestartPolicyMode = "on-failure"
  233. RestartPolicyUnlessStopped RestartPolicyMode = "unless-stopped"
  234. )
  235. // IsNone indicates whether the container has the "no" restart policy.
  236. // This means the container will not automatically restart when exiting.
  237. func (rp *RestartPolicy) IsNone() bool {
  238. return rp.Name == RestartPolicyDisabled || rp.Name == ""
  239. }
  240. // IsAlways indicates whether the container has the "always" restart policy.
  241. // This means the container will automatically restart regardless of the exit status.
  242. func (rp *RestartPolicy) IsAlways() bool {
  243. return rp.Name == RestartPolicyAlways
  244. }
  245. // IsOnFailure indicates whether the container has the "on-failure" restart policy.
  246. // This means the container will automatically restart of exiting with a non-zero exit status.
  247. func (rp *RestartPolicy) IsOnFailure() bool {
  248. return rp.Name == RestartPolicyOnFailure
  249. }
  250. // IsUnlessStopped indicates whether the container has the
  251. // "unless-stopped" restart policy. This means the container will
  252. // automatically restart unless user has put it to stopped state.
  253. func (rp *RestartPolicy) IsUnlessStopped() bool {
  254. return rp.Name == RestartPolicyUnlessStopped
  255. }
  256. // IsSame compares two RestartPolicy to see if they are the same
  257. func (rp *RestartPolicy) IsSame(tp *RestartPolicy) bool {
  258. return rp.Name == tp.Name && rp.MaximumRetryCount == tp.MaximumRetryCount
  259. }
  260. // ValidateRestartPolicy validates the given RestartPolicy.
  261. func ValidateRestartPolicy(policy RestartPolicy) error {
  262. switch policy.Name {
  263. case RestartPolicyAlways, RestartPolicyUnlessStopped, RestartPolicyDisabled:
  264. if policy.MaximumRetryCount != 0 {
  265. msg := "invalid restart policy: maximum retry count can only be used with 'on-failure'"
  266. if policy.MaximumRetryCount < 0 {
  267. msg += " and cannot be negative"
  268. }
  269. return &errInvalidParameter{fmt.Errorf(msg)}
  270. }
  271. return nil
  272. case RestartPolicyOnFailure:
  273. if policy.MaximumRetryCount < 0 {
  274. return &errInvalidParameter{fmt.Errorf("invalid restart policy: maximum retry count cannot be negative")}
  275. }
  276. return nil
  277. case "":
  278. // Versions before v25.0.0 created an empty restart-policy "name" as
  279. // default. Allow an empty name with "any" MaximumRetryCount for
  280. // backward-compatibility.
  281. return nil
  282. default:
  283. return &errInvalidParameter{fmt.Errorf("invalid restart policy: unknown policy '%s'; use one of '%s', '%s', '%s', or '%s'", policy.Name, RestartPolicyDisabled, RestartPolicyAlways, RestartPolicyOnFailure, RestartPolicyUnlessStopped)}
  284. }
  285. }
  286. // LogMode is a type to define the available modes for logging
  287. // These modes affect how logs are handled when log messages start piling up.
  288. type LogMode string
  289. // Available logging modes
  290. const (
  291. LogModeUnset LogMode = ""
  292. LogModeBlocking LogMode = "blocking"
  293. LogModeNonBlock LogMode = "non-blocking"
  294. )
  295. // LogConfig represents the logging configuration of the container.
  296. type LogConfig struct {
  297. Type string
  298. Config map[string]string
  299. }
  300. // Resources contains container's resources (cgroups config, ulimits...)
  301. type Resources struct {
  302. // Applicable to all platforms
  303. CPUShares int64 `json:"CpuShares"` // CPU shares (relative weight vs. other containers)
  304. Memory int64 // Memory limit (in bytes)
  305. NanoCPUs int64 `json:"NanoCpus"` // CPU quota in units of 10<sup>-9</sup> CPUs.
  306. // Applicable to UNIX platforms
  307. CgroupParent string // Parent cgroup.
  308. BlkioWeight uint16 // Block IO weight (relative weight vs. other containers)
  309. BlkioWeightDevice []*blkiodev.WeightDevice
  310. BlkioDeviceReadBps []*blkiodev.ThrottleDevice
  311. BlkioDeviceWriteBps []*blkiodev.ThrottleDevice
  312. BlkioDeviceReadIOps []*blkiodev.ThrottleDevice
  313. BlkioDeviceWriteIOps []*blkiodev.ThrottleDevice
  314. CPUPeriod int64 `json:"CpuPeriod"` // CPU CFS (Completely Fair Scheduler) period
  315. CPUQuota int64 `json:"CpuQuota"` // CPU CFS (Completely Fair Scheduler) quota
  316. CPURealtimePeriod int64 `json:"CpuRealtimePeriod"` // CPU real-time period
  317. CPURealtimeRuntime int64 `json:"CpuRealtimeRuntime"` // CPU real-time runtime
  318. CpusetCpus string // CpusetCpus 0-2, 0,1
  319. CpusetMems string // CpusetMems 0-2, 0,1
  320. Devices []DeviceMapping // List of devices to map inside the container
  321. DeviceCgroupRules []string // List of rule to be added to the device cgroup
  322. DeviceRequests []DeviceRequest // List of device requests for device drivers
  323. // KernelMemory specifies the kernel memory limit (in bytes) for the container.
  324. // Deprecated: kernel 5.4 deprecated kmem.limit_in_bytes.
  325. KernelMemory int64 `json:",omitempty"`
  326. KernelMemoryTCP int64 `json:",omitempty"` // Hard limit for kernel TCP buffer memory (in bytes)
  327. MemoryReservation int64 // Memory soft limit (in bytes)
  328. MemorySwap int64 // Total memory usage (memory + swap); set `-1` to enable unlimited swap
  329. MemorySwappiness *int64 // Tuning container memory swappiness behaviour
  330. OomKillDisable *bool // Whether to disable OOM Killer or not
  331. PidsLimit *int64 // Setting PIDs limit for a container; Set `0` or `-1` for unlimited, or `null` to not change.
  332. Ulimits []*units.Ulimit // List of ulimits to be set in the container
  333. // Applicable to Windows
  334. CPUCount int64 `json:"CpuCount"` // CPU count
  335. CPUPercent int64 `json:"CpuPercent"` // CPU percent
  336. IOMaximumIOps uint64 // Maximum IOps for the container system drive
  337. IOMaximumBandwidth uint64 // Maximum IO in bytes per second for the container system drive
  338. }
  339. // UpdateConfig holds the mutable attributes of a Container.
  340. // Those attributes can be updated at runtime.
  341. type UpdateConfig struct {
  342. // Contains container's resources (cgroups, ulimits)
  343. Resources
  344. RestartPolicy RestartPolicy
  345. }
  346. // HostConfig the non-portable Config structure of a container.
  347. // Here, "non-portable" means "dependent of the host we are running on".
  348. // Portable information *should* appear in Config.
  349. type HostConfig struct {
  350. // Applicable to all platforms
  351. Binds []string // List of volume bindings for this container
  352. ContainerIDFile string // File (path) where the containerId is written
  353. LogConfig LogConfig // Configuration of the logs for this container
  354. NetworkMode NetworkMode // Network mode to use for the container
  355. PortBindings nat.PortMap // Port mapping between the exposed port (container) and the host
  356. RestartPolicy RestartPolicy // Restart policy to be used for the container
  357. AutoRemove bool // Automatically remove container when it exits
  358. VolumeDriver string // Name of the volume driver used to mount volumes
  359. VolumesFrom []string // List of volumes to take from other container
  360. ConsoleSize [2]uint // Initial console size (height,width)
  361. Annotations map[string]string `json:",omitempty"` // Arbitrary non-identifying metadata attached to container and provided to the runtime
  362. // Applicable to UNIX platforms
  363. CapAdd strslice.StrSlice // List of kernel capabilities to add to the container
  364. CapDrop strslice.StrSlice // List of kernel capabilities to remove from the container
  365. CgroupnsMode CgroupnsMode // Cgroup namespace mode to use for the container
  366. DNS []string `json:"Dns"` // List of DNS server to lookup
  367. DNSOptions []string `json:"DnsOptions"` // List of DNSOption to look for
  368. DNSSearch []string `json:"DnsSearch"` // List of DNSSearch to look for
  369. ExtraHosts []string // List of extra hosts
  370. GroupAdd []string // List of additional groups that the container process will run as
  371. IpcMode IpcMode // IPC namespace to use for the container
  372. Cgroup CgroupSpec // Cgroup to use for the container
  373. Links []string // List of links (in the name:alias form)
  374. OomScoreAdj int // Container preference for OOM-killing
  375. PidMode PidMode // PID namespace to use for the container
  376. Privileged bool // Is the container in privileged mode
  377. PublishAllPorts bool // Should docker publish all exposed port for the container
  378. ReadonlyRootfs bool // Is the container root filesystem in read-only
  379. SecurityOpt []string // List of string values to customize labels for MLS systems, such as SELinux.
  380. StorageOpt map[string]string `json:",omitempty"` // Storage driver options per container.
  381. Tmpfs map[string]string `json:",omitempty"` // List of tmpfs (mounts) used for the container
  382. UTSMode UTSMode // UTS namespace to use for the container
  383. UsernsMode UsernsMode // The user namespace to use for the container
  384. ShmSize int64 // Total shm memory usage
  385. Sysctls map[string]string `json:",omitempty"` // List of Namespaced sysctls used for the container
  386. Runtime string `json:",omitempty"` // Runtime to use with this container
  387. // Applicable to Windows
  388. Isolation Isolation // Isolation technology of the container (e.g. default, hyperv)
  389. // Contains container's resources (cgroups, ulimits)
  390. Resources
  391. // Mounts specs used by the container
  392. Mounts []mount.Mount `json:",omitempty"`
  393. // MaskedPaths is the list of paths to be masked inside the container (this overrides the default set of paths)
  394. MaskedPaths []string
  395. // ReadonlyPaths is the list of paths to be set as read-only inside the container (this overrides the default set of paths)
  396. ReadonlyPaths []string
  397. // Run a custom init inside the container, if null, use the daemon's configured settings
  398. Init *bool `json:",omitempty"`
  399. }
  400. // containerID splits "container:<ID|name>" values. It returns the container
  401. // ID or name, and whether an ID/name was found. It returns an empty string and
  402. // a "false" if the value does not have a "container:" prefix. Further validation
  403. // of the returned, including checking if the value is empty, should be handled
  404. // by the caller.
  405. func containerID(val string) (idOrName string, ok bool) {
  406. k, v, hasSep := strings.Cut(val, ":")
  407. if !hasSep || k != "container" {
  408. return "", false
  409. }
  410. return v, true
  411. }
  412. // validContainer checks if the given value is a "container:" mode with
  413. // a non-empty name/ID.
  414. func validContainer(val string) bool {
  415. id, ok := containerID(val)
  416. return ok && id != ""
  417. }