container.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  1. package daemon // import "github.com/docker/docker/daemon"
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "runtime"
  8. "time"
  9. "github.com/containerd/containerd/log"
  10. containertypes "github.com/docker/docker/api/types/container"
  11. "github.com/docker/docker/api/types/strslice"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/daemon/config"
  14. "github.com/docker/docker/daemon/network"
  15. "github.com/docker/docker/errdefs"
  16. "github.com/docker/docker/image"
  17. "github.com/docker/docker/oci/caps"
  18. "github.com/docker/docker/opts"
  19. "github.com/docker/docker/pkg/system"
  20. "github.com/docker/docker/runconfig"
  21. volumemounts "github.com/docker/docker/volume/mounts"
  22. "github.com/docker/go-connections/nat"
  23. "github.com/moby/sys/signal"
  24. "github.com/opencontainers/selinux/go-selinux"
  25. "github.com/pkg/errors"
  26. )
  27. // GetContainer looks for a container using the provided information, which could be
  28. // one of the following inputs from the caller:
  29. // - A full container ID, which will exact match a container in daemon's list
  30. // - A container name, which will only exact match via the GetByName() function
  31. // - A partial container ID prefix (e.g. short ID) of any length that is
  32. // unique enough to only return a single container object
  33. // If none of these searches succeed, an error is returned
  34. func (daemon *Daemon) GetContainer(prefixOrName string) (*container.Container, error) {
  35. if len(prefixOrName) == 0 {
  36. return nil, errors.WithStack(invalidIdentifier(prefixOrName))
  37. }
  38. if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
  39. // prefix is an exact match to a full container ID
  40. return containerByID, nil
  41. }
  42. // GetByName will match only an exact name provided; we ignore errors
  43. if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil {
  44. // prefix is an exact match to a full container Name
  45. return containerByName, nil
  46. }
  47. containerID, err := daemon.containersReplica.GetByPrefix(prefixOrName)
  48. if err != nil {
  49. return nil, err
  50. }
  51. ctr := daemon.containers.Get(containerID)
  52. if ctr == nil {
  53. // Updates to the daemon.containersReplica ViewDB are not atomic
  54. // or consistent w.r.t. the live daemon.containers Store so
  55. // while reaching this code path may be indicative of a bug,
  56. // it is not _necessarily_ the case.
  57. log.G(context.TODO()).WithField("prefixOrName", prefixOrName).
  58. WithField("id", containerID).
  59. Debugf("daemon.GetContainer: container is known to daemon.containersReplica but not daemon.containers")
  60. return nil, containerNotFound(prefixOrName)
  61. }
  62. return ctr, nil
  63. }
  64. // checkContainer make sure the specified container validates the specified conditions
  65. func (daemon *Daemon) checkContainer(container *container.Container, conditions ...func(*container.Container) error) error {
  66. for _, condition := range conditions {
  67. if err := condition(container); err != nil {
  68. return err
  69. }
  70. }
  71. return nil
  72. }
  73. // Exists returns a true if a container of the specified ID or name exists,
  74. // false otherwise.
  75. func (daemon *Daemon) Exists(id string) bool {
  76. c, _ := daemon.GetContainer(id)
  77. return c != nil
  78. }
  79. // IsPaused returns a bool indicating if the specified container is paused.
  80. func (daemon *Daemon) IsPaused(id string) bool {
  81. c, _ := daemon.GetContainer(id)
  82. return c.State.IsPaused()
  83. }
  84. func (daemon *Daemon) containerRoot(id string) string {
  85. return filepath.Join(daemon.repository, id)
  86. }
  87. // Load reads the contents of a container from disk
  88. // This is typically done at startup.
  89. func (daemon *Daemon) load(id string) (*container.Container, error) {
  90. ctr := daemon.newBaseContainer(id)
  91. if err := ctr.FromDisk(); err != nil {
  92. return nil, err
  93. }
  94. selinux.ReserveLabel(ctr.ProcessLabel)
  95. if ctr.ID != id {
  96. return ctr, fmt.Errorf("Container %s is stored at %s", ctr.ID, id)
  97. }
  98. return ctr, nil
  99. }
  100. // Register makes a container object usable by the daemon as <container.ID>
  101. func (daemon *Daemon) Register(c *container.Container) error {
  102. // Attach to stdout and stderr
  103. if c.Config.OpenStdin {
  104. c.StreamConfig.NewInputPipes()
  105. } else {
  106. c.StreamConfig.NewNopInputPipe()
  107. }
  108. // once in the memory store it is visible to other goroutines
  109. // grab a Lock until it has been checkpointed to avoid races
  110. c.Lock()
  111. defer c.Unlock()
  112. daemon.containers.Add(c.ID, c)
  113. return c.CheckpointTo(daemon.containersReplica)
  114. }
  115. func (daemon *Daemon) newContainer(name string, operatingSystem string, config *containertypes.Config, hostConfig *containertypes.HostConfig, imgID image.ID, managed bool) (*container.Container, error) {
  116. var (
  117. id string
  118. err error
  119. noExplicitName = name == ""
  120. )
  121. id, name, err = daemon.generateIDAndName(name)
  122. if err != nil {
  123. return nil, err
  124. }
  125. if hostConfig.NetworkMode.IsHost() {
  126. if config.Hostname == "" {
  127. config.Hostname, err = os.Hostname()
  128. if err != nil {
  129. return nil, errdefs.System(err)
  130. }
  131. }
  132. } else {
  133. daemon.generateHostname(id, config)
  134. }
  135. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  136. base := daemon.newBaseContainer(id)
  137. base.Created = time.Now().UTC()
  138. base.Managed = managed
  139. base.Path = entrypoint
  140. base.Args = args // FIXME: de-duplicate from config
  141. base.Config = config
  142. base.HostConfig = &containertypes.HostConfig{}
  143. base.ImageID = imgID
  144. base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName}
  145. base.Name = name
  146. base.Driver = daemon.imageService.StorageDriver()
  147. base.OS = operatingSystem
  148. return base, err
  149. }
  150. // GetByName returns a container given a name.
  151. func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
  152. if len(name) == 0 {
  153. return nil, fmt.Errorf("No container name supplied")
  154. }
  155. fullName := name
  156. if name[0] != '/' {
  157. fullName = "/" + name
  158. }
  159. id, err := daemon.containersReplica.Snapshot().GetID(fullName)
  160. if err != nil {
  161. return nil, fmt.Errorf("Could not find entity for %s", name)
  162. }
  163. e := daemon.containers.Get(id)
  164. if e == nil {
  165. return nil, fmt.Errorf("Could not find container for entity id %s", id)
  166. }
  167. return e, nil
  168. }
  169. // newBaseContainer creates a new container with its initial
  170. // configuration based on the root storage from the daemon.
  171. func (daemon *Daemon) newBaseContainer(id string) *container.Container {
  172. return container.NewBaseContainer(id, daemon.containerRoot(id))
  173. }
  174. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint strslice.StrSlice, configCmd strslice.StrSlice) (string, []string) {
  175. if len(configEntrypoint) != 0 {
  176. return configEntrypoint[0], append(configEntrypoint[1:], configCmd...)
  177. }
  178. return configCmd[0], configCmd[1:]
  179. }
  180. func (daemon *Daemon) generateHostname(id string, config *containertypes.Config) {
  181. // Generate default hostname
  182. if config.Hostname == "" {
  183. config.Hostname = id[:12]
  184. }
  185. }
  186. func (daemon *Daemon) setSecurityOptions(cfg *config.Config, container *container.Container, hostConfig *containertypes.HostConfig) error {
  187. container.Lock()
  188. defer container.Unlock()
  189. return daemon.parseSecurityOpt(cfg, &container.SecurityOptions, hostConfig)
  190. }
  191. func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *containertypes.HostConfig) error {
  192. // Do not lock while creating volumes since this could be calling out to external plugins
  193. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  194. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  195. return err
  196. }
  197. container.Lock()
  198. defer container.Unlock()
  199. // Register any links from the host config before starting the container
  200. if err := daemon.registerLinks(container, hostConfig); err != nil {
  201. return err
  202. }
  203. runconfig.SetDefaultNetModeIfBlank(hostConfig)
  204. container.HostConfig = hostConfig
  205. return nil
  206. }
  207. // verifyContainerSettings performs validation of the hostconfig and config
  208. // structures.
  209. func (daemon *Daemon) verifyContainerSettings(daemonCfg *configStore, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) (warnings []string, err error) {
  210. // First perform verification of settings common across all platforms.
  211. if err = validateContainerConfig(config); err != nil {
  212. return warnings, err
  213. }
  214. if err := validateHostConfig(hostConfig); err != nil {
  215. return warnings, err
  216. }
  217. // Now do platform-specific verification
  218. warnings, err = verifyPlatformContainerSettings(daemon, daemonCfg, hostConfig, update)
  219. for _, w := range warnings {
  220. log.G(context.TODO()).Warn(w)
  221. }
  222. return warnings, err
  223. }
  224. func validateContainerConfig(config *containertypes.Config) error {
  225. if config == nil {
  226. return nil
  227. }
  228. if err := translateWorkingDir(config); err != nil {
  229. return err
  230. }
  231. if len(config.StopSignal) > 0 {
  232. if _, err := signal.ParseSignal(config.StopSignal); err != nil {
  233. return err
  234. }
  235. }
  236. // Validate if Env contains empty variable or not (e.g., ``, `=foo`)
  237. for _, env := range config.Env {
  238. if _, err := opts.ValidateEnv(env); err != nil {
  239. return err
  240. }
  241. }
  242. return validateHealthCheck(config.Healthcheck)
  243. }
  244. func validateHostConfig(hostConfig *containertypes.HostConfig) error {
  245. if hostConfig == nil {
  246. return nil
  247. }
  248. if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  249. return errors.Errorf("can't create 'AutoRemove' container with restart policy")
  250. }
  251. // Validate mounts; check if host directories still exist
  252. parser := volumemounts.NewParser()
  253. for _, c := range hostConfig.Mounts {
  254. cfg := c
  255. if err := parser.ValidateMountConfig(&cfg); err != nil {
  256. return err
  257. }
  258. }
  259. for _, extraHost := range hostConfig.ExtraHosts {
  260. if _, err := opts.ValidateExtraHost(extraHost); err != nil {
  261. return err
  262. }
  263. }
  264. if err := validatePortBindings(hostConfig.PortBindings); err != nil {
  265. return err
  266. }
  267. if err := validateRestartPolicy(hostConfig.RestartPolicy); err != nil {
  268. return err
  269. }
  270. if err := validateCapabilities(hostConfig); err != nil {
  271. return err
  272. }
  273. if !hostConfig.Isolation.IsValid() {
  274. return errors.Errorf("invalid isolation '%s' on %s", hostConfig.Isolation, runtime.GOOS)
  275. }
  276. for k := range hostConfig.Annotations {
  277. if k == "" {
  278. return errors.Errorf("invalid Annotations: the empty string is not permitted as an annotation key")
  279. }
  280. }
  281. return nil
  282. }
  283. func validateCapabilities(hostConfig *containertypes.HostConfig) error {
  284. if _, err := caps.NormalizeLegacyCapabilities(hostConfig.CapAdd); err != nil {
  285. return errors.Wrap(err, "invalid CapAdd")
  286. }
  287. if _, err := caps.NormalizeLegacyCapabilities(hostConfig.CapDrop); err != nil {
  288. return errors.Wrap(err, "invalid CapDrop")
  289. }
  290. // TODO consider returning warnings if "Privileged" is combined with Capabilities, CapAdd and/or CapDrop
  291. return nil
  292. }
  293. // validateHealthCheck validates the healthcheck params of Config
  294. func validateHealthCheck(healthConfig *containertypes.HealthConfig) error {
  295. if healthConfig == nil {
  296. return nil
  297. }
  298. if healthConfig.Interval != 0 && healthConfig.Interval < containertypes.MinimumDuration {
  299. return errors.Errorf("Interval in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  300. }
  301. if healthConfig.Timeout != 0 && healthConfig.Timeout < containertypes.MinimumDuration {
  302. return errors.Errorf("Timeout in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  303. }
  304. if healthConfig.Retries < 0 {
  305. return errors.Errorf("Retries in Healthcheck cannot be negative")
  306. }
  307. if healthConfig.StartPeriod != 0 && healthConfig.StartPeriod < containertypes.MinimumDuration {
  308. return errors.Errorf("StartPeriod in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  309. }
  310. return nil
  311. }
  312. func validatePortBindings(ports nat.PortMap) error {
  313. for port := range ports {
  314. _, portStr := nat.SplitProtoPort(string(port))
  315. if _, err := nat.ParsePort(portStr); err != nil {
  316. return errors.Errorf("invalid port specification: %q", portStr)
  317. }
  318. for _, pb := range ports[port] {
  319. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  320. if err != nil {
  321. return errors.Errorf("invalid port specification: %q", pb.HostPort)
  322. }
  323. }
  324. }
  325. return nil
  326. }
  327. func validateRestartPolicy(policy containertypes.RestartPolicy) error {
  328. switch policy.Name {
  329. case "always", "unless-stopped", "no":
  330. if policy.MaximumRetryCount != 0 {
  331. return errors.Errorf("maximum retry count cannot be used with restart policy '%s'", policy.Name)
  332. }
  333. case "on-failure":
  334. if policy.MaximumRetryCount < 0 {
  335. return errors.Errorf("maximum retry count cannot be negative")
  336. }
  337. case "":
  338. // do nothing
  339. return nil
  340. default:
  341. return errors.Errorf("invalid restart policy '%s'", policy.Name)
  342. }
  343. return nil
  344. }
  345. // translateWorkingDir translates the working-dir for the target platform,
  346. // and returns an error if the given path is not an absolute path.
  347. func translateWorkingDir(config *containertypes.Config) error {
  348. if config.WorkingDir == "" {
  349. return nil
  350. }
  351. wd := filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  352. if !system.IsAbs(wd) {
  353. return fmt.Errorf("the working directory '%s' is invalid, it needs to be an absolute path", config.WorkingDir)
  354. }
  355. config.WorkingDir = wd
  356. return nil
  357. }