container.go 9.8 KB

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