container.go 13 KB

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