container.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348
  1. package 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/opts"
  17. "github.com/docker/docker/pkg/signal"
  18. "github.com/docker/docker/pkg/system"
  19. "github.com/docker/docker/pkg/truncindex"
  20. "github.com/docker/docker/runconfig"
  21. "github.com/docker/docker/volume"
  22. "github.com/docker/go-connections/nat"
  23. "github.com/opencontainers/selinux/go-selinux/label"
  24. "github.com/pkg/errors"
  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. container := daemon.newBaseContainer(id)
  83. if err := container.FromDisk(); err != nil {
  84. return nil, err
  85. }
  86. if err := label.ReserveLabel(container.ProcessLabel); err != nil {
  87. return nil, err
  88. }
  89. if container.ID != id {
  90. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  91. }
  92. return container, nil
  93. }
  94. // Register makes a container object usable by the daemon as <container.ID>
  95. func (daemon *Daemon) Register(c *container.Container) error {
  96. // Attach to stdout and stderr
  97. if c.Config.OpenStdin {
  98. c.StreamConfig.NewInputPipes()
  99. } else {
  100. c.StreamConfig.NewNopInputPipe()
  101. }
  102. // once in the memory store it is visible to other goroutines
  103. // grab a Lock until it has been checkpointed to avoid races
  104. c.Lock()
  105. defer c.Unlock()
  106. daemon.containers.Add(c.ID, c)
  107. daemon.idIndex.Add(c.ID)
  108. return c.CheckpointTo(daemon.containersReplica)
  109. }
  110. func (daemon *Daemon) newContainer(name string, operatingSystem string, config *containertypes.Config, hostConfig *containertypes.HostConfig, imgID image.ID, managed bool) (*container.Container, error) {
  111. var (
  112. id string
  113. err error
  114. noExplicitName = name == ""
  115. )
  116. id, name, err = daemon.generateIDAndName(name)
  117. if err != nil {
  118. return nil, err
  119. }
  120. if hostConfig.NetworkMode.IsHost() {
  121. if config.Hostname == "" {
  122. config.Hostname, err = os.Hostname()
  123. if err != nil {
  124. return nil, errdefs.System(err)
  125. }
  126. }
  127. } else {
  128. daemon.generateHostname(id, config)
  129. }
  130. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  131. base := daemon.newBaseContainer(id)
  132. base.Created = time.Now().UTC()
  133. base.Managed = managed
  134. base.Path = entrypoint
  135. base.Args = args //FIXME: de-duplicate from config
  136. base.Config = config
  137. base.HostConfig = &containertypes.HostConfig{}
  138. base.ImageID = imgID
  139. base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName}
  140. base.Name = name
  141. base.Driver = daemon.GraphDriverName(operatingSystem)
  142. base.OS = operatingSystem
  143. return base, err
  144. }
  145. // GetByName returns a container given a name.
  146. func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
  147. if len(name) == 0 {
  148. return nil, fmt.Errorf("No container name supplied")
  149. }
  150. fullName := name
  151. if name[0] != '/' {
  152. fullName = "/" + name
  153. }
  154. id, err := daemon.containersReplica.Snapshot().GetID(fullName)
  155. if err != nil {
  156. return nil, fmt.Errorf("Could not find entity for %s", name)
  157. }
  158. e := daemon.containers.Get(id)
  159. if e == nil {
  160. return nil, fmt.Errorf("Could not find container for entity id %s", id)
  161. }
  162. return e, nil
  163. }
  164. // newBaseContainer creates a new container with its initial
  165. // configuration based on the root storage from the daemon.
  166. func (daemon *Daemon) newBaseContainer(id string) *container.Container {
  167. return container.NewBaseContainer(id, daemon.containerRoot(id))
  168. }
  169. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint strslice.StrSlice, configCmd strslice.StrSlice) (string, []string) {
  170. if len(configEntrypoint) != 0 {
  171. return configEntrypoint[0], append(configEntrypoint[1:], configCmd...)
  172. }
  173. return configCmd[0], configCmd[1:]
  174. }
  175. func (daemon *Daemon) generateHostname(id string, config *containertypes.Config) {
  176. // Generate default hostname
  177. if config.Hostname == "" {
  178. config.Hostname = id[:12]
  179. }
  180. }
  181. func (daemon *Daemon) setSecurityOptions(container *container.Container, hostConfig *containertypes.HostConfig) error {
  182. container.Lock()
  183. defer container.Unlock()
  184. return daemon.parseSecurityOpt(container, hostConfig)
  185. }
  186. func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *containertypes.HostConfig) error {
  187. // Do not lock while creating volumes since this could be calling out to external plugins
  188. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  189. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  190. return err
  191. }
  192. container.Lock()
  193. defer container.Unlock()
  194. // Register any links from the host config before starting the container
  195. if err := daemon.registerLinks(container, hostConfig); err != nil {
  196. return err
  197. }
  198. runconfig.SetDefaultNetModeIfBlank(hostConfig)
  199. container.HostConfig = hostConfig
  200. return container.CheckpointTo(daemon.containersReplica)
  201. }
  202. // verifyContainerSettings performs validation of the hostconfig and config
  203. // structures.
  204. func (daemon *Daemon) verifyContainerSettings(platform string, hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  205. // First perform verification of settings common across all platforms.
  206. if config != nil {
  207. if config.WorkingDir != "" {
  208. wdInvalid := false
  209. if runtime.GOOS == platform {
  210. config.WorkingDir = filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  211. if !system.IsAbs(config.WorkingDir) {
  212. wdInvalid = true
  213. }
  214. } else {
  215. // LCOW. Force Unix semantics
  216. config.WorkingDir = strings.Replace(config.WorkingDir, string(os.PathSeparator), "/", -1)
  217. if !path.IsAbs(config.WorkingDir) {
  218. wdInvalid = true
  219. }
  220. }
  221. if wdInvalid {
  222. return nil, fmt.Errorf("the working directory '%s' is invalid, it needs to be an absolute path", config.WorkingDir)
  223. }
  224. }
  225. if len(config.StopSignal) > 0 {
  226. _, err := signal.ParseSignal(config.StopSignal)
  227. if err != nil {
  228. return nil, err
  229. }
  230. }
  231. // Validate if Env contains empty variable or not (e.g., ``, `=foo`)
  232. for _, env := range config.Env {
  233. if _, err := opts.ValidateEnv(env); err != nil {
  234. return nil, err
  235. }
  236. }
  237. // Validate the healthcheck params of Config
  238. if config.Healthcheck != nil {
  239. if config.Healthcheck.Interval != 0 && config.Healthcheck.Interval < containertypes.MinimumDuration {
  240. return nil, errors.Errorf("Interval in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  241. }
  242. if config.Healthcheck.Timeout != 0 && config.Healthcheck.Timeout < containertypes.MinimumDuration {
  243. return nil, errors.Errorf("Timeout in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  244. }
  245. if config.Healthcheck.Retries < 0 {
  246. return nil, errors.Errorf("Retries in Healthcheck cannot be negative")
  247. }
  248. if config.Healthcheck.StartPeriod != 0 && config.Healthcheck.StartPeriod < containertypes.MinimumDuration {
  249. return nil, errors.Errorf("StartPeriod in Healthcheck cannot be less than %s", containertypes.MinimumDuration)
  250. }
  251. }
  252. }
  253. if hostConfig == nil {
  254. return nil, nil
  255. }
  256. if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  257. return nil, errors.Errorf("can't create 'AutoRemove' container with restart policy")
  258. }
  259. // Validate mounts; check if host directories still exist
  260. parser := volume.NewParser(platform)
  261. for _, cfg := range hostConfig.Mounts {
  262. if err := parser.ValidateMountConfig(&cfg); err != nil {
  263. return nil, err
  264. }
  265. }
  266. for _, extraHost := range hostConfig.ExtraHosts {
  267. if _, err := opts.ValidateExtraHost(extraHost); err != nil {
  268. return nil, err
  269. }
  270. }
  271. for port := range hostConfig.PortBindings {
  272. _, portStr := nat.SplitProtoPort(string(port))
  273. if _, err := nat.ParsePort(portStr); err != nil {
  274. return nil, errors.Errorf("invalid port specification: %q", portStr)
  275. }
  276. for _, pb := range hostConfig.PortBindings[port] {
  277. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  278. if err != nil {
  279. return nil, errors.Errorf("invalid port specification: %q", pb.HostPort)
  280. }
  281. }
  282. }
  283. p := hostConfig.RestartPolicy
  284. switch p.Name {
  285. case "always", "unless-stopped", "no":
  286. if p.MaximumRetryCount != 0 {
  287. return nil, errors.Errorf("maximum retry count cannot be used with restart policy '%s'", p.Name)
  288. }
  289. case "on-failure":
  290. if p.MaximumRetryCount < 0 {
  291. return nil, errors.Errorf("maximum retry count cannot be negative")
  292. }
  293. case "":
  294. // do nothing
  295. default:
  296. return nil, errors.Errorf("invalid restart policy '%s'", p.Name)
  297. }
  298. if !hostConfig.Isolation.IsValid() {
  299. return nil, errors.Errorf("invalid isolation '%s' on %s", hostConfig.Isolation, runtime.GOOS)
  300. }
  301. // Now do platform-specific verification
  302. return verifyPlatformContainerSettings(daemon, hostConfig, config, update)
  303. }