linux_parser.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454
  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. createMountpoint := mnt.BindOptions != nil && mnt.BindOptions.CreateMountpoint
  76. if !exists && !createMountpoint {
  77. return &errMountConfig{mnt, errBindSourceDoesNotExist(mnt.Source)}
  78. }
  79. }
  80. case mount.TypeVolume:
  81. if mnt.BindOptions != nil {
  82. return &errMountConfig{mnt, errExtraField("BindOptions")}
  83. }
  84. anonymousVolume := len(mnt.Source) == 0
  85. if mnt.VolumeOptions != nil && mnt.VolumeOptions.Subpath != "" {
  86. if anonymousVolume {
  87. return &errMountConfig{mnt, errAnonymousVolumeWithSubpath}
  88. }
  89. if !filepath.IsLocal(mnt.VolumeOptions.Subpath) {
  90. return &errMountConfig{mnt, errInvalidSubpath}
  91. }
  92. }
  93. if mnt.ReadOnly && anonymousVolume {
  94. return &errMountConfig{mnt, fmt.Errorf("must not set ReadOnly mode when using anonymous volumes")}
  95. }
  96. case mount.TypeTmpfs:
  97. if mnt.BindOptions != nil {
  98. return &errMountConfig{mnt, errExtraField("BindOptions")}
  99. }
  100. if len(mnt.Source) != 0 {
  101. return &errMountConfig{mnt, errExtraField("Source")}
  102. }
  103. if _, err := p.ConvertTmpfsOptions(mnt.TmpfsOptions, mnt.ReadOnly); err != nil {
  104. return &errMountConfig{mnt, err}
  105. }
  106. default:
  107. return &errMountConfig{mnt, errors.New("mount type unknown")}
  108. }
  109. return nil
  110. }
  111. // label modes
  112. var linuxLabelModes = map[string]bool{
  113. "Z": true,
  114. "z": true,
  115. }
  116. // consistency modes
  117. var linuxConsistencyModes = map[mount.Consistency]bool{
  118. mount.ConsistencyFull: true,
  119. mount.ConsistencyCached: true,
  120. mount.ConsistencyDelegated: true,
  121. }
  122. var linuxPropagationModes = map[mount.Propagation]bool{
  123. mount.PropagationPrivate: true,
  124. mount.PropagationRPrivate: true,
  125. mount.PropagationSlave: true,
  126. mount.PropagationRSlave: true,
  127. mount.PropagationShared: true,
  128. mount.PropagationRShared: true,
  129. }
  130. const linuxDefaultPropagationMode = mount.PropagationRPrivate
  131. func linuxGetPropagation(mode string) mount.Propagation {
  132. for _, o := range strings.Split(mode, ",") {
  133. prop := mount.Propagation(o)
  134. if linuxPropagationModes[prop] {
  135. return prop
  136. }
  137. }
  138. return linuxDefaultPropagationMode
  139. }
  140. func linuxHasPropagation(mode string) bool {
  141. for _, o := range strings.Split(mode, ",") {
  142. if linuxPropagationModes[mount.Propagation(o)] {
  143. return true
  144. }
  145. }
  146. return false
  147. }
  148. func linuxValidMountMode(mode string) bool {
  149. if mode == "" {
  150. return true
  151. }
  152. rwModeCount := 0
  153. labelModeCount := 0
  154. propagationModeCount := 0
  155. copyModeCount := 0
  156. consistencyModeCount := 0
  157. for _, o := range strings.Split(mode, ",") {
  158. switch {
  159. case rwModes[o]:
  160. rwModeCount++
  161. case linuxLabelModes[o]:
  162. labelModeCount++
  163. case linuxPropagationModes[mount.Propagation(o)]:
  164. propagationModeCount++
  165. case copyModeExists(o):
  166. copyModeCount++
  167. case linuxConsistencyModes[mount.Consistency(o)]:
  168. consistencyModeCount++
  169. default:
  170. return false
  171. }
  172. }
  173. // Only one string for each mode is allowed.
  174. if rwModeCount > 1 || labelModeCount > 1 || propagationModeCount > 1 || copyModeCount > 1 || consistencyModeCount > 1 {
  175. return false
  176. }
  177. return true
  178. }
  179. var validTmpfsOptions = map[string]bool{
  180. "exec": true,
  181. "noexec": true,
  182. }
  183. func validateTmpfsOptions(rawOptions string) ([]string, error) {
  184. var options []string
  185. for _, opt := range strings.Split(rawOptions, ",") {
  186. if _, ok := validTmpfsOptions[opt]; !ok {
  187. return nil, errors.New("invalid option: " + opt)
  188. }
  189. options = append(options, opt)
  190. }
  191. return options, nil
  192. }
  193. func (p *linuxParser) ReadWrite(mode string) bool {
  194. if !linuxValidMountMode(mode) {
  195. return false
  196. }
  197. for _, o := range strings.Split(mode, ",") {
  198. if o == "ro" {
  199. return false
  200. }
  201. }
  202. return true
  203. }
  204. func (p *linuxParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
  205. arr := strings.SplitN(raw, ":", 4)
  206. if arr[0] == "" {
  207. return nil, errInvalidSpec(raw)
  208. }
  209. var spec mount.Mount
  210. var mode string
  211. switch len(arr) {
  212. case 1:
  213. // Just a destination path in the container
  214. spec.Target = arr[0]
  215. case 2:
  216. if linuxValidMountMode(arr[1]) {
  217. // Destination + Mode is not a valid volume - volumes
  218. // cannot include a mode. e.g. /foo:rw
  219. return nil, errInvalidSpec(raw)
  220. }
  221. // Host Source Path or Name + Destination
  222. spec.Source = arr[0]
  223. spec.Target = arr[1]
  224. case 3:
  225. // HostSourcePath+DestinationPath+Mode
  226. spec.Source = arr[0]
  227. spec.Target = arr[1]
  228. mode = arr[2]
  229. default:
  230. return nil, errInvalidSpec(raw)
  231. }
  232. if !linuxValidMountMode(mode) {
  233. return nil, errInvalidMode(mode)
  234. }
  235. if path.IsAbs(spec.Source) {
  236. spec.Type = mount.TypeBind
  237. } else {
  238. spec.Type = mount.TypeVolume
  239. }
  240. spec.ReadOnly = !p.ReadWrite(mode)
  241. // cannot assume that if a volume driver is passed in that we should set it
  242. if volumeDriver != "" && spec.Type == mount.TypeVolume {
  243. spec.VolumeOptions = &mount.VolumeOptions{
  244. DriverConfig: &mount.Driver{Name: volumeDriver},
  245. }
  246. }
  247. if copyData, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  248. if spec.VolumeOptions == nil {
  249. spec.VolumeOptions = &mount.VolumeOptions{}
  250. }
  251. spec.VolumeOptions.NoCopy = !copyData
  252. }
  253. if linuxHasPropagation(mode) {
  254. spec.BindOptions = &mount.BindOptions{
  255. Propagation: linuxGetPropagation(mode),
  256. }
  257. }
  258. mp, err := p.parseMountSpec(spec, false)
  259. if mp != nil {
  260. mp.Mode = mode
  261. }
  262. if err != nil {
  263. err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
  264. }
  265. return mp, err
  266. }
  267. func (p *linuxParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) {
  268. return p.parseMountSpec(cfg, true)
  269. }
  270. func (p *linuxParser) parseMountSpec(cfg mount.Mount, validateBindSourceExists bool) (*MountPoint, error) {
  271. if err := p.validateMountConfigImpl(&cfg, validateBindSourceExists); err != nil {
  272. return nil, err
  273. }
  274. mp := &MountPoint{
  275. RW: !cfg.ReadOnly,
  276. Destination: path.Clean(filepath.ToSlash(cfg.Target)),
  277. Type: cfg.Type,
  278. Spec: cfg,
  279. }
  280. switch cfg.Type {
  281. case mount.TypeVolume:
  282. if cfg.Source == "" {
  283. mp.Name = stringid.GenerateRandomID()
  284. } else {
  285. mp.Name = cfg.Source
  286. }
  287. mp.CopyData = p.DefaultCopyMode()
  288. if cfg.VolumeOptions != nil {
  289. if cfg.VolumeOptions.DriverConfig != nil {
  290. mp.Driver = cfg.VolumeOptions.DriverConfig.Name
  291. }
  292. if cfg.VolumeOptions.NoCopy {
  293. mp.CopyData = false
  294. }
  295. }
  296. case mount.TypeBind:
  297. mp.Source = path.Clean(filepath.ToSlash(cfg.Source))
  298. if cfg.BindOptions != nil && len(cfg.BindOptions.Propagation) > 0 {
  299. mp.Propagation = cfg.BindOptions.Propagation
  300. } else {
  301. // If user did not specify a propagation mode, get
  302. // default propagation mode.
  303. mp.Propagation = linuxDefaultPropagationMode
  304. }
  305. case mount.TypeTmpfs:
  306. // NOP
  307. }
  308. return mp, nil
  309. }
  310. func (p *linuxParser) ParseVolumesFrom(spec string) (string, string, error) {
  311. if len(spec) == 0 {
  312. return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
  313. }
  314. id, mode, _ := strings.Cut(spec, ":")
  315. if mode == "" {
  316. return id, "rw", nil
  317. }
  318. if !linuxValidMountMode(mode) {
  319. return "", "", errInvalidMode(mode)
  320. }
  321. // For now don't allow propagation properties while importing
  322. // volumes from data container. These volumes will inherit
  323. // the same propagation property as of the original volume
  324. // in data container. This probably can be relaxed in future.
  325. if linuxHasPropagation(mode) {
  326. return "", "", errInvalidMode(mode)
  327. }
  328. // Do not allow copy modes on volumes-from
  329. if _, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  330. return "", "", errInvalidMode(mode)
  331. }
  332. return id, mode, nil
  333. }
  334. func (p *linuxParser) DefaultPropagationMode() mount.Propagation {
  335. return linuxDefaultPropagationMode
  336. }
  337. func (p *linuxParser) ConvertTmpfsOptions(opt *mount.TmpfsOptions, readOnly bool) (string, error) {
  338. var rawOpts []string
  339. if readOnly {
  340. rawOpts = append(rawOpts, "ro")
  341. }
  342. if opt != nil && opt.Mode != 0 {
  343. rawOpts = append(rawOpts, fmt.Sprintf("mode=%o", opt.Mode))
  344. }
  345. if opt != nil && opt.SizeBytes != 0 {
  346. // calculate suffix here, making this linux specific, but that is
  347. // okay, since API is that way anyways.
  348. // we do this by finding the suffix that divides evenly into the
  349. // value, returning the value itself, with no suffix, if it fails.
  350. //
  351. // For the most part, we don't enforce any semantic to this values.
  352. // The operating system will usually align this and enforce minimum
  353. // and maximums.
  354. var (
  355. size = opt.SizeBytes
  356. suffix string
  357. )
  358. for _, r := range []struct {
  359. suffix string
  360. divisor int64
  361. }{
  362. {"g", 1 << 30},
  363. {"m", 1 << 20},
  364. {"k", 1 << 10},
  365. } {
  366. if size%r.divisor == 0 {
  367. size = size / r.divisor
  368. suffix = r.suffix
  369. break
  370. }
  371. }
  372. rawOpts = append(rawOpts, fmt.Sprintf("size=%d%s", size, suffix))
  373. }
  374. if opt != nil && len(opt.Options) > 0 {
  375. tmpfsOpts, err := validateTmpfsOptions(opt.Options)
  376. if err != nil {
  377. return "", err
  378. }
  379. rawOpts = append(rawOpts, tmpfsOpts...)
  380. }
  381. return strings.Join(rawOpts, ","), nil
  382. }
  383. func (p *linuxParser) DefaultCopyMode() bool {
  384. return true
  385. }
  386. func (p *linuxParser) ValidateVolumeName(name string) error {
  387. return nil
  388. }
  389. func (p *linuxParser) IsBackwardCompatible(m *MountPoint) bool {
  390. return len(m.Source) > 0 || m.Driver == volume.DefaultDriverName
  391. }
  392. func (p *linuxParser) ValidateTmpfsMountDestination(dest string) error {
  393. if err := linuxValidateNotRoot(dest); err != nil {
  394. return err
  395. }
  396. return linuxValidateAbsolute(dest)
  397. }