volumes.go 11 KB

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