container.go 13 KB

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