container.go 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256
  1. package daemon
  2. import (
  3. "fmt"
  4. "path/filepath"
  5. "regexp"
  6. "time"
  7. "github.com/docker/docker/container"
  8. "github.com/docker/docker/daemon/network"
  9. "github.com/docker/docker/errors"
  10. "github.com/docker/docker/image"
  11. "github.com/docker/docker/pkg/signal"
  12. "github.com/docker/docker/pkg/system"
  13. "github.com/docker/docker/pkg/truncindex"
  14. containertypes "github.com/docker/engine-api/types/container"
  15. "github.com/docker/engine-api/types/strslice"
  16. "github.com/docker/go-connections/nat"
  17. )
  18. // GetContainer looks for a container using the provided information, which could be
  19. // one of the following inputs from the caller:
  20. // - A full container ID, which will exact match a container in daemon's list
  21. // - A container name, which will only exact match via the GetByName() function
  22. // - A partial container ID prefix (e.g. short ID) of any length that is
  23. // unique enough to only return a single container object
  24. // If none of these searches succeed, an error is returned
  25. func (daemon *Daemon) GetContainer(prefixOrName string) (*container.Container, error) {
  26. if len(prefixOrName) == 0 {
  27. return nil, errors.NewBadRequestError(fmt.Errorf("No container name or ID supplied"))
  28. }
  29. if containerByID := daemon.containers.Get(prefixOrName); containerByID != nil {
  30. // prefix is an exact match to a full container ID
  31. return containerByID, nil
  32. }
  33. // GetByName will match only an exact name provided; we ignore errors
  34. if containerByName, _ := daemon.GetByName(prefixOrName); containerByName != nil {
  35. // prefix is an exact match to a full container Name
  36. return containerByName, nil
  37. }
  38. containerID, indexError := daemon.idIndex.Get(prefixOrName)
  39. if indexError != nil {
  40. // When truncindex defines an error type, use that instead
  41. if indexError == truncindex.ErrNotExist {
  42. err := fmt.Errorf("No such container: %s", prefixOrName)
  43. return nil, errors.NewRequestNotFoundError(err)
  44. }
  45. return nil, indexError
  46. }
  47. return daemon.containers.Get(containerID), nil
  48. }
  49. // Exists returns a true if a container of the specified ID or name exists,
  50. // false otherwise.
  51. func (daemon *Daemon) Exists(id string) bool {
  52. c, _ := daemon.GetContainer(id)
  53. return c != nil
  54. }
  55. // IsPaused returns a bool indicating if the specified container is paused.
  56. func (daemon *Daemon) IsPaused(id string) bool {
  57. c, _ := daemon.GetContainer(id)
  58. return c.State.IsPaused()
  59. }
  60. func (daemon *Daemon) containerRoot(id string) string {
  61. return filepath.Join(daemon.repository, id)
  62. }
  63. // Load reads the contents of a container from disk
  64. // This is typically done at startup.
  65. func (daemon *Daemon) load(id string) (*container.Container, error) {
  66. container := daemon.newBaseContainer(id)
  67. if err := container.FromDisk(); err != nil {
  68. return nil, err
  69. }
  70. if container.ID != id {
  71. return container, fmt.Errorf("Container %s is stored at %s", container.ID, id)
  72. }
  73. return container, nil
  74. }
  75. // Register makes a container object usable by the daemon as <container.ID>
  76. func (daemon *Daemon) Register(c *container.Container) error {
  77. // Attach to stdout and stderr
  78. if c.Config.OpenStdin {
  79. c.NewInputPipes()
  80. } else {
  81. c.NewNopInputPipe()
  82. }
  83. daemon.containers.Add(c.ID, c)
  84. daemon.idIndex.Add(c.ID)
  85. return nil
  86. }
  87. func (daemon *Daemon) newContainer(name string, config *containertypes.Config, imgID image.ID, managed bool) (*container.Container, error) {
  88. var (
  89. id string
  90. err error
  91. noExplicitName = name == ""
  92. )
  93. id, name, err = daemon.generateIDAndName(name)
  94. if err != nil {
  95. return nil, err
  96. }
  97. daemon.generateHostname(id, config)
  98. entrypoint, args := daemon.getEntrypointAndArgs(config.Entrypoint, config.Cmd)
  99. base := daemon.newBaseContainer(id)
  100. base.Created = time.Now().UTC()
  101. base.Managed = managed
  102. base.Path = entrypoint
  103. base.Args = args //FIXME: de-duplicate from config
  104. base.Config = config
  105. base.HostConfig = &containertypes.HostConfig{}
  106. base.ImageID = imgID
  107. base.NetworkSettings = &network.Settings{IsAnonymousEndpoint: noExplicitName}
  108. base.Name = name
  109. base.Driver = daemon.GraphDriverName()
  110. return base, err
  111. }
  112. // GetByName returns a container given a name.
  113. func (daemon *Daemon) GetByName(name string) (*container.Container, error) {
  114. if len(name) == 0 {
  115. return nil, fmt.Errorf("No container name supplied")
  116. }
  117. fullName := name
  118. if name[0] != '/' {
  119. fullName = "/" + name
  120. }
  121. id, err := daemon.nameIndex.Get(fullName)
  122. if err != nil {
  123. return nil, fmt.Errorf("Could not find entity for %s", name)
  124. }
  125. e := daemon.containers.Get(id)
  126. if e == nil {
  127. return nil, fmt.Errorf("Could not find container for entity id %s", id)
  128. }
  129. return e, nil
  130. }
  131. // newBaseContainer creates a new container with its initial
  132. // configuration based on the root storage from the daemon.
  133. func (daemon *Daemon) newBaseContainer(id string) *container.Container {
  134. return container.NewBaseContainer(id, daemon.containerRoot(id))
  135. }
  136. func (daemon *Daemon) getEntrypointAndArgs(configEntrypoint strslice.StrSlice, configCmd strslice.StrSlice) (string, []string) {
  137. if len(configEntrypoint) != 0 {
  138. return configEntrypoint[0], append(configEntrypoint[1:], configCmd...)
  139. }
  140. return configCmd[0], configCmd[1:]
  141. }
  142. func (daemon *Daemon) generateHostname(id string, config *containertypes.Config) {
  143. // Generate default hostname
  144. if config.Hostname == "" {
  145. config.Hostname = id[:12]
  146. }
  147. }
  148. func (daemon *Daemon) setSecurityOptions(container *container.Container, hostConfig *containertypes.HostConfig) error {
  149. container.Lock()
  150. defer container.Unlock()
  151. return parseSecurityOpt(container, hostConfig)
  152. }
  153. func (daemon *Daemon) setHostConfig(container *container.Container, hostConfig *containertypes.HostConfig) error {
  154. // Do not lock while creating volumes since this could be calling out to external plugins
  155. // Don't want to block other actions, like `docker ps` because we're waiting on an external plugin
  156. if err := daemon.registerMountPoints(container, hostConfig); err != nil {
  157. return err
  158. }
  159. container.Lock()
  160. defer container.Unlock()
  161. // Register any links from the host config before starting the container
  162. if err := daemon.registerLinks(container, hostConfig); err != nil {
  163. return err
  164. }
  165. // make sure links is not nil
  166. // this ensures that on the next daemon restart we don't try to migrate from legacy sqlite links
  167. if hostConfig.Links == nil {
  168. hostConfig.Links = []string{}
  169. }
  170. container.HostConfig = hostConfig
  171. return container.ToDisk()
  172. }
  173. // verifyContainerSettings performs validation of the hostconfig and config
  174. // structures.
  175. func (daemon *Daemon) verifyContainerSettings(hostConfig *containertypes.HostConfig, config *containertypes.Config, update bool, validateHostname bool) ([]string, error) {
  176. // First perform verification of settings common across all platforms.
  177. if config != nil {
  178. if config.WorkingDir != "" {
  179. config.WorkingDir = filepath.FromSlash(config.WorkingDir) // Ensure in platform semantics
  180. if !system.IsAbs(config.WorkingDir) {
  181. return nil, fmt.Errorf("The working directory '%s' is invalid. It needs to be an absolute path", config.WorkingDir)
  182. }
  183. }
  184. if len(config.StopSignal) > 0 {
  185. _, err := signal.ParseSignal(config.StopSignal)
  186. if err != nil {
  187. return nil, err
  188. }
  189. }
  190. // Validate if the given hostname is RFC 1123 (https://tools.ietf.org/html/rfc1123) compliant.
  191. if validateHostname && len(config.Hostname) > 0 {
  192. // RFC1123 specifies that 63 bytes is the maximium length
  193. // Windows has the limitation of 63 bytes in length
  194. // Linux hostname is limited to HOST_NAME_MAX=64, not including the terminating null byte.
  195. // We limit the length to 63 bytes here to match RFC1035 and RFC1123.
  196. matched, _ := regexp.MatchString("^(([[:alnum:]]|[[:alnum:]][[:alnum:]\\-]*[[:alnum:]])\\.)*([[:alnum:]]|[[:alnum:]][[:alnum:]\\-]*[[:alnum:]])$", config.Hostname)
  197. if len(config.Hostname) > 63 || !matched {
  198. return nil, fmt.Errorf("invalid hostname format: %s", config.Hostname)
  199. }
  200. }
  201. }
  202. if hostConfig == nil {
  203. return nil, nil
  204. }
  205. for port := range hostConfig.PortBindings {
  206. _, portStr := nat.SplitProtoPort(string(port))
  207. if _, err := nat.ParsePort(portStr); err != nil {
  208. return nil, fmt.Errorf("Invalid port specification: %q", portStr)
  209. }
  210. for _, pb := range hostConfig.PortBindings[port] {
  211. _, err := nat.NewPort(nat.SplitProtoPort(pb.HostPort))
  212. if err != nil {
  213. return nil, fmt.Errorf("Invalid port specification: %q", pb.HostPort)
  214. }
  215. }
  216. }
  217. // Now do platform-specific verification
  218. return verifyPlatformContainerSettings(daemon, hostConfig, config, update)
  219. }