volumes.go 11 KB

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