container.go 12 KB

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