linux_parser.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429
  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. func (p *linuxParser) ReadWrite(mode string) bool {
  180. if !linuxValidMountMode(mode) {
  181. return false
  182. }
  183. for _, o := range strings.Split(mode, ",") {
  184. if o == "ro" {
  185. return false
  186. }
  187. }
  188. return true
  189. }
  190. func (p *linuxParser) ParseMountRaw(raw, volumeDriver string) (*MountPoint, error) {
  191. arr := strings.SplitN(raw, ":", 4)
  192. if arr[0] == "" {
  193. return nil, errInvalidSpec(raw)
  194. }
  195. var spec mount.Mount
  196. var mode string
  197. switch len(arr) {
  198. case 1:
  199. // Just a destination path in the container
  200. spec.Target = arr[0]
  201. case 2:
  202. if linuxValidMountMode(arr[1]) {
  203. // Destination + Mode is not a valid volume - volumes
  204. // cannot include a mode. e.g. /foo:rw
  205. return nil, errInvalidSpec(raw)
  206. }
  207. // Host Source Path or Name + Destination
  208. spec.Source = arr[0]
  209. spec.Target = arr[1]
  210. case 3:
  211. // HostSourcePath+DestinationPath+Mode
  212. spec.Source = arr[0]
  213. spec.Target = arr[1]
  214. mode = arr[2]
  215. default:
  216. return nil, errInvalidSpec(raw)
  217. }
  218. if !linuxValidMountMode(mode) {
  219. return nil, errInvalidMode(mode)
  220. }
  221. if path.IsAbs(spec.Source) {
  222. spec.Type = mount.TypeBind
  223. } else {
  224. spec.Type = mount.TypeVolume
  225. }
  226. spec.ReadOnly = !p.ReadWrite(mode)
  227. // cannot assume that if a volume driver is passed in that we should set it
  228. if volumeDriver != "" && spec.Type == mount.TypeVolume {
  229. spec.VolumeOptions = &mount.VolumeOptions{
  230. DriverConfig: &mount.Driver{Name: volumeDriver},
  231. }
  232. }
  233. if copyData, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  234. if spec.VolumeOptions == nil {
  235. spec.VolumeOptions = &mount.VolumeOptions{}
  236. }
  237. spec.VolumeOptions.NoCopy = !copyData
  238. }
  239. if linuxHasPropagation(mode) {
  240. spec.BindOptions = &mount.BindOptions{
  241. Propagation: linuxGetPropagation(mode),
  242. }
  243. }
  244. mp, err := p.parseMountSpec(spec, false)
  245. if mp != nil {
  246. mp.Mode = mode
  247. }
  248. if err != nil {
  249. err = fmt.Errorf("%v: %v", errInvalidSpec(raw), err)
  250. }
  251. return mp, err
  252. }
  253. func (p *linuxParser) ParseMountSpec(cfg mount.Mount) (*MountPoint, error) {
  254. return p.parseMountSpec(cfg, true)
  255. }
  256. func (p *linuxParser) parseMountSpec(cfg mount.Mount, validateBindSourceExists bool) (*MountPoint, error) {
  257. if err := p.validateMountConfigImpl(&cfg, validateBindSourceExists); err != nil {
  258. return nil, err
  259. }
  260. mp := &MountPoint{
  261. RW: !cfg.ReadOnly,
  262. Destination: path.Clean(filepath.ToSlash(cfg.Target)),
  263. Type: cfg.Type,
  264. Spec: cfg,
  265. }
  266. switch cfg.Type {
  267. case mount.TypeVolume:
  268. if cfg.Source == "" {
  269. mp.Name = stringid.GenerateRandomID()
  270. } else {
  271. mp.Name = cfg.Source
  272. }
  273. mp.CopyData = p.DefaultCopyMode()
  274. if cfg.VolumeOptions != nil {
  275. if cfg.VolumeOptions.DriverConfig != nil {
  276. mp.Driver = cfg.VolumeOptions.DriverConfig.Name
  277. }
  278. if cfg.VolumeOptions.NoCopy {
  279. mp.CopyData = false
  280. }
  281. }
  282. case mount.TypeBind:
  283. mp.Source = path.Clean(filepath.ToSlash(cfg.Source))
  284. if cfg.BindOptions != nil && len(cfg.BindOptions.Propagation) > 0 {
  285. mp.Propagation = cfg.BindOptions.Propagation
  286. } else {
  287. // If user did not specify a propagation mode, get
  288. // default propagation mode.
  289. mp.Propagation = linuxDefaultPropagationMode
  290. }
  291. case mount.TypeTmpfs:
  292. // NOP
  293. }
  294. return mp, nil
  295. }
  296. func (p *linuxParser) ParseVolumesFrom(spec string) (string, string, error) {
  297. if len(spec) == 0 {
  298. return "", "", fmt.Errorf("volumes-from specification cannot be an empty string")
  299. }
  300. id, mode, _ := strings.Cut(spec, ":")
  301. if mode == "" {
  302. return id, "rw", nil
  303. }
  304. if !linuxValidMountMode(mode) {
  305. return "", "", errInvalidMode(mode)
  306. }
  307. // For now don't allow propagation properties while importing
  308. // volumes from data container. These volumes will inherit
  309. // the same propagation property as of the original volume
  310. // in data container. This probably can be relaxed in future.
  311. if linuxHasPropagation(mode) {
  312. return "", "", errInvalidMode(mode)
  313. }
  314. // Do not allow copy modes on volumes-from
  315. if _, isSet := getCopyMode(mode, p.DefaultCopyMode()); isSet {
  316. return "", "", errInvalidMode(mode)
  317. }
  318. return id, mode, nil
  319. }
  320. func (p *linuxParser) DefaultPropagationMode() mount.Propagation {
  321. return linuxDefaultPropagationMode
  322. }
  323. func (p *linuxParser) ConvertTmpfsOptions(opt *mount.TmpfsOptions, readOnly bool) (string, error) {
  324. var rawOpts []string
  325. if readOnly {
  326. rawOpts = append(rawOpts, "ro")
  327. }
  328. if opt != nil && opt.Mode != 0 {
  329. rawOpts = append(rawOpts, fmt.Sprintf("mode=%o", opt.Mode))
  330. }
  331. if opt != nil && opt.SizeBytes != 0 {
  332. // calculate suffix here, making this linux specific, but that is
  333. // okay, since API is that way anyways.
  334. // we do this by finding the suffix that divides evenly into the
  335. // value, returning the value itself, with no suffix, if it fails.
  336. //
  337. // For the most part, we don't enforce any semantic to this values.
  338. // The operating system will usually align this and enforce minimum
  339. // and maximums.
  340. var (
  341. size = opt.SizeBytes
  342. suffix string
  343. )
  344. for _, r := range []struct {
  345. suffix string
  346. divisor int64
  347. }{
  348. {"g", 1 << 30},
  349. {"m", 1 << 20},
  350. {"k", 1 << 10},
  351. } {
  352. if size%r.divisor == 0 {
  353. size = size / r.divisor
  354. suffix = r.suffix
  355. break
  356. }
  357. }
  358. rawOpts = append(rawOpts, fmt.Sprintf("size=%d%s", size, suffix))
  359. }
  360. return strings.Join(rawOpts, ","), nil
  361. }
  362. func (p *linuxParser) DefaultCopyMode() bool {
  363. return true
  364. }
  365. func (p *linuxParser) ValidateVolumeName(name string) error {
  366. return nil
  367. }
  368. func (p *linuxParser) IsBackwardCompatible(m *MountPoint) bool {
  369. return len(m.Source) > 0 || m.Driver == volume.DefaultDriverName
  370. }
  371. func (p *linuxParser) ValidateTmpfsMountDestination(dest string) error {
  372. if err := linuxValidateNotRoot(dest); err != nil {
  373. return err
  374. }
  375. return linuxValidateAbsolute(dest)
  376. }