volumes.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. package daemon
  2. import (
  3. "errors"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "reflect"
  8. "strings"
  9. "time"
  10. "github.com/Sirupsen/logrus"
  11. dockererrors "github.com/docker/docker/api/errors"
  12. "github.com/docker/docker/api/types"
  13. containertypes "github.com/docker/docker/api/types/container"
  14. mounttypes "github.com/docker/docker/api/types/mount"
  15. "github.com/docker/docker/container"
  16. "github.com/docker/docker/volume"
  17. "github.com/docker/docker/volume/drivers"
  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. 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 := volume.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 && volume.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 := volume.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 fmt.Errorf("Duplicate mount point '%s'", 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 := volume.ParseMountSpec(cfg)
  155. if err != nil {
  156. return dockererrors.NewBadRequestError(err)
  157. }
  158. if binds[mp.Destination] {
  159. return fmt.Errorf("Duplicate mount point '%s'", 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. }
  185. binds[mp.Destination] = true
  186. dereferenceIfExists(mp.Destination)
  187. mountPoints[mp.Destination] = mp
  188. }
  189. container.Lock()
  190. // 4. Cleanup old volumes that are about to be reassigned.
  191. for _, m := range mountPoints {
  192. if m.BackwardsCompatible() {
  193. if mp, exists := container.MountPoints[m.Destination]; exists && mp.Volume != nil {
  194. daemon.volumes.Dereference(mp.Volume, container.ID)
  195. }
  196. }
  197. }
  198. container.MountPoints = mountPoints
  199. container.Unlock()
  200. return nil
  201. }
  202. // lazyInitializeVolume initializes a mountpoint's volume if needed.
  203. // This happens after a daemon restart.
  204. func (daemon *Daemon) lazyInitializeVolume(containerID string, m *volume.MountPoint) error {
  205. if len(m.Driver) > 0 && m.Volume == nil {
  206. v, err := daemon.volumes.GetWithRef(m.Name, m.Driver, containerID)
  207. if err != nil {
  208. return err
  209. }
  210. m.Volume = v
  211. }
  212. return nil
  213. }
  214. // backportMountSpec resolves mount specs (introduced in 1.13) from pre-1.13
  215. // mount configurations
  216. // The container lock should not be held when calling this function.
  217. // Changes are only made in-memory and may make changes to containers referenced
  218. // by `container.HostConfig.VolumesFrom`
  219. func (daemon *Daemon) backportMountSpec(container *container.Container) {
  220. container.Lock()
  221. defer container.Unlock()
  222. maybeUpdate := make(map[string]bool)
  223. for _, mp := range container.MountPoints {
  224. if mp.Spec.Source != "" && mp.Type != "" {
  225. continue
  226. }
  227. maybeUpdate[mp.Destination] = true
  228. }
  229. if len(maybeUpdate) == 0 {
  230. return
  231. }
  232. mountSpecs := make(map[string]bool, len(container.HostConfig.Mounts))
  233. for _, m := range container.HostConfig.Mounts {
  234. mountSpecs[m.Target] = true
  235. }
  236. binds := make(map[string]*volume.MountPoint, len(container.HostConfig.Binds))
  237. for _, rawSpec := range container.HostConfig.Binds {
  238. mp, err := volume.ParseMountRaw(rawSpec, container.HostConfig.VolumeDriver)
  239. if err != nil {
  240. logrus.WithError(err).Error("Got unexpected error while re-parsing raw volume spec during spec backport")
  241. continue
  242. }
  243. binds[mp.Destination] = mp
  244. }
  245. volumesFrom := make(map[string]volume.MountPoint)
  246. for _, fromSpec := range container.HostConfig.VolumesFrom {
  247. from, _, err := volume.ParseVolumesFrom(fromSpec)
  248. if err != nil {
  249. logrus.WithError(err).WithField("id", container.ID).Error("Error reading volumes-from spec during mount spec backport")
  250. continue
  251. }
  252. fromC, err := daemon.GetContainer(from)
  253. if err != nil {
  254. logrus.WithError(err).WithField("from-container", from).Error("Error looking up volumes-from container")
  255. continue
  256. }
  257. // make sure from container's specs have been backported
  258. daemon.backportMountSpec(fromC)
  259. fromC.Lock()
  260. for t, mp := range fromC.MountPoints {
  261. volumesFrom[t] = *mp
  262. }
  263. fromC.Unlock()
  264. }
  265. needsUpdate := func(containerMount, other *volume.MountPoint) bool {
  266. if containerMount.Type != other.Type || !reflect.DeepEqual(containerMount.Spec, other.Spec) {
  267. return true
  268. }
  269. return false
  270. }
  271. // main
  272. for _, cm := range container.MountPoints {
  273. if !maybeUpdate[cm.Destination] {
  274. continue
  275. }
  276. // nothing to backport if from hostconfig.Mounts
  277. if mountSpecs[cm.Destination] {
  278. continue
  279. }
  280. if mp, exists := binds[cm.Destination]; exists {
  281. if needsUpdate(cm, mp) {
  282. cm.Spec = mp.Spec
  283. cm.Type = mp.Type
  284. }
  285. continue
  286. }
  287. if cm.Name != "" {
  288. if mp, exists := volumesFrom[cm.Destination]; exists {
  289. if needsUpdate(cm, &mp) {
  290. cm.Spec = mp.Spec
  291. cm.Type = mp.Type
  292. }
  293. continue
  294. }
  295. if cm.Type != "" {
  296. // probably specified via the hostconfig.Mounts
  297. continue
  298. }
  299. // anon volume
  300. cm.Type = mounttypes.TypeVolume
  301. cm.Spec.Type = mounttypes.TypeVolume
  302. } else {
  303. if cm.Type != "" {
  304. // already updated
  305. continue
  306. }
  307. cm.Type = mounttypes.TypeBind
  308. cm.Spec.Type = mounttypes.TypeBind
  309. cm.Spec.Source = cm.Source
  310. if cm.Propagation != "" {
  311. cm.Spec.BindOptions = &mounttypes.BindOptions{
  312. Propagation: cm.Propagation,
  313. }
  314. }
  315. }
  316. cm.Spec.Target = cm.Destination
  317. cm.Spec.ReadOnly = !cm.RW
  318. }
  319. }
  320. func (daemon *Daemon) traverseLocalVolumes(fn func(volume.Volume) error) error {
  321. localVolumeDriver, err := volumedrivers.GetDriver(volume.DefaultDriverName)
  322. if err != nil {
  323. return fmt.Errorf("can't retrieve local volume driver: %v", err)
  324. }
  325. vols, err := localVolumeDriver.List()
  326. if err != nil {
  327. return fmt.Errorf("can't retrieve local volumes: %v", err)
  328. }
  329. for _, v := range vols {
  330. name := v.Name()
  331. vol, err := daemon.volumes.Get(name)
  332. if err != nil {
  333. logrus.Warnf("failed to retrieve volume %s from store: %v", name, err)
  334. } else {
  335. // daemon.volumes.Get will return DetailedVolume
  336. v = vol
  337. }
  338. err = fn(v)
  339. if err != nil {
  340. return err
  341. }
  342. }
  343. return nil
  344. }