container.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370
  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/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. // Exists returns a true if a container of the specified ID or name exists,
  65. // false otherwise.
  66. func (daemon *Daemon) Exists(id string) bool {
  67. c, _ := daemon.GetContainer(id)
  68. return c != nil
  69. }
  70. // IsPaused returns a bool indicating if the specified container is paused.
  71. func (daemon *Daemon) IsPaused(id string) bool {
  72. c, _ := daemon.GetContainer(id)
  73. return c.State.IsPaused()
  74. }
  75. func (daemon *Daemon) containerRoot(id string) string {
  76. return filepath.Join(daemon.repository, id)
  77. }
  78. // Load reads the contents of a container from disk
  79. // This is typically done at startup.
  80. func (daemon *Daemon) load(id string) (*container.Container, error) {
  81. ctr := daemon.newBaseContainer(id)
  82. if err := ctr.FromDisk(); err != nil {
  83. return nil, err
  84. }
  85. selinux.ReserveLabel(ctr.ProcessLabel)
  86. if ctr.ID != id {
  87. return ctr, fmt.Errorf("Container %s is stored at %s", ctr.ID, id)
  88. }
  89. return ctr, nil
  90. }
  91. // Register makes a container object usable by the daemon as <container.ID>
  92. func (daemon *Daemon) Register(c *container.Container) error {
  93. // Attach to stdout and stderr
  94. if c.Config.OpenStdin {
  95. c.StreamConfig.NewInputPipes()
  96. } else {
  97. c.StreamConfig.NewNopInputPipe()
  98. }
  99. // once in the memory store it is visible to other goroutines
  100. // grab a Lock until it has been checkpointed to avoid races
  101. c.Lock()
  102. defer c.Unlock()
  103. daemon.containers.Add(c.ID, c)
  104. return c.CheckpointTo(daemon.containersReplica)
  105. }
  106. func (daemon *Daemon) newContainer(name string, operatingSystem string, config *containertypes.Config, hostConfig *containertypes.HostConfig, imgID image.ID, managed bool) (*container.Container, error) {
  107. var (
  108. id string
  109. err error
  110. noExplicitName = name == ""
  111. )
  112. id, name, err = daemon.generateIDAndName(name)
  113. if err != nil {
  114. return nil, err
  115. }
  116. if hostConfig.NetworkMode.IsHost() {
  117. if config.Hostname == "" {
  118. config.Hostname, err = os.Hostname()
  119. if err != nil {
  120. return nil, errdefs.System(err)
  121. }
  122. }
  123. } else {
  124. daemon.generateHostname(id, config)
  125. }
  126. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  127. base := daemon.newBaseContainer(id)
  128. base.Created = time.Now().UTC()
  129. base.Managed = managed
  130. base.Path = entrypoint
  131. base.Args = args // FIXME: de-duplicate from config
  132. base.Config = config
  133. base.HostConfig = &containertypes.HostConfig{}
  134. base.ImageID = imgID
  135. base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName}
  136. base.Name = name
  137. base.Driver = daemon.imageService.StorageDriver()
  138. base.OS = operatingSystem
  139. return base, err
  140. }
  141. // GetByName returns a container given a name.
  142. func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
  143. if len(name) == 0 {
  144. return nil, fmt.Errorf("No container name supplied")
  145. }
  146. fullName := name
  147. if name[0] != '/' {
  148. fullName = "/" + name
  149. }
  150. id, err := daemon.containersReplica.Snapshot().GetID(fullName)
  151. if err != nil {
  152. return nil, fmt.Errorf("Could not find entity for %s", name)
  153. }
  154. e := daemon.containers.Get(id)
  155. if e == nil {
  156. return nil, fmt.Errorf("Could not find container for entity id %s", id)
  157. }
  158. return e, nil
  159. }
  160. // newBaseContainer creates a new container with its initial
  161. // configuration based on the root storage from the daemon.
  162. func (daemon *Daemon) newBaseContainer(id string) *container.Container {
  163. return container.NewBaseContainer(id, daemon.containerRoot(id))
  164. }
  165. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint strslice.StrSlice, configCmd strslice.StrSlice) (string, []string) {
  166. if len(configEntrypoint) != 0 {
  167. return configEntrypoint[0], append(configEntrypoint[1:], configCmd...)
  168. }
  169. return configCmd[0], configCmd[1:]
  170. }
  171. func (daemon *Daemon) generateHostname(id string, config *containertypes.Config) {
  172. // Generate default hostname
  173. if config.Hostname == "" {
  174. config.Hostname = id[:12]
  175. }
  176. }
  177. func (daemon *Daemon) setSecurityOptions(cfg *config.Config, container *container.Container, hostConfig *containertypes.HostConfig) error {
  178. container.Lock()
  179. defer container.Unlock()
  180. return daemon.parseSecurityOpt(cfg, &container.SecurityOptions, hostConfig)
  181. }
  182. func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *containertypes.HostConfig) error {
  183. // Do not lock while creating volumes since this could be calling out to external plugins
  184. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  185. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  186. return err
  187. }
  188. container.Lock()
  189. defer container.Unlock()
  190. // Register any links from the host config before starting the container
  191. if err := daemon.registerLinks(container, hostConfig); err != nil {
  192. return err
  193. }
  194. runconfig.SetDefaultNetModeIfBlank(hostConfig)
  195. container.HostConfig = hostConfig
  196. return nil
  197. }
  198. // verifyContainerSettings performs validation of the hostconfig and config
  199. // structures.
  200. func (daemon *Daemon) verifyContainerSettings(daemonCfg *configStore, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) (warnings []string, err error) {
  201. // First perform verification of settings common across all platforms.
  202. if err = validateContainerConfig(config); err != nil {
  203. return warnings, err
  204. }
  205. if err := validateHostConfig(hostConfig); err != nil {
  206. return warnings, err
  207. }
  208. // Now do platform-specific verification
  209. warnings, err = verifyPlatformContainerSettings(daemon, daemonCfg, hostConfig, update)
  210. for _, w := range warnings {
  211. log.G(context.TODO()).Warn(w)
  212. }
  213. return warnings, err
  214. }
  215. func validateContainerConfig(config *containertypes.Config) error {
  216. if config == nil {
  217. return nil
  218. }
  219. if err := translateWorkingDir(config); err != nil {
  220. return err
  221. }
  222. if len(config.StopSignal) > 0 {
  223. if _, err := signal.ParseSignal(config.StopSignal); err != nil {
  224. return err
  225. }
  226. }
  227. // Validate if Env contains empty variable or not (e.g., ``, `=foo`)
  228. for _, env := range config.Env {
  229. if _, err := opts.ValidateEnv(env); err != nil {
  230. return err
  231. }
  232. }
  233. return validateHealthCheck(config.Healthcheck)
  234. }
  235. func validateHostConfig(hostConfig *containertypes.HostConfig) error {
  236. if hostConfig == nil {
  237. return nil
  238. }
  239. if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  240. return errors.Errorf("can't create 'AutoRemove' container with restart policy")
  241. }
  242. // Validate mounts; check if host directories still exist
  243. parser := volumemounts.NewParser()
  244. for _, c := range hostConfig.Mounts {
  245. cfg := c
  246. if err := parser.ValidateMountConfig(&cfg); err != nil {
  247. return err
  248. }
  249. }
  250. for _, extraHost := range hostConfig.ExtraHosts {
  251. if _, err := opts.ValidateExtraHost(extraHost); err != nil {
  252. return err
  253. }
  254. }
  255. if err := validatePortBindings(hostConfig.PortBindings); err != nil {
  256. return err
  257. }
  258. if err := containertypes.ValidateRestartPolicy(hostConfig.RestartPolicy); err != nil {
  259. return err
  260. }
  261. if err := validateCapabilities(hostConfig); err != nil {
  262. return err
  263. }
  264. if !hostConfig.Isolation.IsValid() {
  265. return errors.Errorf("invalid isolation '%s' on %s", hostConfig.Isolation, runtime.GOOS)
  266. }
  267. for k := range hostConfig.Annotations {
  268. if k == "" {
  269. return errors.Errorf("invalid Annotations: the empty string is not permitted as an annotation key")
  270. }
  271. }
  272. return nil
  273. }
  274. func validateCapabilities(hostConfig *containertypes.HostConfig) error {
  275. if _, err := caps.NormalizeLegacyCapabilities(hostConfig.CapAdd); err != nil {
  276. return errors.Wrap(err, "invalid CapAdd")
  277. }
  278. if _, err := caps.NormalizeLegacyCapabilities(hostConfig.CapDrop); err != nil {
  279. return errors.Wrap(err, "invalid CapDrop")
  280. }
  281. // TODO consider returning warnings if "Privileged" is combined with Capabilities, CapAdd and/or CapDrop
  282. return nil
  283. }
  284. // validateHealthCheck validates the healthcheck params of Config
  285. func validateHealthCheck(healthConfig *containertypes.HealthConfig) error {
  286. if healthConfig == nil {
  287. return nil
  288. }
  289. if healthConfig.Interval != 0 && healthConfig.Interval < containertypes.MinimumDuration {
  290. return errors.Errorf("Interval in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  291. }
  292. if healthConfig.Timeout != 0 && healthConfig.Timeout < containertypes.MinimumDuration {
  293. return errors.Errorf("Timeout in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  294. }
  295. if healthConfig.Retries < 0 {
  296. return errors.Errorf("Retries in Healthcheck cannot be negative")
  297. }
  298. if healthConfig.StartPeriod != 0 && healthConfig.StartPeriod < containertypes.MinimumDuration {
  299. return errors.Errorf("StartPeriod in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  300. }
  301. if healthConfig.StartInterval != 0 && healthConfig.StartInterval < containertypes.MinimumDuration {
  302. return errors.Errorf("StartInterval in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  303. }
  304. return nil
  305. }
  306. func validatePortBindings(ports nat.PortMap) error {
  307. for port := range ports {
  308. _, portStr := nat.SplitProtoPort(string(port))
  309. if _, err := nat.ParsePort(portStr); err != nil {
  310. return errors.Errorf("invalid port specification: %q", portStr)
  311. }
  312. for _, pb := range ports[port] {
  313. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  314. if err != nil {
  315. return errors.Errorf("invalid port specification: %q", pb.HostPort)
  316. }
  317. }
  318. }
  319. return nil
  320. }
  321. // translateWorkingDir translates the working-dir for the target platform,
  322. // and returns an error if the given path is not an absolute path.
  323. func translateWorkingDir(config *containertypes.Config) error {
  324. if config.WorkingDir == "" {
  325. return nil
  326. }
  327. wd := filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  328. if !system.IsAbs(wd) {
  329. return fmt.Errorf("the working directory '%s' is invalid, it needs to be an absolute path", config.WorkingDir)
  330. }
  331. config.WorkingDir = wd
  332. return nil
  333. }