container.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291
  1. package daemon
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "time"
  7. "github.com/docker/docker/api/errors"
  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/image"
  13. "github.com/docker/docker/opts"
  14. "github.com/docker/docker/pkg/signal"
  15. "github.com/docker/docker/pkg/system"
  16. "github.com/docker/docker/pkg/truncindex"
  17. "github.com/docker/go-connections/nat"
  18. )
  19. // GetContainer looks for a container using the provided information, which could be
  20. // one of the following inputs from the caller:
  21. // - A full container ID, which will exact match a container in daemon's list
  22. // - A container name, which will only exact match via the GetByName() function
  23. // - A partial container ID prefix (e.g. short ID) of any length that is
  24. // unique enough to only return a single container object
  25. // If none of these searches succeed, an error is returned
  26. func (daemon *Daemon) GetContainer(prefixOrName string) (*container.Container, error) {
  27. if len(prefixOrName) == 0 {
  28. return nil, errors.NewBadRequestError(fmt.Errorf("No container name or ID supplied"))
  29. }
  30. if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
  31. // prefix is an exact match to a full container ID
  32. return containerByID, nil
  33. }
  34. // GetByName will match only an exact name provided; we ignore errors
  35. if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil {
  36. // prefix is an exact match to a full container Name
  37. return containerByName, nil
  38. }
  39. containerID, indexError := daemon.idIndex.Get(prefixOrName)
  40. if indexError != nil {
  41. // When truncindex defines an error type, use that instead
  42. if indexError == truncindex.ErrNotExist {
  43. err := fmt.Errorf("No such container: %s", prefixOrName)
  44. return nil, errors.NewRequestNotFoundError(err)
  45. }
  46. return nil, indexError
  47. }
  48. return daemon.containers.Get(containerID), nil
  49. }
  50. // Exists returns a true if a container of the specified ID or name exists,
  51. // false otherwise.
  52. func (daemon *Daemon) Exists(id string) bool {
  53. c, _ := daemon.GetContainer(id)
  54. return c != nil
  55. }
  56. // IsPaused returns a bool indicating if the specified container is paused.
  57. func (daemon *Daemon) IsPaused(id string) bool {
  58. c, _ := daemon.GetContainer(id)
  59. return c.State.IsPaused()
  60. }
  61. func (daemon *Daemon) containerRoot(id string) string {
  62. return filepath.Join(daemon.repository, id)
  63. }
  64. // Load reads the contents of a container from disk
  65. // This is typically done at startup.
  66. func (daemon *Daemon) load(id string) (*container.Container, error) {
  67. container := daemon.newBaseContainer(id)
  68. if err := container.FromDisk(); err != nil {
  69. return nil, err
  70. }
  71. if container.ID != id {
  72. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  73. }
  74. return container, nil
  75. }
  76. // Register makes a container object usable by the daemon as <container.ID>
  77. func (daemon *Daemon) Register(c *container.Container) error {
  78. // Attach to stdout and stderr
  79. if c.Config.OpenStdin {
  80. c.StreamConfig.NewInputPipes()
  81. } else {
  82. c.StreamConfig.NewNopInputPipe()
  83. }
  84. daemon.containers.Add(c.ID, c)
  85. daemon.idIndex.Add(c.ID)
  86. return nil
  87. }
  88. func (daemon *Daemon) newContainer(name string, config *containertypes.Config, hostConfig *containertypes.HostConfig, imgID image.ID, managed bool) (*container.Container, error) {
  89. var (
  90. id string
  91. err error
  92. noExplicitName = name == ""
  93. )
  94. id, name, err = daemon.generateIDAndName(name)
  95. if err != nil {
  96. return nil, err
  97. }
  98. if hostConfig.NetworkMode.IsHost() {
  99. if config.Hostname == "" {
  100. config.Hostname, err = os.Hostname()
  101. if err != nil {
  102. return nil, err
  103. }
  104. }
  105. } else {
  106. daemon.generateHostname(id, config)
  107. }
  108. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  109. base := daemon.newBaseContainer(id)
  110. base.Created = time.Now().UTC()
  111. base.Managed = managed
  112. base.Path = entrypoint
  113. base.Args = args //FIXME: de-duplicate from config
  114. base.Config = config
  115. base.HostConfig = &containertypes.HostConfig{}
  116. base.ImageID = imgID
  117. base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName}
  118. base.Name = name
  119. base.Driver = daemon.GraphDriverName()
  120. return base, err
  121. }
  122. // GetByName returns a container given a name.
  123. func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
  124. if len(name) == 0 {
  125. return nil, fmt.Errorf("No container name supplied")
  126. }
  127. fullName := name
  128. if name[0] != '/' {
  129. fullName = "/" + name
  130. }
  131. id, err := daemon.nameIndex.Get(fullName)
  132. if err != nil {
  133. return nil, fmt.Errorf("Could not find entity for %s", name)
  134. }
  135. e := daemon.containers.Get(id)
  136. if e == nil {
  137. return nil, fmt.Errorf("Could not find container for entity id %s", id)
  138. }
  139. return e, nil
  140. }
  141. // newBaseContainer creates a new container with its initial
  142. // configuration based on the root storage from the daemon.
  143. func (daemon *Daemon) newBaseContainer(id string) *container.Container {
  144. return container.NewBaseContainer(id, daemon.containerRoot(id))
  145. }
  146. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint strslice.StrSlice, configCmd strslice.StrSlice) (string, []string) {
  147. if len(configEntrypoint) != 0 {
  148. return configEntrypoint[0], append(configEntrypoint[1:], configCmd...)
  149. }
  150. return configCmd[0], configCmd[1:]
  151. }
  152. func (daemon *Daemon) generateHostname(id string, config *containertypes.Config) {
  153. // Generate default hostname
  154. if config.Hostname == "" {
  155. config.Hostname = id[:12]
  156. }
  157. }
  158. func (daemon *Daemon) setSecurityOptions(container *container.Container, hostConfig *containertypes.HostConfig) error {
  159. container.Lock()
  160. defer container.Unlock()
  161. return parseSecurityOpt(container, hostConfig)
  162. }
  163. func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *containertypes.HostConfig) error {
  164. // Do not lock while creating volumes since this could be calling out to external plugins
  165. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  166. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  167. return err
  168. }
  169. container.Lock()
  170. defer container.Unlock()
  171. // Register any links from the host config before starting the container
  172. if err := daemon.registerLinks(container, hostConfig); err != nil {
  173. return err
  174. }
  175. container.HostConfig = hostConfig
  176. return container.ToDisk()
  177. }
  178. // verifyContainerSettings performs validation of the hostconfig and config
  179. // structures.
  180. func (daemon *Daemon) verifyContainerSettings(hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool) ([]string, error) {
  181. // First perform verification of settings common across all platforms.
  182. if config != nil {
  183. if config.WorkingDir != "" {
  184. config.WorkingDir = filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  185. if !system.IsAbs(config.WorkingDir) {
  186. return nil, fmt.Errorf("the working directory '%s' is invalid, it needs to be an absolute path", config.WorkingDir)
  187. }
  188. }
  189. if len(config.StopSignal) > 0 {
  190. _, err := signal.ParseSignal(config.StopSignal)
  191. if err != nil {
  192. return nil, err
  193. }
  194. }
  195. // Validate if Env contains empty variable or not (e.g., ``, `=foo`)
  196. for _, env := range config.Env {
  197. if _, err := opts.ValidateEnv(env); err != nil {
  198. return nil, err
  199. }
  200. }
  201. // Validate the healthcheck params of Config
  202. if config.Healthcheck != nil {
  203. if config.Healthcheck.Interval != 0 && config.Healthcheck.Interval < time.Second {
  204. return nil, fmt.Errorf("Interval in Healthcheck cannot be less than one second")
  205. }
  206. if config.Healthcheck.Timeout != 0 && config.Healthcheck.Timeout < time.Second {
  207. return nil, fmt.Errorf("Timeout in Healthcheck cannot be less than one second")
  208. }
  209. if config.Healthcheck.Retries < 0 {
  210. return nil, fmt.Errorf("Retries in Healthcheck cannot be negative")
  211. }
  212. }
  213. }
  214. if hostConfig == nil {
  215. return nil, nil
  216. }
  217. if hostConfig.AutoRemove && !hostConfig.RestartPolicy.IsNone() {
  218. return nil, fmt.Errorf("can't create 'AutoRemove' container with restart policy")
  219. }
  220. for port := range hostConfig.PortBindings {
  221. _, portStr := nat.SplitProtoPort(string(port))
  222. if _, err := nat.ParsePort(portStr); err != nil {
  223. return nil, fmt.Errorf("invalid port specification: %q", portStr)
  224. }
  225. for _, pb := range hostConfig.PortBindings[port] {
  226. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  227. if err != nil {
  228. return nil, fmt.Errorf("invalid port specification: %q", pb.HostPort)
  229. }
  230. }
  231. }
  232. p := hostConfig.RestartPolicy
  233. switch p.Name {
  234. case "always", "unless-stopped", "no":
  235. if p.MaximumRetryCount != 0 {
  236. return nil, fmt.Errorf("maximum retry count cannot be used with restart policy '%s'", p.Name)
  237. }
  238. case "on-failure":
  239. if p.MaximumRetryCount < 0 {
  240. return nil, fmt.Errorf("maximum retry count cannot be negative")
  241. }
  242. case "":
  243. // do nothing
  244. default:
  245. return nil, fmt.Errorf("invalid restart policy '%s'", p.Name)
  246. }
  247. // Now do platform-specific verification
  248. return verifyPlatformContainerSettings(daemon, hostConfig, config, update)
  249. }