commit.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package daemon
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "io"
  6. "runtime"
  7. "strings"
  8. "time"
  9. "github.com/docker/distribution/reference"
  10. "github.com/docker/docker/api/types/backend"
  11. containertypes "github.com/docker/docker/api/types/container"
  12. "github.com/docker/docker/builder/dockerfile"
  13. "github.com/docker/docker/errdefs"
  14. "github.com/docker/docker/image"
  15. "github.com/docker/docker/layer"
  16. "github.com/docker/docker/pkg/ioutils"
  17. "github.com/docker/docker/pkg/system"
  18. "github.com/pkg/errors"
  19. )
  20. // merge merges two Config, the image container configuration (defaults values),
  21. // and the user container configuration, either passed by the API or generated
  22. // by the cli.
  23. // It will mutate the specified user configuration (userConf) with the image
  24. // configuration where the user configuration is incomplete.
  25. func merge(userConf, imageConf *containertypes.Config) error {
  26. if userConf.User == "" {
  27. userConf.User = imageConf.User
  28. }
  29. if len(userConf.ExposedPorts) == 0 {
  30. userConf.ExposedPorts = imageConf.ExposedPorts
  31. } else if imageConf.ExposedPorts != nil {
  32. for port := range imageConf.ExposedPorts {
  33. if _, exists := userConf.ExposedPorts[port]; !exists {
  34. userConf.ExposedPorts[port] = struct{}{}
  35. }
  36. }
  37. }
  38. if len(userConf.Env) == 0 {
  39. userConf.Env = imageConf.Env
  40. } else {
  41. for _, imageEnv := range imageConf.Env {
  42. found := false
  43. imageEnvKey := strings.Split(imageEnv, "=")[0]
  44. for _, userEnv := range userConf.Env {
  45. userEnvKey := strings.Split(userEnv, "=")[0]
  46. if runtime.GOOS == "windows" {
  47. // Case insensitive environment variables on Windows
  48. imageEnvKey = strings.ToUpper(imageEnvKey)
  49. userEnvKey = strings.ToUpper(userEnvKey)
  50. }
  51. if imageEnvKey == userEnvKey {
  52. found = true
  53. break
  54. }
  55. }
  56. if !found {
  57. userConf.Env = append(userConf.Env, imageEnv)
  58. }
  59. }
  60. }
  61. if userConf.Labels == nil {
  62. userConf.Labels = map[string]string{}
  63. }
  64. for l, v := range imageConf.Labels {
  65. if _, ok := userConf.Labels[l]; !ok {
  66. userConf.Labels[l] = v
  67. }
  68. }
  69. if len(userConf.Entrypoint) == 0 {
  70. if len(userConf.Cmd) == 0 {
  71. userConf.Cmd = imageConf.Cmd
  72. userConf.ArgsEscaped = imageConf.ArgsEscaped
  73. }
  74. if userConf.Entrypoint == nil {
  75. userConf.Entrypoint = imageConf.Entrypoint
  76. }
  77. }
  78. if imageConf.Healthcheck != nil {
  79. if userConf.Healthcheck == nil {
  80. userConf.Healthcheck = imageConf.Healthcheck
  81. } else {
  82. if len(userConf.Healthcheck.Test) == 0 {
  83. userConf.Healthcheck.Test = imageConf.Healthcheck.Test
  84. }
  85. if userConf.Healthcheck.Interval == 0 {
  86. userConf.Healthcheck.Interval = imageConf.Healthcheck.Interval
  87. }
  88. if userConf.Healthcheck.Timeout == 0 {
  89. userConf.Healthcheck.Timeout = imageConf.Healthcheck.Timeout
  90. }
  91. if userConf.Healthcheck.StartPeriod == 0 {
  92. userConf.Healthcheck.StartPeriod = imageConf.Healthcheck.StartPeriod
  93. }
  94. if userConf.Healthcheck.Retries == 0 {
  95. userConf.Healthcheck.Retries = imageConf.Healthcheck.Retries
  96. }
  97. }
  98. }
  99. if userConf.WorkingDir == "" {
  100. userConf.WorkingDir = imageConf.WorkingDir
  101. }
  102. if len(userConf.Volumes) == 0 {
  103. userConf.Volumes = imageConf.Volumes
  104. } else {
  105. for k, v := range imageConf.Volumes {
  106. userConf.Volumes[k] = v
  107. }
  108. }
  109. if userConf.StopSignal == "" {
  110. userConf.StopSignal = imageConf.StopSignal
  111. }
  112. return nil
  113. }
  114. // CreateImageFromContainer creates a new image from a container. The container
  115. // config will be updated by applying the change set to the custom config, then
  116. // applying that config over the existing container config.
  117. func (daemon *Daemon) CreateImageFromContainer(name string, c *backend.CreateImageConfig) (string, error) {
  118. start := time.Now()
  119. container, err := daemon.GetContainer(name)
  120. if err != nil {
  121. return "", err
  122. }
  123. // It is not possible to commit a running container on Windows
  124. if (runtime.GOOS == "windows") && container.IsRunning() {
  125. return "", errors.Errorf("%+v does not support commit of a running container", runtime.GOOS)
  126. }
  127. if container.IsDead() {
  128. err := fmt.Errorf("You cannot commit container %s which is Dead", container.ID)
  129. return "", errdefs.Conflict(err)
  130. }
  131. if container.IsRemovalInProgress() {
  132. err := fmt.Errorf("You cannot commit container %s which is being removed", container.ID)
  133. return "", errdefs.Conflict(err)
  134. }
  135. if c.Pause && !container.IsPaused() {
  136. daemon.containerPause(container)
  137. defer daemon.containerUnpause(container)
  138. }
  139. if c.Config == nil {
  140. c.Config = container.Config
  141. }
  142. newConfig, err := dockerfile.BuildFromConfig(c.Config, c.Changes, container.OS)
  143. if err != nil {
  144. return "", err
  145. }
  146. if err := merge(newConfig, container.Config); err != nil {
  147. return "", err
  148. }
  149. id, err := daemon.commitImage(backend.CommitConfig{
  150. Author: c.Author,
  151. Comment: c.Comment,
  152. Config: newConfig,
  153. ContainerConfig: container.Config,
  154. ContainerID: container.ID,
  155. ContainerMountLabel: container.MountLabel,
  156. ContainerOS: container.OS,
  157. ParentImageID: string(container.ImageID),
  158. })
  159. if err != nil {
  160. return "", err
  161. }
  162. imageRef, err := daemon.tagCommit(c.Repo, c.Tag, id)
  163. if err != nil {
  164. return "", err
  165. }
  166. daemon.LogContainerEventWithAttributes(container, "commit", map[string]string{
  167. "comment": c.Comment,
  168. "imageID": id.String(),
  169. "imageRef": imageRef,
  170. })
  171. containerActions.WithValues("commit").UpdateSince(start)
  172. return id.String(), nil
  173. }
  174. func (daemon *Daemon) commitImage(c backend.CommitConfig) (image.ID, error) {
  175. layerStore, ok := daemon.layerStores[c.ContainerOS]
  176. if !ok {
  177. return "", system.ErrNotSupportedOperatingSystem
  178. }
  179. rwTar, err := exportContainerRw(layerStore, c.ContainerID, c.ContainerMountLabel)
  180. if err != nil {
  181. return "", err
  182. }
  183. defer func() {
  184. if rwTar != nil {
  185. rwTar.Close()
  186. }
  187. }()
  188. var parent *image.Image
  189. if c.ParentImageID == "" {
  190. parent = new(image.Image)
  191. parent.RootFS = image.NewRootFS()
  192. } else {
  193. parent, err = daemon.imageStore.Get(image.ID(c.ParentImageID))
  194. if err != nil {
  195. return "", err
  196. }
  197. }
  198. l, err := layerStore.Register(rwTar, parent.RootFS.ChainID())
  199. if err != nil {
  200. return "", err
  201. }
  202. defer layer.ReleaseAndLog(layerStore, l)
  203. cc := image.ChildConfig{
  204. ContainerID: c.ContainerID,
  205. Author: c.Author,
  206. Comment: c.Comment,
  207. ContainerConfig: c.ContainerConfig,
  208. Config: c.Config,
  209. DiffID: l.DiffID(),
  210. }
  211. config, err := json.Marshal(image.NewChildImage(parent, cc, c.ContainerOS))
  212. if err != nil {
  213. return "", err
  214. }
  215. id, err := daemon.imageStore.Create(config)
  216. if err != nil {
  217. return "", err
  218. }
  219. if c.ParentImageID != "" {
  220. if err := daemon.imageStore.SetParent(id, image.ID(c.ParentImageID)); err != nil {
  221. return "", err
  222. }
  223. }
  224. return id, nil
  225. }
  226. // TODO: remove from Daemon, move to api backend
  227. func (daemon *Daemon) tagCommit(repo string, tag string, id image.ID) (string, error) {
  228. imageRef := ""
  229. if repo != "" {
  230. newTag, err := reference.ParseNormalizedNamed(repo) // todo: should move this to API layer
  231. if err != nil {
  232. return "", err
  233. }
  234. if !reference.IsNameOnly(newTag) {
  235. return "", errors.Errorf("unexpected repository name: %s", repo)
  236. }
  237. if tag != "" {
  238. if newTag, err = reference.WithTag(newTag, tag); err != nil {
  239. return "", err
  240. }
  241. }
  242. if err := daemon.TagImageWithReference(id, newTag); err != nil {
  243. return "", err
  244. }
  245. imageRef = reference.FamiliarString(newTag)
  246. }
  247. return imageRef, nil
  248. }
  249. func exportContainerRw(layerStore layer.Store, id, mountLabel string) (arch io.ReadCloser, err error) {
  250. rwlayer, err := layerStore.GetRWLayer(id)
  251. if err != nil {
  252. return nil, err
  253. }
  254. defer func() {
  255. if err != nil {
  256. layerStore.ReleaseRWLayer(rwlayer)
  257. }
  258. }()
  259. // TODO: this mount call is not necessary as we assume that TarStream() should
  260. // mount the layer if needed. But the Diff() function for windows requests that
  261. // the layer should be mounted when calling it. So we reserve this mount call
  262. // until windows driver can implement Diff() interface correctly.
  263. _, err = rwlayer.Mount(mountLabel)
  264. if err != nil {
  265. return nil, err
  266. }
  267. archive, err := rwlayer.TarStream()
  268. if err != nil {
  269. rwlayer.Unmount()
  270. return nil, err
  271. }
  272. return ioutils.NewReadCloserWrapper(archive, func() error {
  273. archive.Close()
  274. err = rwlayer.Unmount()
  275. layerStore.ReleaseRWLayer(rwlayer)
  276. return err
  277. }),
  278. nil
  279. }
  280. // CommitBuildStep is used by the builder to create an image for each step in
  281. // the build.
  282. //
  283. // This method is different from CreateImageFromContainer:
  284. // * it doesn't attempt to validate container state
  285. // * it doesn't send a commit action to metrics
  286. // * it doesn't log a container commit event
  287. //
  288. // This is a temporary shim. Should be removed when builder stops using commit.
  289. func (daemon *Daemon) CommitBuildStep(c backend.CommitConfig) (image.ID, error) {
  290. container, err := daemon.GetContainer(c.ContainerID)
  291. if err != nil {
  292. return "", err
  293. }
  294. c.ContainerMountLabel = container.MountLabel
  295. c.ContainerOS = container.OS
  296. c.ParentImageID = string(container.ImageID)
  297. return daemon.commitImage(c)
  298. }