linux_parser.go 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  1. package mounts // import "github.com/docker/docker/volume/mounts"
  2. import (
  3. "errors"
  4. "fmt"
  5. "path"
  6. "path/filepath"
  7. "strings"
  8. "github.com/docker/docker/api/types/mount"
  9. "github.com/docker/docker/pkg/stringid"
  10. "github.com/docker/docker/volume"
  11. )
  12. // NewLinuxParser creates a parser with Linux semantics.
  13. func NewLinuxParser() Parser {
  14. return &linuxParser{
  15. fi: defaultFileInfoProvider{},
  16. }
  17. }
  18. type linuxParser struct {
  19. fi fileInfoProvider
  20. }
  21. func linuxValidateNotRoot(p string) error {
  22. p = path.Clean(strings.ReplaceAll(p, `\`, `/`))
  23. if p == "/" {
  24. return ErrVolumeTargetIsRoot
  25. }
  26. return nil
  27. }
  28. func linuxValidateAbsolute(p string) error {
  29. p = strings.ReplaceAll(p, `\`, `/`)
  30. if path.IsAbs(p) {
  31. return nil
  32. }
  33. return fmt.Errorf("invalid mount path: '%s' mount path must be absolute", p)
  34. }
  35. func (p *linuxParser) ValidateMountConfig(mnt *mount.Mount) error {
  36. // there was something looking like a bug in existing codebase:
  37. // - validateMountConfig on linux was called with options skipping bind source existence when calling ParseMountRaw
  38. // - but not when calling ParseMountSpec directly... nor when the unit test called it directly
  39. return p.validateMountConfigImpl(mnt, true)
  40. }
  41. func (p *linuxParser) validateMountConfigImpl(mnt *mount.Mount, validateBindSourceExists bool) error {
  42. if len(mnt.Target) == 0 {
  43. return &errMountConfig{mnt, errMissingField("Target")}
  44. }
  45. if err := linuxValidateNotRoot(mnt.Target); err != nil {
  46. return &errMountConfig{mnt, err}
  47. }
  48. if err := linuxValidateAbsolute(mnt.Target); err != nil {
  49. return &errMountConfig{mnt, err}
  50. }
  51. switch mnt.Type {
  52. case mount.TypeBind:
  53. if len(mnt.Source) == 0 {
  54. return &errMountConfig{mnt, errMissingField("Source")}
  55. }
  56. // Don't error out just because the propagation mode is not supported on the platform
  57. if opts := mnt.BindOptions; opts != nil {
  58. if len(opts.Propagation) > 0 && len(linuxPropagationModes) > 0 {
  59. if _, ok := linuxPropagationModes[opts.Propagation]; !ok {
  60. return &errMountConfig{mnt, fmt.Errorf("invalid propagation mode: %s", opts.Propagation)}
  61. }
  62. }
  63. }
  64. if mnt.VolumeOptions != nil {
  65. return &errMountConfig{mnt, errExtraField("VolumeOptions")}
  66. }
  67. if err := linuxValidateAbsolute(mnt.Source); err != nil {
  68. return &errMountConfig{mnt, err}
  69. }
  70. if validateBindSourceExists {
  71. exists, _, err := p.fi.fileInfo(mnt.Source)
  72. if err != nil {
  73. return &errMountConfig{mnt, err}
  74. }
  75. if !exists {
  76. return &errMountConfig{mnt, errBindSourceDoesNotExist(mnt.Source)}
  77. }
  78. }
  79. case mount.TypeVolume:
  80. if mnt.BindOptions != nil {
  81. return &errMountConfig{mnt, errExtraField("BindOptions")}
  82. }
  83. if len(mnt.Source) == 0 && mnt.ReadOnly {
  84. return &errMountConfig{mnt, fmt.Errorf("must not set ReadOnly mode when using anonymous volumes")}
  85. }
  86. case mount.TypeTmpfs:
  87. if mnt.BindOptions != nil {
  88. return &errMountConfig{mnt, errExtraField("BindOptions")}
  89. }
  90. if len(mnt.Source) != 0 {
  91. return &errMountConfig{mnt, errExtraField("Source")}
  92. }
  93. if _, err := p.ConvertTmpfsOptions(mnt.TmpfsOptions, mnt.ReadOnly); err != nil {
  94. return &errMountConfig{mnt, err}
  95. }
  96. default:
  97. return &errMountConfig{mnt, errors.New("mount type unknown")}
  98. }
  99. return nil
  100. }
  101. // label modes
  102. var linuxLabelModes = map[string]bool{
  103. "Z": true,
  104. "z": true,
  105. }
  106. // consistency modes
  107. var linuxConsistencyModes = map[mount.Consistency]bool{
  108. mount.ConsistencyFull: true,
  109. mount.ConsistencyCached: true,
  110. mount.ConsistencyDelegated: true,
  111. }
  112. var linuxPropagationModes = map[mount.Propagation]bool{
  113. mount.PropagationPrivate: true,
  114. mount.PropagationRPrivate: true,
  115. mount.PropagationSlave: true,
  116. mount.PropagationRSlave: true,
  117. mount.PropagationShared: true,
  118. mount.PropagationRShared: true,
  119. }
  120. const linuxDefaultPropagationMode = mount.PropagationRPrivate
  121. func linuxGetPropagation(mode string) mount.Propagation {
  122. for _, o := range strings.Split(mode, ",") {
  123. prop := mount.Propagation(o)
  124. if linuxPropagationModes[prop] {
  125. return prop
  126. }
  127. }
  128. return linuxDefaultPropagationMode
  129. }
  130. func linuxHasPropagation(mode string) bool {
  131. for _, o := range strings.Split(mode, ",") {
  132. if linuxPropagationModes[mount.Propagation(o)] {
  133. return true
  134. }
  135. }
  136. return false
  137. }
  138. func linuxValidMountMode(mode string) bool {
  139. if mode == "" {
  140. return true
  141. }
  142. rwModeCount := 0
  143. labelModeCount := 0
  144. propagationModeCount := 0
  145. copyModeCount := 0
  146. consistencyModeCount := 0
  147. for _, o := range strings.Split(mode, ",") {
  148. switch {
  149. case rwModes[o]:
  150. rwModeCount++
  151. case linuxLabelModes[o]:
  152. labelModeCount++
  153. case linuxPropagationModes[mount.Propagation(o)]:
  154. propagationModeCount++
  155. case copyModeExists(o):
  156. copyModeCount++
  157. case linuxConsistencyModes[mount.Consistency(o)]:
  158. consistencyModeCount++
  159. default:
  160. return false
  161. }
  162. }
  163. // Only one string for each mode is allowed.
  164. if rwModeCount > 1 || labelModeCount > 1 || propagationModeCount > 1 || copyModeCount > 1 || consistencyModeCount > 1 {
  165. return false
  166. }
  167. return true
  168. }
  169. func (p *linuxParser) ReadWrite(mode string) bool {
  170. if !linuxValidMountMode(mode) {
  171. return false
  172. }
  173. for _, o := range strings.Split(mode, ",") {
  174. if o == "ro" {
  175. return false
  176. }
  177. }
  178. return true
  179. }
  180. func (p *linuxParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
  181. arr := strings.SplitN(raw, ":", 4)
  182. if arr[0] == "" {
  183. return nil, errInvalidSpec(raw)
  184. }
  185. var spec mount.Mount
  186. var mode string
  187. switch len(arr) {
  188. case 1:
  189. // Just a destination path in the container
  190. spec.Target = arr[0]
  191. case 2:
  192. if linuxValidMountMode(arr[1]) {
  193. // Destination + Mode is not a valid volume - volumes
  194. // cannot include a mode. e.g. /foo:rw
  195. return nil, errInvalidSpec(raw)
  196. }
  197. // Host Source Path or Name + Destination
  198. spec.Source = arr[0]
  199. spec.Target = arr[1]
  200. case 3:
  201. // HostSourcePath+DestinationPath+Mode
  202. spec.Source = arr[0]
  203. spec.Target = arr[1]
  204. mode = arr[2]
  205. default:
  206. return nil, errInvalidSpec(raw)
  207. }
  208. if !linuxValidMountMode(mode) {
  209. return nil, errInvalidMode(mode)
  210. }
  211. if path.IsAbs(spec.Source) {
  212. spec.Type = mount.TypeBind
  213. } else {
  214. spec.Type = mount.TypeVolume
  215. }
  216. spec.ReadOnly = !p.ReadWrite(mode)
  217. // cannot assume that if a volume driver is passed in that we should set it
  218. if volumeDriver != "" && spec.Type == mount.TypeVolume {
  219. spec.VolumeOptions = &mount.VolumeOptions{
  220. DriverConfig: &mount.Driver{Name: volumeDriver},
  221. }
  222. }
  223. if copyData, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  224. if spec.VolumeOptions == nil {
  225. spec.VolumeOptions = &mount.VolumeOptions{}
  226. }
  227. spec.VolumeOptions.NoCopy = !copyData
  228. }
  229. if linuxHasPropagation(mode) {
  230. spec.BindOptions = &mount.BindOptions{
  231. Propagation: linuxGetPropagation(mode),
  232. }
  233. }
  234. mp, err := p.parseMountSpec(spec, false)
  235. if mp != nil {
  236. mp.Mode = mode
  237. }
  238. if err != nil {
  239. err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
  240. }
  241. return mp, err
  242. }
  243. func (p *linuxParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) {
  244. return p.parseMountSpec(cfg, true)
  245. }
  246. func (p *linuxParser) parseMountSpec(cfg mount.Mount, validateBindSourceExists bool) (*MountPoint, error) {
  247. if err := p.validateMountConfigImpl(&cfg, validateBindSourceExists); err != nil {
  248. return nil, err
  249. }
  250. mp := &MountPoint{
  251. RW: !cfg.ReadOnly,
  252. Destination: path.Clean(filepath.ToSlash(cfg.Target)),
  253. Type: cfg.Type,
  254. Spec: cfg,
  255. }
  256. switch cfg.Type {
  257. case mount.TypeVolume:
  258. if cfg.Source == "" {
  259. mp.Name = stringid.GenerateRandomID()
  260. } else {
  261. mp.Name = cfg.Source
  262. }
  263. mp.CopyData = p.DefaultCopyMode()
  264. if cfg.VolumeOptions != nil {
  265. if cfg.VolumeOptions.DriverConfig != nil {
  266. mp.Driver = cfg.VolumeOptions.DriverConfig.Name
  267. }
  268. if cfg.VolumeOptions.NoCopy {
  269. mp.CopyData = false
  270. }
  271. }
  272. case mount.TypeBind:
  273. mp.Source = path.Clean(filepath.ToSlash(cfg.Source))
  274. if cfg.BindOptions != nil && len(cfg.BindOptions.Propagation) > 0 {
  275. mp.Propagation = cfg.BindOptions.Propagation
  276. } else {
  277. // If user did not specify a propagation mode, get
  278. // default propagation mode.
  279. mp.Propagation = linuxDefaultPropagationMode
  280. }
  281. case mount.TypeTmpfs:
  282. // NOP
  283. }
  284. return mp, nil
  285. }
  286. func (p *linuxParser) ParseVolumesFrom(spec string) (string, string, error) {
  287. if len(spec) == 0 {
  288. return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
  289. }
  290. id, mode, _ := strings.Cut(spec, ":")
  291. if mode == "" {
  292. return id, "rw", nil
  293. }
  294. if !linuxValidMountMode(mode) {
  295. return "", "", errInvalidMode(mode)
  296. }
  297. // For now don't allow propagation properties while importing
  298. // volumes from data container. These volumes will inherit
  299. // the same propagation property as of the original volume
  300. // in data container. This probably can be relaxed in future.
  301. if linuxHasPropagation(mode) {
  302. return "", "", errInvalidMode(mode)
  303. }
  304. // Do not allow copy modes on volumes-from
  305. if _, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  306. return "", "", errInvalidMode(mode)
  307. }
  308. return id, mode, nil
  309. }
  310. func (p *linuxParser) DefaultPropagationMode() mount.Propagation {
  311. return linuxDefaultPropagationMode
  312. }
  313. func (p *linuxParser) ConvertTmpfsOptions(opt *mount.TmpfsOptions, readOnly bool) (string, error) {
  314. var rawOpts []string
  315. if readOnly {
  316. rawOpts = append(rawOpts, "ro")
  317. }
  318. if opt != nil && opt.Mode != 0 {
  319. rawOpts = append(rawOpts, fmt.Sprintf("mode=%o", opt.Mode))
  320. }
  321. if opt != nil && opt.SizeBytes != 0 {
  322. // calculate suffix here, making this linux specific, but that is
  323. // okay, since API is that way anyways.
  324. // we do this by finding the suffix that divides evenly into the
  325. // value, returning the value itself, with no suffix, if it fails.
  326. //
  327. // For the most part, we don't enforce any semantic to this values.
  328. // The operating system will usually align this and enforce minimum
  329. // and maximums.
  330. var (
  331. size = opt.SizeBytes
  332. suffix string
  333. )
  334. for _, r := range []struct {
  335. suffix string
  336. divisor int64
  337. }{
  338. {"g", 1 << 30},
  339. {"m", 1 << 20},
  340. {"k", 1 << 10},
  341. } {
  342. if size%r.divisor == 0 {
  343. size = size / r.divisor
  344. suffix = r.suffix
  345. break
  346. }
  347. }
  348. rawOpts = append(rawOpts, fmt.Sprintf("size=%d%s", size, suffix))
  349. }
  350. return strings.Join(rawOpts, ","), nil
  351. }
  352. func (p *linuxParser) DefaultCopyMode() bool {
  353. return true
  354. }
  355. func (p *linuxParser) ValidateVolumeName(name string) error {
  356. return nil
  357. }
  358. func (p *linuxParser) IsBackwardCompatible(m *MountPoint) bool {
  359. return len(m.Source) > 0 || m.Driver == volume.DefaultDriverName
  360. }
  361. func (p *linuxParser) ValidateTmpfsMountDestination(dest string) error {
  362. if err := linuxValidateNotRoot(dest); err != nil {
  363. return err
  364. }
  365. return linuxValidateAbsolute(dest)
  366. }