volumes.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400
  1. package daemon
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "reflect"
  7. "strings"
  8. "time"
  9. "github.com/docker/docker/api/types"
  10. containertypes "github.com/docker/docker/api/types/container"
  11. mounttypes "github.com/docker/docker/api/types/mount"
  12. "github.com/docker/docker/container"
  13. "github.com/docker/docker/volume"
  14. "github.com/docker/docker/volume/drivers"
  15. "github.com/pkg/errors"
  16. "github.com/sirupsen/logrus"
  17. )
  18. var (
  19. // ErrVolumeReadonly is used to signal an error when trying to copy data into
  20. // a volume mount that is not writable.
  21. ErrVolumeReadonly = errors.New("mounted volume is marked read-only")
  22. )
  23. type mounts []container.Mount
  24. // volumeToAPIType converts a volume.Volume to the type used by the Engine API
  25. func volumeToAPIType(v volume.Volume) *types.Volume {
  26. createdAt, _ := v.CreatedAt()
  27. tv := &types.Volume{
  28. Name: v.Name(),
  29. Driver: v.DriverName(),
  30. CreatedAt: createdAt.Format(time.RFC3339),
  31. }
  32. if v, ok := v.(volume.DetailedVolume); ok {
  33. tv.Labels = v.Labels()
  34. tv.Options = v.Options()
  35. tv.Scope = v.Scope()
  36. }
  37. return tv
  38. }
  39. // Len returns the number of mounts. Used in sorting.
  40. func (m mounts) Len() int {
  41. return len(m)
  42. }
  43. // Less returns true if the number of parts (a/b/c would be 3 parts) in the
  44. // mount indexed by parameter 1 is less than that of the mount indexed by
  45. // parameter 2. Used in sorting.
  46. func (m mounts) Less(i, j int) bool {
  47. return m.parts(i) < m.parts(j)
  48. }
  49. // Swap swaps two items in an array of mounts. Used in sorting
  50. func (m mounts) Swap(i, j int) {
  51. m[i], m[j] = m[j], m[i]
  52. }
  53. // parts returns the number of parts in the destination of a mount. Used in sorting.
  54. func (m mounts) parts(i int) int {
  55. return strings.Count(filepath.Clean(m[i].Destination), string(os.PathSeparator))
  56. }
  57. // registerMountPoints initializes the container mount points with the configured volumes and bind mounts.
  58. // It follows the next sequence to decide what to mount in each final destination:
  59. //
  60. // 1. Select the previously configured mount points for the containers, if any.
  61. // 2. Select the volumes mounted from another containers. Overrides previously configured mount point destination.
  62. // 3. Select the bind mounts set by the client. Overrides previously configured mount point destinations.
  63. // 4. Cleanup old volumes that are about to be reassigned.
  64. func (daemon *Daemon) registerMountPoints(container *container.Container, hostConfig *containertypes.HostConfig) (retErr error) {
  65. binds := map[string]bool{}
  66. mountPoints := map[string]*volume.MountPoint{}
  67. parser := volume.NewParser(container.Platform)
  68. defer func() {
  69. // clean up the container mountpoints once return with error
  70. if retErr != nil {
  71. for _, m := range mountPoints {
  72. if m.Volume == nil {
  73. continue
  74. }
  75. daemon.volumes.Dereference(m.Volume, container.ID)
  76. }
  77. }
  78. }()
  79. dereferenceIfExists := func(destination string) {
  80. if v, ok := mountPoints[destination]; ok {
  81. logrus.Debugf("Duplicate mount point '%s'", destination)
  82. if v.Volume != nil {
  83. daemon.volumes.Dereference(v.Volume, container.ID)
  84. }
  85. }
  86. }
  87. // 1. Read already configured mount points.
  88. for destination, point := range container.MountPoints {
  89. mountPoints[destination] = point
  90. }
  91. // 2. Read volumes from other containers.
  92. for _, v := range hostConfig.VolumesFrom {
  93. containerID, mode, err := parser.ParseVolumesFrom(v)
  94. if err != nil {
  95. return err
  96. }
  97. c, err := daemon.GetContainer(containerID)
  98. if err != nil {
  99. return err
  100. }
  101. for _, m := range c.MountPoints {
  102. cp := &volume.MountPoint{
  103. Type: m.Type,
  104. Name: m.Name,
  105. Source: m.Source,
  106. RW: m.RW && parser.ReadWrite(mode),
  107. Driver: m.Driver,
  108. Destination: m.Destination,
  109. Propagation: m.Propagation,
  110. Spec: m.Spec,
  111. CopyData: false,
  112. }
  113. if len(cp.Source) == 0 {
  114. v, err := daemon.volumes.GetWithRef(cp.Name, cp.Driver, container.ID)
  115. if err != nil {
  116. return err
  117. }
  118. cp.Volume = v
  119. }
  120. dereferenceIfExists(cp.Destination)
  121. mountPoints[cp.Destination] = cp
  122. }
  123. }
  124. // 3. Read bind mounts
  125. for _, b := range hostConfig.Binds {
  126. bind, err := parser.ParseMountRaw(b, hostConfig.VolumeDriver)
  127. if err != nil {
  128. return err
  129. }
  130. // #10618
  131. _, tmpfsExists := hostConfig.Tmpfs[bind.Destination]
  132. if binds[bind.Destination] || tmpfsExists {
  133. return duplicateMountPointError(bind.Destination)
  134. }
  135. if bind.Type == mounttypes.TypeVolume {
  136. // create the volume
  137. v, err := daemon.volumes.CreateWithRef(bind.Name, bind.Driver, container.ID, nil, nil)
  138. if err != nil {
  139. return err
  140. }
  141. bind.Volume = v
  142. bind.Source = v.Path()
  143. // bind.Name is an already existing volume, we need to use that here
  144. bind.Driver = v.DriverName()
  145. if bind.Driver == volume.DefaultDriverName {
  146. setBindModeIfNull(bind)
  147. }
  148. }
  149. binds[bind.Destination] = true
  150. dereferenceIfExists(bind.Destination)
  151. mountPoints[bind.Destination] = bind
  152. }
  153. for _, cfg := range hostConfig.Mounts {
  154. mp, err := parser.ParseMountSpec(cfg)
  155. if err != nil {
  156. return validationError{err}
  157. }
  158. if binds[mp.Destination] {
  159. return duplicateMountPointError(cfg.Target)
  160. }
  161. if mp.Type == mounttypes.TypeVolume {
  162. var v volume.Volume
  163. if cfg.VolumeOptions != nil {
  164. var driverOpts map[string]string
  165. if cfg.VolumeOptions.DriverConfig != nil {
  166. driverOpts = cfg.VolumeOptions.DriverConfig.Options
  167. }
  168. v, err = daemon.volumes.CreateWithRef(mp.Name, mp.Driver, container.ID, driverOpts, cfg.VolumeOptions.Labels)
  169. } else {
  170. v, err = daemon.volumes.CreateWithRef(mp.Name, mp.Driver, container.ID, nil, nil)
  171. }
  172. if err != nil {
  173. return err
  174. }
  175. mp.Volume = v
  176. mp.Name = v.Name()
  177. mp.Driver = v.DriverName()
  178. // only use the cached path here since getting the path is not necessary right now and calling `Path()` may be slow
  179. if cv, ok := v.(interface {
  180. CachedPath() string
  181. }); ok {
  182. mp.Source = cv.CachedPath()
  183. }
  184. if mp.Driver == volume.DefaultDriverName {
  185. setBindModeIfNull(mp)
  186. }
  187. }
  188. binds[mp.Destination] = true
  189. dereferenceIfExists(mp.Destination)
  190. mountPoints[mp.Destination] = mp
  191. }
  192. container.Lock()
  193. // 4. Cleanup old volumes that are about to be reassigned.
  194. for _, m := range mountPoints {
  195. if parser.IsBackwardCompatible(m) {
  196. if mp, exists := container.MountPoints[m.Destination]; exists && mp.Volume != nil {
  197. daemon.volumes.Dereference(mp.Volume, container.ID)
  198. }
  199. }
  200. }
  201. container.MountPoints = mountPoints
  202. container.Unlock()
  203. return nil
  204. }
  205. // lazyInitializeVolume initializes a mountpoint's volume if needed.
  206. // This happens after a daemon restart.
  207. func (daemon *Daemon) lazyInitializeVolume(containerID string, m *volume.MountPoint) error {
  208. if len(m.Driver) > 0 && m.Volume == nil {
  209. v, err := daemon.volumes.GetWithRef(m.Name, m.Driver, containerID)
  210. if err != nil {
  211. return err
  212. }
  213. m.Volume = v
  214. }
  215. return nil
  216. }
  217. // backportMountSpec resolves mount specs (introduced in 1.13) from pre-1.13
  218. // mount configurations
  219. // The container lock should not be held when calling this function.
  220. // Changes are only made in-memory and may make changes to containers referenced
  221. // by `container.HostConfig.VolumesFrom`
  222. func (daemon *Daemon) backportMountSpec(container *container.Container) {
  223. container.Lock()
  224. defer container.Unlock()
  225. parser := volume.NewParser(container.Platform)
  226. maybeUpdate := make(map[string]bool)
  227. for _, mp := range container.MountPoints {
  228. if mp.Spec.Source != "" && mp.Type != "" {
  229. continue
  230. }
  231. maybeUpdate[mp.Destination] = true
  232. }
  233. if len(maybeUpdate) == 0 {
  234. return
  235. }
  236. mountSpecs := make(map[string]bool, len(container.HostConfig.Mounts))
  237. for _, m := range container.HostConfig.Mounts {
  238. mountSpecs[m.Target] = true
  239. }
  240. binds := make(map[string]*volume.MountPoint, len(container.HostConfig.Binds))
  241. for _, rawSpec := range container.HostConfig.Binds {
  242. mp, err := parser.ParseMountRaw(rawSpec, container.HostConfig.VolumeDriver)
  243. if err != nil {
  244. logrus.WithError(err).Error("Got unexpected error while re-parsing raw volume spec during spec backport")
  245. continue
  246. }
  247. binds[mp.Destination] = mp
  248. }
  249. volumesFrom := make(map[string]volume.MountPoint)
  250. for _, fromSpec := range container.HostConfig.VolumesFrom {
  251. from, _, err := parser.ParseVolumesFrom(fromSpec)
  252. if err != nil {
  253. logrus.WithError(err).WithField("id", container.ID).Error("Error reading volumes-from spec during mount spec backport")
  254. continue
  255. }
  256. fromC, err := daemon.GetContainer(from)
  257. if err != nil {
  258. logrus.WithError(err).WithField("from-container", from).Error("Error looking up volumes-from container")
  259. continue
  260. }
  261. // make sure from container's specs have been backported
  262. daemon.backportMountSpec(fromC)
  263. fromC.Lock()
  264. for t, mp := range fromC.MountPoints {
  265. volumesFrom[t] = *mp
  266. }
  267. fromC.Unlock()
  268. }
  269. needsUpdate := func(containerMount, other *volume.MountPoint) bool {
  270. if containerMount.Type != other.Type || !reflect.DeepEqual(containerMount.Spec, other.Spec) {
  271. return true
  272. }
  273. return false
  274. }
  275. // main
  276. for _, cm := range container.MountPoints {
  277. if !maybeUpdate[cm.Destination] {
  278. continue
  279. }
  280. // nothing to backport if from hostconfig.Mounts
  281. if mountSpecs[cm.Destination] {
  282. continue
  283. }
  284. if mp, exists := binds[cm.Destination]; exists {
  285. if needsUpdate(cm, mp) {
  286. cm.Spec = mp.Spec
  287. cm.Type = mp.Type
  288. }
  289. continue
  290. }
  291. if cm.Name != "" {
  292. if mp, exists := volumesFrom[cm.Destination]; exists {
  293. if needsUpdate(cm, &mp) {
  294. cm.Spec = mp.Spec
  295. cm.Type = mp.Type
  296. }
  297. continue
  298. }
  299. if cm.Type != "" {
  300. // probably specified via the hostconfig.Mounts
  301. continue
  302. }
  303. // anon volume
  304. cm.Type = mounttypes.TypeVolume
  305. cm.Spec.Type = mounttypes.TypeVolume
  306. } else {
  307. if cm.Type != "" {
  308. // already updated
  309. continue
  310. }
  311. cm.Type = mounttypes.TypeBind
  312. cm.Spec.Type = mounttypes.TypeBind
  313. cm.Spec.Source = cm.Source
  314. if cm.Propagation != "" {
  315. cm.Spec.BindOptions = &mounttypes.BindOptions{
  316. Propagation: cm.Propagation,
  317. }
  318. }
  319. }
  320. cm.Spec.Target = cm.Destination
  321. cm.Spec.ReadOnly = !cm.RW
  322. }
  323. }
  324. func (daemon *Daemon) traverseLocalVolumes(fn func(volume.Volume) error) error {
  325. localVolumeDriver, err := volumedrivers.GetDriver(volume.DefaultDriverName)
  326. if err != nil {
  327. return fmt.Errorf("can't retrieve local volume driver: %v", err)
  328. }
  329. vols, err := localVolumeDriver.List()
  330. if err != nil {
  331. return fmt.Errorf("can't retrieve local volumes: %v", err)
  332. }
  333. for _, v := range vols {
  334. name := v.Name()
  335. vol, err := daemon.volumes.Get(name)
  336. if err != nil {
  337. logrus.Warnf("failed to retrieve volume %s from store: %v", name, err)
  338. } else {
  339. // daemon.volumes.Get will return DetailedVolume
  340. v = vol
  341. }
  342. err = fn(v)
  343. if err != nil {
  344. return err
  345. }
  346. }
  347. return nil
  348. }