container.go 12 KB

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